send.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package send
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "errors"
  6. log "github.com/sirupsen/logrus"
  7. "net"
  8. "pmail/dto/parsemail"
  9. "pmail/utils/array"
  10. "pmail/utils/async"
  11. "pmail/utils/consts"
  12. "pmail/utils/context"
  13. "pmail/utils/smtp"
  14. "strings"
  15. "sync"
  16. )
  17. type mxDomain struct {
  18. domain string
  19. mxHost string
  20. }
  21. // Forward 转发邮件
  22. func Forward(ctx *context.Context, e *parsemail.Email, forwardAddress string) error {
  23. log.WithContext(ctx).Debugf("开始转发邮件")
  24. b := e.ForwardBuildBytes(ctx, forwardAddress)
  25. var to []*parsemail.User
  26. to = []*parsemail.User{
  27. {EmailAddress: forwardAddress},
  28. }
  29. // 按域名整理
  30. toByDomain := map[mxDomain][]*parsemail.User{}
  31. for _, s := range to {
  32. args := strings.Split(s.EmailAddress, "@")
  33. if len(args) == 2 {
  34. if args[1] == consts.TEST_DOMAIN {
  35. // 测试使用
  36. address := mxDomain{
  37. domain: "localhost",
  38. mxHost: "127.0.0.1",
  39. }
  40. toByDomain[address] = append(toByDomain[address], s)
  41. } else {
  42. //查询dns mx记录
  43. mxInfo, err := net.LookupMX(args[1])
  44. address := mxDomain{
  45. domain: "smtp." + args[1],
  46. mxHost: "smtp." + args[1],
  47. }
  48. if err != nil {
  49. log.WithContext(ctx).Errorf(s.EmailAddress, "域名mx记录查询失败")
  50. }
  51. if len(mxInfo) > 0 {
  52. address = mxDomain{
  53. domain: args[1],
  54. mxHost: mxInfo[0].Host,
  55. }
  56. }
  57. toByDomain[address] = append(toByDomain[address], s)
  58. }
  59. } else {
  60. log.WithContext(ctx).Errorf("邮箱地址解析错误! %s", s)
  61. continue
  62. }
  63. }
  64. var errEmailAddress []string
  65. as := async.New(ctx)
  66. for domain, tos := range toByDomain {
  67. domain := domain
  68. tos := tos
  69. as.WaitProcess(func(p any) {
  70. err := smtp.SendMail("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  71. if err != nil {
  72. log.WithContext(ctx).Warnf("SMTP Send Error! Error:%+v", err)
  73. } else {
  74. log.WithContext(ctx).Infof("SMTP Send Success !")
  75. }
  76. // 重新选取证书域名
  77. if err != nil {
  78. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  79. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  80. if hostnameErr.Certificate != nil {
  81. certificateHostName := hostnameErr.Certificate.DNSNames
  82. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  83. if err != nil {
  84. log.WithContext(ctx).Warnf("SMTP Send Error! Error:%+v", err)
  85. } else {
  86. log.WithContext(ctx).Infof("SMTP Send Success !")
  87. }
  88. }
  89. }
  90. }
  91. }
  92. if err != nil {
  93. log.WithContext(ctx).Errorf("%v 邮件投递失败%+v", tos, err)
  94. for _, user := range tos {
  95. errEmailAddress = append(errEmailAddress, user.EmailAddress)
  96. }
  97. }
  98. }, nil)
  99. }
  100. as.Wait()
  101. if len(errEmailAddress) > 0 {
  102. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ","))
  103. }
  104. return nil
  105. }
  106. func Send(ctx *context.Context, e *parsemail.Email) (error, map[string]error) {
  107. b := e.BuildBytes(ctx, true)
  108. log.WithContext(ctx).Debugf("Message Infos : %s", string(b))
  109. var to []*parsemail.User
  110. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  111. // 按域名整理
  112. toByDomain := map[mxDomain][]*parsemail.User{}
  113. for _, s := range to {
  114. args := strings.Split(s.EmailAddress, "@")
  115. if len(args) == 2 {
  116. if args[1] == consts.TEST_DOMAIN {
  117. // 测试使用
  118. address := mxDomain{
  119. domain: "localhost",
  120. mxHost: "127.0.0.1",
  121. }
  122. toByDomain[address] = append(toByDomain[address], s)
  123. } else {
  124. //查询dns mx记录
  125. mxInfo, err := net.LookupMX(args[1])
  126. address := mxDomain{
  127. domain: "smtp." + args[1],
  128. mxHost: "smtp." + args[1],
  129. }
  130. if err != nil {
  131. log.WithContext(ctx).Errorf(s.EmailAddress, "域名mx记录查询失败")
  132. }
  133. if len(mxInfo) > 0 {
  134. address = mxDomain{
  135. domain: args[1],
  136. mxHost: mxInfo[0].Host,
  137. }
  138. }
  139. toByDomain[address] = append(toByDomain[address], s)
  140. }
  141. } else {
  142. log.WithContext(ctx).Errorf("邮箱地址解析错误! %s", s)
  143. continue
  144. }
  145. }
  146. var errEmailAddress []string
  147. errMap := sync.Map{}
  148. as := async.New(ctx)
  149. for domain, tos := range toByDomain {
  150. domain := domain
  151. tos := tos
  152. as.WaitProcess(func(p any) {
  153. err := smtp.SendMail("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  154. // 使用其他方式发送
  155. if err != nil {
  156. // EOF 表示未知错误,此时降级为非tls连接发送(目前仅139邮箱有这个问题)
  157. if errors.Is(err, smtp.NoSupportSTARTTLSError) || err.Error() == "EOF" {
  158. err = smtp.SendMailWithTls("", domain.mxHost+":465", nil, e.From.EmailAddress, buildAddress(tos), b)
  159. if err != nil {
  160. log.WithContext(ctx).Warnf("Unsafe! %s Server Not Support SMTPS & STARTTLS", domain.domain)
  161. err = smtp.SendMailUnsafe("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  162. }
  163. }
  164. // 证书错误,从新选取证书发送
  165. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  166. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  167. if hostnameErr.Certificate != nil {
  168. certificateHostName := hostnameErr.Certificate.DNSNames
  169. // 重新选取证书发送
  170. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  171. }
  172. }
  173. }
  174. }
  175. if err != nil {
  176. log.WithContext(ctx).Errorf("%v 邮件投递失败%+v", tos, err)
  177. for _, user := range tos {
  178. errEmailAddress = append(errEmailAddress, user.EmailAddress)
  179. }
  180. }
  181. errMap.Store(domain.domain, err)
  182. }, nil)
  183. }
  184. as.Wait()
  185. orgMap := map[string]error{}
  186. errMap.Range(func(key, value any) bool {
  187. if value != nil {
  188. orgMap[key.(string)] = value.(error)
  189. } else {
  190. orgMap[key.(string)] = nil
  191. }
  192. return true
  193. })
  194. if len(errEmailAddress) > 0 {
  195. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ",")), orgMap
  196. }
  197. return nil, orgMap
  198. }
  199. func buildAddress(u []*parsemail.User) []string {
  200. var ret []string
  201. for _, user := range u {
  202. ret = append(ret, user.EmailAddress)
  203. }
  204. return ret
  205. }
  206. func domainMatch(domain string, dnsNames []string) string {
  207. if len(dnsNames) == 0 {
  208. return domain
  209. }
  210. secondMatch := ""
  211. for _, name := range dnsNames {
  212. if strings.Contains(name, "smtp") {
  213. secondMatch = name
  214. }
  215. if name == domain {
  216. return name
  217. }
  218. if strings.Contains(name, "*") {
  219. nameArg := strings.Split(name, ".")
  220. domainArg := strings.Split(domain, ".")
  221. match := true
  222. for i := 0; i < len(nameArg); i++ {
  223. if nameArg[len(nameArg)-1-i] == "*" {
  224. continue
  225. }
  226. if len(domainArg) > i {
  227. if nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  228. continue
  229. }
  230. }
  231. match = false
  232. break
  233. }
  234. for i := 0; i < len(domainArg); i++ {
  235. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  236. continue
  237. }
  238. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == "*" {
  239. continue
  240. }
  241. match = false
  242. break
  243. }
  244. if match {
  245. return domain
  246. }
  247. }
  248. }
  249. if secondMatch != "" {
  250. return strings.ReplaceAll(secondMatch, "*.", "")
  251. }
  252. return strings.ReplaceAll(dnsNames[0], "*.", "")
  253. }