send.go 7.1 KB

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