email.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package utils
  2. import (
  3. "fmt"
  4. "gopkg.in/gomail.v2"
  5. "mime"
  6. "strings"
  7. )
  8. //发送邮件
  9. func SendEmail(title, content string, touser string) bool {
  10. var arr []string
  11. sub := strings.Index(touser, ";")
  12. if sub >= 0 {
  13. spArr := strings.Split(touser, ";")
  14. for _, v := range spArr {
  15. arr = append(arr, v)
  16. }
  17. } else {
  18. arr = append(arr, touser)
  19. }
  20. //mailConn := map[string]string{
  21. // "user": "18170239278@163.com",
  22. // "pass": "JYWLATLVZJROWMWZ",
  23. // "host": "smtp.163.com",
  24. // "port": "465",
  25. //}
  26. //mailPort, _ := strconv.Atoi(mailConn["port"]) //转换端口类型为int
  27. m := gomail.NewMessage()
  28. //m.SetHeader("From", mailConn["user"])
  29. m.SetHeader("From", m.FormatAddress("qunao007@qq.com", APPNAME)) //这种方式可以添加别名,即“XX官方”
  30. // 说明:如果是用网易邮箱账号发送,以下方法别名可以是中文,如果是qq企业邮箱,以下方法用中文别名,会报错,需要用上面此方法转码
  31. //m.SetHeader("From", "FB Sample"+"<"+mailConn["user"]+">") //这种方式可以添加别名,即“FB Sample”, 也可以直接用<code>m.SetHeader("From",mailConn["user"])</code> 读者可以自行实验下效果
  32. //m.SetHeader("From", mailConn["user"])
  33. m.SetHeader("To", arr...)
  34. m.SetHeader("Subject", title+" "+GetRandString(16))
  35. m.SetBody("text/html", content)
  36. d := gomail.NewDialer("smtp.qq.com", 587, "qunao007@qq.com", "cyhjgffhaobteihd")
  37. //d := gomail.NewDialer(mailConn["host"], mailPort, mailConn["user"], mailConn["pass"])
  38. if err := d.DialAndSend(m); err != nil {
  39. fmt.Println("err:", err)
  40. return false
  41. }
  42. return true
  43. }
  44. //发送邮件
  45. func SendEmailByHongze(title, content string, touser, attachPath, attachName string) bool {
  46. var arr []string
  47. sub := strings.Index(touser, ";")
  48. if sub >= 0 {
  49. spArr := strings.Split(touser, ";")
  50. for _, v := range spArr {
  51. arr = append(arr, v)
  52. }
  53. } else {
  54. arr = append(arr, touser)
  55. }
  56. m := gomail.NewMessage()
  57. m.SetHeader("From", "public@hzinsights.com")
  58. m.SetHeader("To", arr...)
  59. m.SetHeader("Subject", title+" "+GetRandStringNoSpecialChar(8))
  60. m.SetBody("text/html", content)
  61. //body := new(bytes.Buffer)
  62. if attachPath != "" {
  63. m.Attach(attachPath,
  64. gomail.Rename(attachName),
  65. gomail.SetHeader(map[string][]string{
  66. "Content-Disposition": {
  67. fmt.Sprintf(`attachment; filename="%s"`, mime.QEncoding.Encode("UTF-8", attachName)),
  68. },
  69. }))
  70. }
  71. d := gomail.NewDialer("smtp.mxhichina.com", 465, "public@hzinsights.com", "Hzinsights2018")
  72. if err := d.DialAndSend(m); err != nil {
  73. fmt.Println("send err:", err.Error())
  74. return false
  75. }
  76. return true
  77. }