driver_smtp.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package mail
  2. // Installation
  3. // go get github.com/jordan-wright/email
  4. // Note: Version > 1 of this library requires Go v1.5 or above.
  5. // If you need compatibility with previous Go versions, you can use the previous package at gopkg.in/jordan-wright/email.v1
  6. // Sending email using Gmail
  7. //
  8. // e := email.NewEmail()
  9. // e.From = "Jordan Wright <test@gmail.com>"
  10. // e.To = []string{"test@example.com"}
  11. // e.Bcc = []string{"test_bcc@example.com"}
  12. // e.Cc = []string{"test_cc@example.com"}
  13. // e.Subject = "Awesome Subject"
  14. // e.Text = []byte("Text Body is, of course, supported!")
  15. // e.HTML = []byte("<h1>Fancy HTML is supported, too!</h1>")
  16. // e.Send("smtp.gmail.com:587", smtp.PlainAuth("", "test@gmail.com", "password123", "smtp.gmail.com"))
  17. import (
  18. "fmt"
  19. "net/smtp"
  20. emailPKG "github.com/jordan-wright/email"
  21. "github.com/runningwater/gohub/pkg/logger"
  22. )
  23. // SMTP 实现 email.Driver 接口
  24. // 使用 github.com/jordan-wright/email 库实现 SMTP 协议邮件发送
  25. type SMTP struct{}
  26. // Send 发送邮件
  27. // 参数 config 需包含以下配置项:
  28. //
  29. // host - SMTP 服务器地址
  30. // port - SMTP 端口
  31. // username - 认证用户名
  32. // password - 认证密码
  33. //
  34. // 返回 bool 表示邮件是否成功投递到服务器
  35. func (s *SMTP) Send(email Email, config map[string]string) bool {
  36. // 实现发送邮件的逻辑
  37. e := emailPKG.NewEmail()
  38. e.From = fmt.Sprintf("%s <%s>", email.From.Name, email.From.Address)
  39. e.To = email.To
  40. e.Bcc = email.Bcc
  41. e.Cc = email.Cc
  42. e.Subject = email.Subject
  43. e.Text = email.Text
  44. e.HTML = email.HTML
  45. logger.DebugJSON("发送邮件", "发送详情", e)
  46. if err := e.Send(
  47. fmt.Sprintf("%v:%v", config["host"], config["port"]),
  48. smtp.PlainAuth(
  49. "",
  50. config["username"],
  51. config["password"],
  52. config["host"],
  53. ),
  54. ); err != nil {
  55. logger.ErrorString("发送邮件", "发送邮件失败", err.Error())
  56. return false
  57. }
  58. // 成功时记录简略日志,避免泄露敏感内容
  59. logger.DebugString("发送邮件", "投递状态", "服务器已接收邮件")
  60. return true
  61. }