send.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  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. "sync"
  15. )
  16. type mxDomain struct {
  17. domain string
  18. mxHost string
  19. }
  20. // Forward 转发邮件
  21. func Forward(ctx *context.Context, e *parsemail.Email, forwardAddress string) error {
  22. log.WithContext(ctx).Debugf("开始转发邮件")
  23. b := e.ForwardBuildBytes(ctx, forwardAddress)
  24. var to []*parsemail.User
  25. to = []*parsemail.User{
  26. {EmailAddress: forwardAddress},
  27. }
  28. // 按域名整理
  29. toByDomain := map[mxDomain][]*parsemail.User{}
  30. for _, s := range to {
  31. args := strings.Split(s.EmailAddress, "@")
  32. if len(args) == 2 {
  33. //查询dns mx记录
  34. mxInfo, err := net.LookupMX(args[1])
  35. address := mxDomain{
  36. domain: "smtp." + args[1],
  37. mxHost: "smtp." + args[1],
  38. }
  39. if err != nil {
  40. log.WithContext(ctx).Errorf(s.EmailAddress, "域名mx记录查询失败")
  41. }
  42. if len(mxInfo) > 0 {
  43. address = mxDomain{
  44. domain: args[1],
  45. mxHost: mxInfo[0].Host,
  46. }
  47. }
  48. toByDomain[address] = append(toByDomain[address], s)
  49. } else {
  50. log.WithContext(ctx).Errorf("邮箱地址解析错误! %s", s)
  51. continue
  52. }
  53. }
  54. var errEmailAddress []string
  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. }, nil)
  89. }
  90. as.Wait()
  91. if len(errEmailAddress) > 0 {
  92. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ","))
  93. }
  94. return nil
  95. }
  96. func Send(ctx *context.Context, e *parsemail.Email) (error, map[string]error) {
  97. b := e.BuildBytes(ctx, true)
  98. log.WithContext(ctx).Debugf("Message Infos : %s", string(b))
  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 := sync.Map{}
  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. // 使用其他方式发送
  136. if err != nil {
  137. if errors.Is(err, smtp.NoSupportSTARTTLSError) {
  138. err = smtp.SendMailWithTls("", domain.mxHost+":465", nil, e.From.EmailAddress, buildAddress(tos), b)
  139. if err != nil {
  140. log.WithContext(ctx).Warnf("Unsafe! %s Server Not Support SMTPS & STARTTLS", domain.domain)
  141. err = smtp.SendMailUnsafe("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  142. }
  143. }
  144. // 证书错误,从新选取证书发送
  145. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  146. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  147. if hostnameErr.Certificate != nil {
  148. certificateHostName := hostnameErr.Certificate.DNSNames
  149. // 重新选取证书发送
  150. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  151. }
  152. }
  153. }
  154. }
  155. if err != nil {
  156. log.WithContext(ctx).Errorf("%v 邮件投递失败%+v", tos, err)
  157. for _, user := range tos {
  158. errEmailAddress = append(errEmailAddress, user.EmailAddress)
  159. }
  160. }
  161. errMap.Store(domain.domain, err)
  162. }, nil)
  163. }
  164. as.Wait()
  165. orgMap := map[string]error{}
  166. errMap.Range(func(key, value any) bool {
  167. if value != nil {
  168. orgMap[key.(string)] = value.(error)
  169. }else {
  170. orgMap[key.(string)] = nil
  171. }
  172. return true
  173. })
  174. if len(errEmailAddress) > 0 {
  175. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ",")), orgMap
  176. }
  177. return nil, orgMap
  178. }
  179. func buildAddress(u []*parsemail.User) []string {
  180. var ret []string
  181. for _, user := range u {
  182. ret = append(ret, user.EmailAddress)
  183. }
  184. return ret
  185. }
  186. func domainMatch(domain string, dnsNames []string) string {
  187. if len(dnsNames) == 0 {
  188. return domain
  189. }
  190. secondMatch := ""
  191. for _, name := range dnsNames {
  192. if strings.Contains(name, "smtp") {
  193. secondMatch = name
  194. }
  195. if name == domain {
  196. return name
  197. }
  198. if strings.Contains(name, "*") {
  199. nameArg := strings.Split(name, ".")
  200. domainArg := strings.Split(domain, ".")
  201. match := true
  202. for i := 0; i < len(nameArg); i++ {
  203. if nameArg[len(nameArg)-1-i] == "*" {
  204. continue
  205. }
  206. if len(domainArg) > i {
  207. if nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  208. continue
  209. }
  210. }
  211. match = false
  212. break
  213. }
  214. for i := 0; i < len(domainArg); i++ {
  215. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  216. continue
  217. }
  218. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == "*" {
  219. continue
  220. }
  221. match = false
  222. break
  223. }
  224. if match {
  225. return domain
  226. }
  227. }
  228. }
  229. if secondMatch != "" {
  230. return strings.ReplaceAll(secondMatch, "*.", "")
  231. }
  232. return strings.ReplaceAll(dnsNames[0], "*.", "")
  233. }