send.go 7.6 KB

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