send.go 6.4 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. b := e.ForwardBuildBytes(ctx, forwardAddress)
  22. var to []*parsemail.User
  23. to = []*parsemail.User{
  24. {EmailAddress: forwardAddress},
  25. }
  26. // 按域名整理
  27. toByDomain := map[mxDomain][]*parsemail.User{}
  28. for _, s := range to {
  29. args := strings.Split(s.EmailAddress, "@")
  30. if len(args) == 2 {
  31. //查询dns mx记录
  32. mxInfo, err := net.LookupMX(args[1])
  33. address := mxDomain{
  34. domain: "smtp." + args[1],
  35. mxHost: "smtp." + args[1],
  36. }
  37. if err != nil {
  38. log.WithContext(ctx).Errorf(s.EmailAddress, "域名mx记录查询失败")
  39. }
  40. if len(mxInfo) > 0 {
  41. address = mxDomain{
  42. domain: args[1],
  43. mxHost: mxInfo[0].Host,
  44. }
  45. }
  46. toByDomain[address] = append(toByDomain[address], s)
  47. } else {
  48. log.WithContext(ctx).Errorf("邮箱地址解析错误! %s", s)
  49. continue
  50. }
  51. }
  52. var errEmailAddress []string
  53. errMap := map[string]error{}
  54. as := async.New(ctx)
  55. for domain, tos := range toByDomain {
  56. domain := domain
  57. tos := tos
  58. as.WaitProcess(func(p any) {
  59. // 先使用smtps协议尝试
  60. err := smtp.SendMailWithTls("", domain.mxHost+":465", nil, e.From.EmailAddress, buildAddress(tos), b)
  61. if err != nil {
  62. // smtps发送失败,尝试smtp
  63. err = smtp.SendMail("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  64. }
  65. // 重新选取证书域名
  66. if err != nil {
  67. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  68. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  69. if hostnameErr.Certificate != nil {
  70. certificateHostName := hostnameErr.Certificate.DNSNames
  71. // 先使用smtps协议尝试
  72. err = smtp.SendMailWithTls(domainMatch(domain.domain, certificateHostName), domain.mxHost+":465", nil, e.From.EmailAddress, buildAddress(tos), b)
  73. if err != nil {
  74. log.Infoln(err)
  75. // smtps发送失败,尝试smtp
  76. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  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)
  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. // 先使用smtps协议尝试
  135. err := smtp.SendMailWithTls("", domain.mxHost+":465", nil, e.From.EmailAddress, buildAddress(tos), b)
  136. if err != nil {
  137. // smtps发送失败,尝试smtp
  138. err = smtp.SendMail("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  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协议尝试
  147. err = smtp.SendMailWithTls(domainMatch(domain.domain, certificateHostName), domain.mxHost+":465", nil, e.From.EmailAddress, buildAddress(tos), b)
  148. if err != nil {
  149. // smtps发送失败,尝试smtp
  150. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  151. }
  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. secondMatch := ""
  180. for _, name := range dnsNames {
  181. if strings.Contains(name, "smtp") {
  182. secondMatch = name
  183. }
  184. if name == domain {
  185. return name
  186. }
  187. if strings.Contains(name, "*") {
  188. nameArg := strings.Split(name, ".")
  189. domainArg := strings.Split(domain, ".")
  190. match := true
  191. for i := 0; i < len(nameArg); i++ {
  192. if nameArg[len(nameArg)-1-i] == "*" {
  193. continue
  194. }
  195. if len(domainArg) > i {
  196. if nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  197. continue
  198. }
  199. }
  200. match = false
  201. break
  202. }
  203. for i := 0; i < len(domainArg); i++ {
  204. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  205. continue
  206. }
  207. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == "*" {
  208. continue
  209. }
  210. match = false
  211. break
  212. }
  213. if match {
  214. return domain
  215. }
  216. }
  217. }
  218. if secondMatch != "" {
  219. return strings.ReplaceAll(secondMatch, "*.", "")
  220. }
  221. return strings.ReplaceAll(dnsNames[0], "*.", "")
  222. }