You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
2.0 KiB

  1. package utils
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "net/smtp"
  6. "strings"
  7. "gin-vue-admin/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(subject string, body string) error {
  16. to := strings.Split(global.GVA_CONFIG.Email.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.GVA_CONFIG.Email.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.GVA_CONFIG.Email.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.GVA_CONFIG.Email.From
  47. nickname := global.GVA_CONFIG.Email.Nickname
  48. secret := global.GVA_CONFIG.Email.Secret
  49. host := global.GVA_CONFIG.Email.Host
  50. port := global.GVA_CONFIG.Email.Port
  51. isSSL := global.GVA_CONFIG.Email.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. }