email.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package notify
  2. import (
  3. "crypto/tls"
  4. "gopkg.in/gomail.v2"
  5. "iot_manager_service/config"
  6. "strconv"
  7. )
  8. func SendEmail(html string, title string, receiver ...string) error {
  9. message := html
  10. config := config.Instance().MonitNotice.Email
  11. // QQ 邮箱:
  12. // SMTP 服务器地址:smtp.qq.com(SSL协议端口:465/994 | 非SSL协议端口:25)
  13. // 163 邮箱:
  14. // SMTP 服务器地址:smtp.163.com(端口:25)
  15. host := config.Host
  16. port := config.Port
  17. AuthName := config.AuthName
  18. password := config.PassWord
  19. m := gomail.NewMessage()
  20. m.SetHeader("From", AuthName) // 发件人
  21. // m.SetHeader("From", "alias"+"<"+AuthName+">") // 增加发件人别名
  22. m.SetHeader("To", receiver...) // 收件人,可以多个收件人,但必须使用相同的 SMTP 连接
  23. //m.SetHeader("Cc", "******@qq.com") // 抄送,可以多个
  24. //m.SetHeader("Bcc", "******@qq.com") // 暗送,可以多个
  25. m.SetHeader("Subject", title) // 邮件主题
  26. // text/html 的意思是将文件的 content-type 设置为 text/html 的形式,浏览器在获取到这种文件时会自动调用html的解析器对文件进行相应的处理。
  27. // 可以通过 text/html 处理文本格式进行特殊处理,如换行、缩进、加粗等等
  28. //m.SetBody("text/html", fmt.Sprintf(message, "testAuth"))
  29. m.SetBody("text/html", message)
  30. // text/plain的意思是将文件设置为纯文本的形式,浏览器在获取到这种文件时并不会对其进行处理
  31. // m.SetBody("text/plain", "纯文本")
  32. // m.Attach("test.sh") // 附件文件,可以是文件,照片,视频等等
  33. // m.Attach("lolcatVideo.mp4") // 视频
  34. // m.Attach("lolcat.jpg") // 照片
  35. portInt, _ := strconv.Atoi(port)
  36. d := gomail.NewDialer(
  37. host,
  38. portInt,
  39. AuthName,
  40. password,
  41. )
  42. // 关闭SSL协议认证
  43. d.TLSConfig = &tls.Config{InsecureSkipVerify: true}
  44. if err := d.DialAndSend(m); err != nil {
  45. return err
  46. }
  47. return nil
  48. }