smtp.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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 smtp provides supports for sending emails
  15. package smtp
  16. import (
  17. "bytes"
  18. "context"
  19. "errors"
  20. "fmt"
  21. "html/template"
  22. "path/filepath"
  23. "sync"
  24. "time"
  25. "github.com/wneessen/go-mail"
  26. "github.com/drakkan/sftpgo/v2/internal/dataprovider"
  27. "github.com/drakkan/sftpgo/v2/internal/logger"
  28. "github.com/drakkan/sftpgo/v2/internal/util"
  29. "github.com/drakkan/sftpgo/v2/internal/version"
  30. )
  31. const (
  32. logSender = "smtp"
  33. )
  34. // EmailContentType defines the support content types for email body
  35. type EmailContentType int
  36. // Supported email body content type
  37. const (
  38. EmailContentTypeTextPlain EmailContentType = iota
  39. EmailContentTypeTextHTML
  40. )
  41. const (
  42. templateEmailDir = "email"
  43. templatePasswordReset = "reset-password.html"
  44. templatePasswordExpiration = "password-expiration.html"
  45. dialTimeout = 10 * time.Second
  46. )
  47. var (
  48. config = &activeConfig{}
  49. initialConfig *Config
  50. emailTemplates = make(map[string]*template.Template)
  51. )
  52. type activeConfig struct {
  53. sync.RWMutex
  54. config *Config
  55. }
  56. func (c *activeConfig) isEnabled() bool {
  57. c.RLock()
  58. defer c.RUnlock()
  59. return c.config != nil && c.config.Host != ""
  60. }
  61. func (c *activeConfig) Set(cfg *dataprovider.SMTPConfigs) {
  62. var config *Config
  63. if cfg != nil {
  64. config = &Config{
  65. Host: cfg.Host,
  66. Port: cfg.Port,
  67. From: cfg.From,
  68. User: cfg.User,
  69. Password: cfg.Password.GetPayload(),
  70. AuthType: cfg.AuthType,
  71. Encryption: cfg.Encryption,
  72. Domain: cfg.Domain,
  73. }
  74. }
  75. c.Lock()
  76. defer c.Unlock()
  77. if config != nil && config.Host != "" {
  78. if c.config != nil && c.config.isEqual(config) {
  79. return
  80. }
  81. c.config = config
  82. logger.Info(logSender, "", "activated new config, server %s:%d", c.config.Host, c.config.Port)
  83. } else {
  84. logger.Debug(logSender, "", "activating initial config")
  85. c.config = initialConfig
  86. if c.config == nil || c.config.Host == "" {
  87. logger.Debug(logSender, "", "configuration disabled, email capabilities will not be available")
  88. }
  89. }
  90. }
  91. func (c *activeConfig) getSMTPClientAndMsg(to []string, subject, body string, contentType EmailContentType,
  92. attachments ...*mail.File,
  93. ) (*mail.Client, *mail.Msg, error) {
  94. c.RLock()
  95. defer c.RUnlock()
  96. if c.config == nil || c.config.Host == "" {
  97. return nil, nil, errors.New("smtp: not configured")
  98. }
  99. return c.config.getSMTPClientAndMsg(to, subject, body, contentType, attachments...)
  100. }
  101. func (c *activeConfig) sendEmail(to []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  102. client, msg, err := c.getSMTPClientAndMsg(to, subject, body, contentType, attachments...)
  103. if err != nil {
  104. return err
  105. }
  106. ctx, cancelFn := context.WithTimeout(context.Background(), dialTimeout)
  107. defer cancelFn()
  108. return client.DialAndSendWithContext(ctx, msg)
  109. }
  110. // IsEnabled returns true if an SMTP server is configured
  111. func IsEnabled() bool {
  112. return config.isEnabled()
  113. }
  114. // Activate sets the specified config as active
  115. func Activate(c *dataprovider.SMTPConfigs) {
  116. config.Set(c)
  117. }
  118. // Config defines the SMTP configuration to use to send emails
  119. type Config struct {
  120. // Location of SMTP email server. Leavy empty to disable email sending capabilities
  121. Host string `json:"host" mapstructure:"host"`
  122. // Port of SMTP email server
  123. Port int `json:"port" mapstructure:"port"`
  124. // From address, for example "SFTPGo <[email protected]>".
  125. // Many SMTP servers reject emails without a `From` header so, if not set,
  126. // SFTPGo will try to use the username as fallback, this may or may not be appropriate
  127. From string `json:"from" mapstructure:"from"`
  128. // SMTP username
  129. User string `json:"user" mapstructure:"user"`
  130. // SMTP password. Leaving both username and password empty the SMTP authentication
  131. // will be disabled
  132. Password string `json:"password" mapstructure:"password"`
  133. // 0 Plain
  134. // 1 Login
  135. // 2 CRAM-MD5
  136. AuthType int `json:"auth_type" mapstructure:"auth_type"`
  137. // 0 no encryption
  138. // 1 TLS
  139. // 2 start TLS
  140. Encryption int `json:"encryption" mapstructure:"encryption"`
  141. // Domain to use for HELO command, if empty localhost will be used
  142. Domain string `json:"domain" mapstructure:"domain"`
  143. // Path to the email templates. This can be an absolute path or a path relative to the config dir.
  144. // Templates are searched within a subdirectory named "email" in the specified path
  145. TemplatesPath string `json:"templates_path" mapstructure:"templates_path"`
  146. }
  147. func (c *Config) isEqual(other *Config) bool {
  148. if c.Host != other.Host {
  149. return false
  150. }
  151. if c.Port != other.Port {
  152. return false
  153. }
  154. if c.From != other.From {
  155. return false
  156. }
  157. if c.User != other.User {
  158. return false
  159. }
  160. if c.Password != other.Password {
  161. return false
  162. }
  163. if c.AuthType != other.AuthType {
  164. return false
  165. }
  166. if c.Encryption != other.Encryption {
  167. return false
  168. }
  169. if c.Domain != other.Domain {
  170. return false
  171. }
  172. return true
  173. }
  174. func (c *Config) validate() error {
  175. if c.Port <= 0 || c.Port > 65535 {
  176. return fmt.Errorf("smtp: invalid port %d", c.Port)
  177. }
  178. if c.AuthType < 0 || c.AuthType > 2 {
  179. return fmt.Errorf("smtp: invalid auth type %d", c.AuthType)
  180. }
  181. if c.Encryption < 0 || c.Encryption > 2 {
  182. return fmt.Errorf("smtp: invalid encryption %d", c.Encryption)
  183. }
  184. if c.From == "" && c.User == "" {
  185. return fmt.Errorf(`smtp: from address and user cannot both be empty`)
  186. }
  187. return nil
  188. }
  189. func (c *Config) loadTemplates(configDir string) error {
  190. if c.TemplatesPath == "" {
  191. logger.Debug(logSender, "", "templates path empty, using default")
  192. c.TemplatesPath = "templates"
  193. }
  194. templatesPath := util.FindSharedDataPath(c.TemplatesPath, configDir)
  195. if templatesPath == "" {
  196. return fmt.Errorf("smtp: invalid templates path %q", templatesPath)
  197. }
  198. loadTemplates(filepath.Join(templatesPath, templateEmailDir))
  199. return nil
  200. }
  201. // Initialize initialized and validates the SMTP configuration
  202. func (c *Config) Initialize(configDir string, isService bool) error {
  203. if !isService && c.Host == "" {
  204. if err := loadConfigFromProvider(); err != nil {
  205. return err
  206. }
  207. if !config.isEnabled() {
  208. return nil
  209. }
  210. return c.loadTemplates(configDir)
  211. }
  212. if err := c.loadTemplates(configDir); err != nil {
  213. return err
  214. }
  215. if c.Host == "" {
  216. return loadConfigFromProvider()
  217. }
  218. if err := c.validate(); err != nil {
  219. return err
  220. }
  221. initialConfig = c
  222. config.Set(nil)
  223. logger.Debug(logSender, "", "configuration successfully initialized, host: %q, port: %d, username: %q, auth: %d, encryption: %d, helo: %q",
  224. c.Host, c.Port, c.User, c.AuthType, c.Encryption, c.Domain)
  225. return loadConfigFromProvider()
  226. }
  227. func (c *Config) getMailClientOptions() []mail.Option {
  228. options := []mail.Option{mail.WithPort(c.Port), mail.WithoutNoop()}
  229. switch c.Encryption {
  230. case 1:
  231. options = append(options, mail.WithSSL())
  232. case 2:
  233. options = append(options, mail.WithTLSPolicy(mail.TLSMandatory))
  234. default:
  235. options = append(options, mail.WithTLSPolicy(mail.NoTLS))
  236. }
  237. if c.User != "" {
  238. options = append(options, mail.WithUsername(c.User))
  239. }
  240. if c.Password != "" {
  241. options = append(options, mail.WithPassword(c.Password))
  242. }
  243. if c.User != "" || c.Password != "" {
  244. switch c.AuthType {
  245. case 1:
  246. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthLogin))
  247. case 2:
  248. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthCramMD5))
  249. default:
  250. options = append(options, mail.WithSMTPAuth(mail.SMTPAuthPlain))
  251. }
  252. }
  253. if c.Domain != "" {
  254. options = append(options, mail.WithHELO(c.Domain))
  255. }
  256. return options
  257. }
  258. func (c *Config) getSMTPClientAndMsg(to []string, subject, body string, contentType EmailContentType,
  259. attachments ...*mail.File) (*mail.Client, *mail.Msg, error) {
  260. version := version.Get()
  261. msg := mail.NewMsg()
  262. msg.SetUserAgent(fmt.Sprintf("SFTPGo-%s-%s", version.Version, version.CommitHash))
  263. var from string
  264. if c.From != "" {
  265. from = c.From
  266. } else {
  267. from = c.User
  268. }
  269. if err := msg.From(from); err != nil {
  270. return nil, nil, fmt.Errorf("invalid from address: %w", err)
  271. }
  272. if err := msg.To(to...); err != nil {
  273. return nil, nil, err
  274. }
  275. msg.Subject(subject)
  276. msg.SetDate()
  277. msg.SetMessageID()
  278. msg.SetAttachements(attachments)
  279. switch contentType {
  280. case EmailContentTypeTextPlain:
  281. msg.SetBodyString(mail.TypeTextPlain, body)
  282. case EmailContentTypeTextHTML:
  283. msg.SetBodyString(mail.TypeTextHTML, body)
  284. default:
  285. return nil, nil, fmt.Errorf("smtp: unsupported body content type %v", contentType)
  286. }
  287. client, err := mail.NewClient(c.Host, c.getMailClientOptions()...)
  288. if err != nil {
  289. return nil, nil, fmt.Errorf("unable to create mail client: %w", err)
  290. }
  291. return client, msg, nil
  292. }
  293. // SendEmail tries to send an email using the specified parameters
  294. func (c *Config) SendEmail(to []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  295. client, msg, err := c.getSMTPClientAndMsg(to, subject, body, contentType, attachments...)
  296. if err != nil {
  297. return err
  298. }
  299. ctx, cancelFn := context.WithTimeout(context.Background(), dialTimeout)
  300. defer cancelFn()
  301. return client.DialAndSendWithContext(ctx, msg)
  302. }
  303. func loadTemplates(templatesPath string) {
  304. logger.Debug(logSender, "", "loading templates from %q", templatesPath)
  305. passwordResetPath := filepath.Join(templatesPath, templatePasswordReset)
  306. pwdResetTmpl := util.LoadTemplate(nil, passwordResetPath)
  307. passwordExpirationPath := filepath.Join(templatesPath, templatePasswordExpiration)
  308. pwdExpirationTmpl := util.LoadTemplate(nil, passwordExpirationPath)
  309. emailTemplates[templatePasswordReset] = pwdResetTmpl
  310. emailTemplates[templatePasswordExpiration] = pwdExpirationTmpl
  311. }
  312. // RenderPasswordResetTemplate executes the password reset template
  313. func RenderPasswordResetTemplate(buf *bytes.Buffer, data any) error {
  314. if !IsEnabled() {
  315. return errors.New("smtp: not configured")
  316. }
  317. return emailTemplates[templatePasswordReset].Execute(buf, data)
  318. }
  319. // RenderPasswordExpirationTemplate executes the password expiration template
  320. func RenderPasswordExpirationTemplate(buf *bytes.Buffer, data any) error {
  321. if !IsEnabled() {
  322. return errors.New("smtp: not configured")
  323. }
  324. return emailTemplates[templatePasswordExpiration].Execute(buf, data)
  325. }
  326. // SendEmail tries to send an email using the specified parameters.
  327. func SendEmail(to []string, subject, body string, contentType EmailContentType, attachments ...*mail.File) error {
  328. return config.sendEmail(to, subject, body, contentType, attachments...)
  329. }
  330. // ReloadProviderConf reloads the configuration from the provider
  331. // and apply it if different from the active one
  332. func ReloadProviderConf() {
  333. loadConfigFromProvider() //nolint:errcheck
  334. }
  335. func loadConfigFromProvider() error {
  336. configs, err := dataprovider.GetConfigs()
  337. if err != nil {
  338. logger.Error(logSender, "", "unable to load config from provider: %v", err)
  339. return fmt.Errorf("smtp: unable to load config from provider: %w", err)
  340. }
  341. configs.SetNilsToEmpty()
  342. if err := configs.SMTP.Password.TryDecrypt(); err != nil {
  343. logger.Error(logSender, "", "unable to decrypt password: %v", err)
  344. return fmt.Errorf("smtp: unable to decrypt password: %w", err)
  345. }
  346. config.Set(configs.SMTP)
  347. return nil
  348. }