send.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  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.SendMail("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  61. if err != nil {
  62. log.WithContext(ctx).Warnf("SMTP Send Error! Error:%+v", err)
  63. } else {
  64. log.WithContext(ctx).Infof("SMTP Send Success !")
  65. }
  66. // 重新选取证书域名
  67. if err != nil {
  68. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  69. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  70. if hostnameErr.Certificate != nil {
  71. certificateHostName := hostnameErr.Certificate.DNSNames
  72. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  73. if err != nil {
  74. log.WithContext(ctx).Warnf("SMTP Send Error! Error:%+v", err)
  75. } else {
  76. log.WithContext(ctx).Infof("SMTP Send Success !")
  77. }
  78. }
  79. }
  80. }
  81. }
  82. if err != nil {
  83. log.WithContext(ctx).Errorf("%v 邮件投递失败%+v", tos, err)
  84. for _, user := range tos {
  85. errEmailAddress = append(errEmailAddress, user.EmailAddress)
  86. }
  87. }
  88. errMap[domain.domain] = err
  89. }, nil)
  90. }
  91. as.Wait()
  92. if len(errEmailAddress) > 0 {
  93. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ","))
  94. }
  95. return nil
  96. }
  97. func Send(ctx *context.Context, e *parsemail.Email) (error, map[string]error) {
  98. b := e.BuildBytes(ctx, true)
  99. log.WithContext(ctx).Debugf("Message Infos : %s", string(b))
  100. var to []*parsemail.User
  101. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  102. // 按域名整理
  103. toByDomain := map[mxDomain][]*parsemail.User{}
  104. for _, s := range to {
  105. args := strings.Split(s.EmailAddress, "@")
  106. if len(args) == 2 {
  107. //查询dns mx记录
  108. mxInfo, err := net.LookupMX(args[1])
  109. address := mxDomain{
  110. domain: "smtp." + args[1],
  111. mxHost: "smtp." + args[1],
  112. }
  113. if err != nil {
  114. log.WithContext(ctx).Errorf(s.EmailAddress, "域名mx记录查询失败")
  115. }
  116. if len(mxInfo) > 0 {
  117. address = mxDomain{
  118. domain: args[1],
  119. mxHost: mxInfo[0].Host,
  120. }
  121. }
  122. toByDomain[address] = append(toByDomain[address], s)
  123. } else {
  124. log.WithContext(ctx).Errorf("邮箱地址解析错误! %s", s)
  125. continue
  126. }
  127. }
  128. var errEmailAddress []string
  129. errMap := map[string]error{}
  130. as := async.New(ctx)
  131. for domain, tos := range toByDomain {
  132. domain := domain
  133. tos := tos
  134. as.WaitProcess(func(p any) {
  135. err := smtp.SendMail("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  136. if err != nil {
  137. log.WithContext(ctx).Warnf("SMTP Send Error! Error:%+v", err)
  138. } else {
  139. log.WithContext(ctx).Infof("SMTP Send Success !")
  140. }
  141. // 重新选取证书域名
  142. if err != nil {
  143. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  144. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  145. if hostnameErr.Certificate != nil {
  146. certificateHostName := hostnameErr.Certificate.DNSNames
  147. // smtps发送失败,尝试smtp
  148. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  149. if err != nil {
  150. log.WithContext(ctx).Warnf("SMTP Send Error! Error:%+v", err)
  151. } else {
  152. log.WithContext(ctx).Infof("SMTP Send Success !")
  153. }
  154. }
  155. }
  156. }
  157. }
  158. if err != nil {
  159. log.WithContext(ctx).Errorf("%v 邮件投递失败%+v", tos, err)
  160. for _, user := range tos {
  161. errEmailAddress = append(errEmailAddress, user.EmailAddress)
  162. }
  163. }
  164. errMap[domain.domain] = err
  165. }, nil)
  166. }
  167. as.Wait()
  168. if len(errEmailAddress) > 0 {
  169. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ",")), errMap
  170. }
  171. return nil, errMap
  172. }
  173. func buildAddress(u []*parsemail.User) []string {
  174. var ret []string
  175. for _, user := range u {
  176. ret = append(ret, user.EmailAddress)
  177. }
  178. return ret
  179. }
  180. func domainMatch(domain string, dnsNames []string) string {
  181. secondMatch := ""
  182. for _, name := range dnsNames {
  183. if strings.Contains(name, "smtp") {
  184. secondMatch = name
  185. }
  186. if name == domain {
  187. return name
  188. }
  189. if strings.Contains(name, "*") {
  190. nameArg := strings.Split(name, ".")
  191. domainArg := strings.Split(domain, ".")
  192. match := true
  193. for i := 0; i < len(nameArg); i++ {
  194. if nameArg[len(nameArg)-1-i] == "*" {
  195. continue
  196. }
  197. if len(domainArg) > i {
  198. if nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  199. continue
  200. }
  201. }
  202. match = false
  203. break
  204. }
  205. for i := 0; i < len(domainArg); i++ {
  206. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  207. continue
  208. }
  209. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == "*" {
  210. continue
  211. }
  212. match = false
  213. break
  214. }
  215. if match {
  216. return domain
  217. }
  218. }
  219. }
  220. if secondMatch != "" {
  221. return strings.ReplaceAll(secondMatch, "*.", "")
  222. }
  223. return strings.ReplaceAll(dnsNames[0], "*.", "")
  224. }