email.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package common
  2. import (
  3. "crypto/tls"
  4. "encoding/base64"
  5. "fmt"
  6. "net/smtp"
  7. "strings"
  8. "time"
  9. )
  10. func generateMessageID() string {
  11. domain := strings.Split(SMTPAccount, "@")[1]
  12. return fmt.Sprintf("<%d.%s@%s>", time.Now().UnixNano(), GetRandomString(12), domain)
  13. }
  14. func SendEmail(subject string, receiver string, content string) error {
  15. if SMTPFrom == "" { // for compatibility
  16. SMTPFrom = SMTPAccount
  17. }
  18. if SMTPServer == "" && SMTPAccount == "" {
  19. return fmt.Errorf("SMTP 服务器未配置")
  20. }
  21. encodedSubject := fmt.Sprintf("=?UTF-8?B?%s?=", base64.StdEncoding.EncodeToString([]byte(subject)))
  22. mail := []byte(fmt.Sprintf("To: %s\r\n"+
  23. "From: %s<%s>\r\n"+
  24. "Subject: %s\r\n"+
  25. "Date: %s\r\n"+
  26. "Message-ID: %s\r\n"+ // 添加 Message-ID 头
  27. "Content-Type: text/html; charset=UTF-8\r\n\r\n%s\r\n",
  28. receiver, SystemName, SMTPFrom, encodedSubject, time.Now().Format(time.RFC1123Z), generateMessageID(), content))
  29. auth := smtp.PlainAuth("", SMTPAccount, SMTPToken, SMTPServer)
  30. addr := fmt.Sprintf("%s:%d", SMTPServer, SMTPPort)
  31. to := strings.Split(receiver, ";")
  32. var err error
  33. if SMTPPort == 465 || SMTPSSLEnabled {
  34. tlsConfig := &tls.Config{
  35. InsecureSkipVerify: true,
  36. ServerName: SMTPServer,
  37. }
  38. conn, err := tls.Dial("tcp", fmt.Sprintf("%s:%d", SMTPServer, SMTPPort), tlsConfig)
  39. if err != nil {
  40. return err
  41. }
  42. client, err := smtp.NewClient(conn, SMTPServer)
  43. if err != nil {
  44. return err
  45. }
  46. defer client.Close()
  47. if err = client.Auth(auth); err != nil {
  48. return err
  49. }
  50. if err = client.Mail(SMTPFrom); err != nil {
  51. return err
  52. }
  53. receiverEmails := strings.Split(receiver, ";")
  54. for _, receiver := range receiverEmails {
  55. if err = client.Rcpt(receiver); err != nil {
  56. return err
  57. }
  58. }
  59. w, err := client.Data()
  60. if err != nil {
  61. return err
  62. }
  63. _, err = w.Write(mail)
  64. if err != nil {
  65. return err
  66. }
  67. err = w.Close()
  68. if err != nil {
  69. return err
  70. }
  71. } else if isOutlookServer(SMTPAccount) {
  72. auth = LoginAuth(SMTPAccount, SMTPToken)
  73. err = smtp.SendMail(addr, auth, SMTPAccount, to, mail)
  74. } else {
  75. err = smtp.SendMail(addr, auth, SMTPAccount, to, mail)
  76. }
  77. return err
  78. }