send.go 6.2 KB

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