smtptest.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // Copyright (C) 2019-2023 Nicola Murino
  2. //
  3. // This program is free software: you can redistribute it and/or modify
  4. // it under the terms of the GNU Affero General Public License as published
  5. // by the Free Software Foundation, version 3.
  6. //
  7. // This program is distributed in the hope that it will be useful,
  8. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. // GNU Affero General Public License for more details.
  11. //
  12. // You should have received a copy of the GNU Affero General Public License
  13. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. package cmd
  15. import (
  16. "os"
  17. "github.com/rs/zerolog"
  18. "github.com/spf13/cobra"
  19. "github.com/drakkan/sftpgo/v2/internal/config"
  20. "github.com/drakkan/sftpgo/v2/internal/logger"
  21. "github.com/drakkan/sftpgo/v2/internal/smtp"
  22. "github.com/drakkan/sftpgo/v2/internal/util"
  23. )
  24. var (
  25. smtpTestRecipient string
  26. smtpTestCmd = &cobra.Command{
  27. Use: "smtptest",
  28. Short: "Test the SMTP configuration",
  29. Long: `SFTPGo will try to send a test email to the specified recipient.
  30. If the SMTP configuration is correct you should receive this email.`,
  31. Run: func(_ *cobra.Command, _ []string) {
  32. logger.DisableLogger()
  33. logger.EnableConsoleLogger(zerolog.DebugLevel)
  34. configDir = util.CleanDirInput(configDir)
  35. err := config.LoadConfig(configDir, configFile)
  36. if err != nil {
  37. logger.WarnToConsole("Unable to initialize data provider, config load error: %v", err)
  38. os.Exit(1)
  39. }
  40. smtpConfig := config.GetSMTPConfig()
  41. err = smtpConfig.Initialize(configDir)
  42. if err != nil {
  43. logger.ErrorToConsole("unable to initialize SMTP configuration: %v", err)
  44. os.Exit(1)
  45. }
  46. err = smtp.SendEmail([]string{smtpTestRecipient}, "SFTPGo - Testing Email Settings", "It appears your SFTPGo email is setup correctly!",
  47. smtp.EmailContentTypeTextPlain)
  48. if err != nil {
  49. logger.WarnToConsole("Error sending email: %v", err)
  50. os.Exit(1)
  51. }
  52. logger.InfoToConsole("No errors were reported while sending an email. Please check your inbox to make sure.")
  53. },
  54. }
  55. )
  56. func init() {
  57. addConfigFlags(smtpTestCmd)
  58. smtpTestCmd.Flags().StringVar(&smtpTestRecipient, "recipient", "", `email address to send the test e-mail to`)
  59. smtpTestCmd.MarkFlagRequired("recipient") //nolint:errcheck
  60. rootCmd.AddCommand(smtpTestCmd)
  61. }