mail.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package thirdparty
  4. import (
  5. "gopkg.in/gomail.v2"
  6. "mime"
  7. "path"
  8. "strconv"
  9. "strings"
  10. "fmt"
  11. )
  12. func SendMail(user, password, host, to, subject string, files []string, content string) error {
  13. hostIp := ""
  14. hostPort := ""
  15. array := strings.Split(host, ":")
  16. if len(array) > 1 {
  17. hostIp = array[0]
  18. hostPort = array[1]
  19. } else {
  20. hostIp = host
  21. hostPort = "465"
  22. }
  23. mailConn := map[string]string{
  24. "user": user,
  25. "pass": password,
  26. "host": hostIp,
  27. "port": hostPort,
  28. }
  29. body := `
  30. <html>
  31. <body>
  32. <h3>
  33. content
  34. </h3>
  35. </body>
  36. </html>
  37. `
  38. body = strings.Replace(body, "content", content, -1)
  39. port, _ := strconv.Atoi(mailConn["port"])
  40. mailTo := strings.Split(to, ";")
  41. m := gomail.NewMessage()
  42. m.SetHeader("From", "sy"+"<"+mailConn["user"]+">")
  43. m.SetHeader("To", mailTo...)
  44. m.SetHeader("Subject", subject)
  45. m.SetBody("text/html", body)
  46. for _, v := range files {
  47. if v != "" {
  48. newname := path.Base(v)
  49. m.Attach(v, gomail.Rename(newname),
  50. gomail.SetHeader(map[string][]string{
  51. "Content-Disposition": []string{
  52. fmt.Sprintf(`attachment; filename="%s"`, mime.QEncoding.Encode("UTF-8", newname)),
  53. }}))
  54. }
  55. }
  56. d := gomail.NewDialer(mailConn["host"], port, mailConn["user"], mailConn["pass"])
  57. err := d.DialAndSend(m)
  58. return err
  59. }