email.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package utils
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "net/smtp"
  6. "strings"
  7. "github.com/flipped-aurora/gin-vue-admin/server/plugin/email/global"
  8. "github.com/jordan-wright/email"
  9. )
  10. //@author: [maplepie](https://github.com/maplepie)
  11. //@function: Email
  12. //@description: Email发送方法
  13. //@param: subject string, body string
  14. //@return: error
  15. func Email(To, subject string, body string) error {
  16. to := strings.Split(To, ",")
  17. return send(to, subject, body)
  18. }
  19. //@author: [SliverHorn](https://github.com/SliverHorn)
  20. //@function: ErrorToEmail
  21. //@description: 给email中间件错误发送邮件到指定邮箱
  22. //@param: subject string, body string
  23. //@return: error
  24. func ErrorToEmail(subject string, body string) error {
  25. to := strings.Split(global.GlobalConfig.To, ",")
  26. if to[len(to)-1] == "" { // 判断切片的最后一个元素是否为空,为空则移除
  27. to = to[:len(to)-1]
  28. }
  29. return send(to, subject, body)
  30. }
  31. //@author: [maplepie](https://github.com/maplepie)
  32. //@function: EmailTest
  33. //@description: Email测试方法
  34. //@param: subject string, body string
  35. //@return: error
  36. func EmailTest(subject string, body string) error {
  37. to := []string{global.GlobalConfig.From}
  38. return send(to, subject, body)
  39. }
  40. //@author: [maplepie](https://github.com/maplepie)
  41. //@function: send
  42. //@description: Email发送方法
  43. //@param: subject string, body string
  44. //@return: error
  45. func send(to []string, subject string, body string) error {
  46. from := global.GlobalConfig.From
  47. nickname := global.GlobalConfig.Nickname
  48. secret := global.GlobalConfig.Secret
  49. host := global.GlobalConfig.Host
  50. port := global.GlobalConfig.Port
  51. isSSL := global.GlobalConfig.IsSSL
  52. auth := smtp.PlainAuth("", from, secret, host)
  53. e := email.NewEmail()
  54. if nickname != "" {
  55. e.From = fmt.Sprintf("%s <%s>", nickname, from)
  56. } else {
  57. e.From = from
  58. }
  59. e.To = to
  60. e.Subject = subject
  61. e.HTML = []byte(body)
  62. var err error
  63. hostAddr := fmt.Sprintf("%s:%d", host, port)
  64. if isSSL {
  65. err = e.SendWithTLS(hostAddr, auth, &tls.Config{ServerName: host})
  66. } else {
  67. err = e.Send(hostAddr, auth)
  68. }
  69. return err
  70. }