email.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package utils
  2. import (
  3. "github.com/sirupsen/logrus"
  4. mail "github.com/xhit/go-simple-mail/v2"
  5. "log"
  6. )
  7. var emailClient = func() *mail.SMTPServer {
  8. // 创建邮件客户端
  9. client := mail.NewSMTPClient()
  10. // 设置SMTP服务器和认证信息
  11. client.Host = "smtp.163.com" // 替换为你的SMTP服务器地址
  12. client.Port = 25 // 替换为SMTP服务器端口
  13. client.Username = "17673481176@163.com" // 替换为SMTP服务器的用户名
  14. client.Password = "kk992471" // 替换为SMTP服务器的密码
  15. return client
  16. }()
  17. func EmailPicture(To, subject, data string, pic *mail.File) {
  18. // 创建邮件客户端
  19. smtpClient, err := emailClient.Connect()
  20. if err != nil {
  21. logrus.Error("email client Connect err", err)
  22. return
  23. }
  24. // 创建邮件对象
  25. email := mail.NewMSG()
  26. // 设置发件人
  27. email.SetFrom("17673481176@163.com")
  28. // 设置收件人
  29. email.AddTo(To)
  30. // 设置主题
  31. email.SetSubject(subject)
  32. // 设置html文本内容
  33. email.SetBody(mail.TextHTML, data)
  34. // 添加图片附件
  35. if pic != nil {
  36. email.Attach(pic)
  37. }
  38. // 发送邮件
  39. err = email.Send(smtpClient)
  40. if err != nil {
  41. log.Println("116 Failed to send email:", err)
  42. return
  43. }
  44. log.Println("Email sent successfully")
  45. }
  46. func Email(To, subject string, body string) {
  47. smtpClient, err := emailClient.Connect()
  48. if err != nil {
  49. logrus.Error("email client connect err", err)
  50. return
  51. }
  52. // 创建邮件对象
  53. email := mail.NewMSG()
  54. // 设置发件人
  55. email.SetFrom("17673481176@163.com")
  56. // 设置收件人
  57. email.AddTo(To)
  58. // 设置主题
  59. email.SetSubject(subject)
  60. // 设置纯文本内容
  61. email.SetBody(mail.TextHTML, body)
  62. // 发送邮件
  63. err = email.Send(smtpClient)
  64. if err != nil {
  65. log.Println("116 Failed to send email:", err)
  66. return
  67. }
  68. log.Println("Email sent successfully")
  69. }
  70. func ErrorToEmail(subject string, body string) error {
  71. //to := strings.Split(global.GlobalConfig.To, ",")
  72. //if to[len(to)-1] == "" { // 判断切片的最后一个元素是否为空,为空则移除
  73. // to = to[:len(to)-1]
  74. //}
  75. //return send(to, subject, body)
  76. return nil
  77. }