send.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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. // 使用其他方式发送
  137. if err != nil {
  138. if errors.Is(err, smtp.NoSupportSTARTTLSError) {
  139. err = smtp.SendMailWithTls("", domain.mxHost+":465", nil, e.From.EmailAddress, buildAddress(tos), b)
  140. if err != nil {
  141. log.WithContext(ctx).Warnf("Unsafe! %s Server Not Support SMTPS & STARTTLS", domain.domain)
  142. err = smtp.SendMailUnsafe("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  143. }
  144. }
  145. // 证书错误,从新选取证书发送
  146. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  147. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  148. if hostnameErr.Certificate != nil {
  149. certificateHostName := hostnameErr.Certificate.DNSNames
  150. // 重新选取证书发送
  151. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  152. }
  153. }
  154. }
  155. }
  156. if err != nil {
  157. log.WithContext(ctx).Errorf("%v 邮件投递失败%+v", tos, err)
  158. for _, user := range tos {
  159. errEmailAddress = append(errEmailAddress, user.EmailAddress)
  160. }
  161. }
  162. errMap[domain.domain] = err
  163. }, nil)
  164. }
  165. as.Wait()
  166. if len(errEmailAddress) > 0 {
  167. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ",")), errMap
  168. }
  169. return nil, errMap
  170. }
  171. func buildAddress(u []*parsemail.User) []string {
  172. var ret []string
  173. for _, user := range u {
  174. ret = append(ret, user.EmailAddress)
  175. }
  176. return ret
  177. }
  178. func domainMatch(domain string, dnsNames []string) string {
  179. if len(dnsNames) == 0 {
  180. return domain
  181. }
  182. secondMatch := ""
  183. for _, name := range dnsNames {
  184. if strings.Contains(name, "smtp") {
  185. secondMatch = name
  186. }
  187. if name == domain {
  188. return name
  189. }
  190. if strings.Contains(name, "*") {
  191. nameArg := strings.Split(name, ".")
  192. domainArg := strings.Split(domain, ".")
  193. match := true
  194. for i := 0; i < len(nameArg); i++ {
  195. if nameArg[len(nameArg)-1-i] == "*" {
  196. continue
  197. }
  198. if len(domainArg) > i {
  199. if nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  200. continue
  201. }
  202. }
  203. match = false
  204. break
  205. }
  206. for i := 0; i < len(domainArg); i++ {
  207. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  208. continue
  209. }
  210. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == "*" {
  211. continue
  212. }
  213. match = false
  214. break
  215. }
  216. if match {
  217. return domain
  218. }
  219. }
  220. }
  221. if secondMatch != "" {
  222. return strings.ReplaceAll(secondMatch, "*.", "")
  223. }
  224. return strings.ReplaceAll(dnsNames[0], "*.", "")
  225. }