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.

59 lines
1.4 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. func Email(subject string, body string) error {
  11. to := strings.Split(global.GVA_CONFIG.Email.To, ",")
  12. return send(to, subject, body)
  13. }
  14. // ErrorToEmail Error 发送邮件
  15. func ErrorToEmail(subject string, body string) error {
  16. to := strings.Split(global.GVA_CONFIG.Email.To, ",")
  17. if to[len(to)-1] == "" { // 判断切片的最后一个元素是否为空,为空则移除
  18. to = to[:len(to)-1]
  19. }
  20. return send(to, subject, body)
  21. }
  22. func EmailTest(subject string, body string) error {
  23. to := []string{global.GVA_CONFIG.Email.From}
  24. return send(to, subject, body)
  25. }
  26. func send(to []string, subject string, body string) error {
  27. from := global.GVA_CONFIG.Email.From
  28. nickname := global.GVA_CONFIG.Email.Nickname
  29. secret := global.GVA_CONFIG.Email.Secret
  30. host := global.GVA_CONFIG.Email.Host
  31. port := global.GVA_CONFIG.Email.Port
  32. isSSL := global.GVA_CONFIG.Email.IsSSL
  33. auth := smtp.PlainAuth("", from, secret, host)
  34. e := email.NewEmail()
  35. if nickname != "" {
  36. e.From = fmt.Sprintf("%s <%s>", nickname, from)
  37. } else {
  38. e.From = from
  39. }
  40. e.To = to
  41. e.Subject = subject
  42. e.HTML = []byte(body)
  43. var err error
  44. hostAddr := fmt.Sprintf("%s:%d", host, port)
  45. if isSSL {
  46. err = e.SendWithTLS(hostAddr, auth, &tls.Config{ServerName: host})
  47. } else {
  48. err = e.Send(hostAddr, auth)
  49. }
  50. return err
  51. }