send.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  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/consts"
  12. "pmail/utils/context"
  13. "pmail/utils/smtp"
  14. "strings"
  15. "sync"
  16. )
  17. type mxDomain struct {
  18. domain string
  19. mxHost string
  20. }
  21. // Forward 转发邮件
  22. func Forward(ctx *context.Context, e *parsemail.Email, forwardAddress string) error {
  23. log.WithContext(ctx).Debugf("开始转发邮件")
  24. b := e.ForwardBuildBytes(ctx, forwardAddress)
  25. var to []*parsemail.User
  26. to = []*parsemail.User{
  27. {EmailAddress: forwardAddress},
  28. }
  29. // 按域名整理
  30. toByDomain := map[mxDomain][]*parsemail.User{}
  31. for _, s := range to {
  32. args := strings.Split(s.EmailAddress, "@")
  33. if len(args) == 2 {
  34. if args[1] == consts.TEST_DOMAIN {
  35. // 测试使用
  36. address := mxDomain{
  37. domain: "localhost",
  38. mxHost: "127.0.0.1",
  39. }
  40. toByDomain[address] = append(toByDomain[address], s)
  41. } else {
  42. //查询dns mx记录
  43. mxInfo, err := net.LookupMX(args[1])
  44. address := mxDomain{
  45. domain: "smtp." + args[1],
  46. mxHost: "smtp." + args[1],
  47. }
  48. if err != nil {
  49. log.WithContext(ctx).Errorf(s.EmailAddress, "域名mx记录查询失败")
  50. }
  51. if len(mxInfo) > 0 {
  52. address = mxDomain{
  53. domain: args[1],
  54. mxHost: mxInfo[0].Host,
  55. }
  56. }
  57. toByDomain[address] = append(toByDomain[address], s)
  58. }
  59. } else {
  60. log.WithContext(ctx).Errorf("邮箱地址解析错误! %s", s)
  61. continue
  62. }
  63. }
  64. var errEmailAddress []string
  65. as := async.New(ctx)
  66. for domain, tos := range toByDomain {
  67. domain := domain
  68. tos := tos
  69. as.WaitProcess(func(p any) {
  70. err := smtp.SendMail("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  71. if err != nil {
  72. log.WithContext(ctx).Warnf("SMTP Send Error! Error:%+v", err)
  73. } else {
  74. log.WithContext(ctx).Infof("SMTP Send Success !")
  75. }
  76. // 重新选取证书域名
  77. if err != nil {
  78. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  79. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  80. if hostnameErr.Certificate != nil {
  81. certificateHostName := hostnameErr.Certificate.DNSNames
  82. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  83. if err != nil {
  84. log.WithContext(ctx).Warnf("SMTP Send Error! Error:%+v", err)
  85. } else {
  86. log.WithContext(ctx).Infof("SMTP Send Success !")
  87. }
  88. }
  89. }
  90. }
  91. }
  92. if err != nil {
  93. log.WithContext(ctx).Errorf("%v 邮件投递失败%+v", tos, err)
  94. for _, user := range tos {
  95. errEmailAddress = append(errEmailAddress, user.EmailAddress)
  96. }
  97. }
  98. }, nil)
  99. }
  100. as.Wait()
  101. if len(errEmailAddress) > 0 {
  102. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ","))
  103. }
  104. return nil
  105. }
  106. func Send(ctx *context.Context, e *parsemail.Email) (error, map[string]error) {
  107. b := e.BuildBytes(ctx, true)
  108. log.WithContext(ctx).Debugf("Message Infos : %s", string(b))
  109. var to []*parsemail.User
  110. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  111. // 按域名整理
  112. toByDomain := map[mxDomain][]*parsemail.User{}
  113. for _, s := range to {
  114. args := strings.Split(s.EmailAddress, "@")
  115. if len(args) == 2 {
  116. if args[1] == consts.TEST_DOMAIN {
  117. // 测试使用
  118. address := mxDomain{
  119. domain: "localhost",
  120. mxHost: "127.0.0.1",
  121. }
  122. toByDomain[address] = append(toByDomain[address], s)
  123. } else {
  124. //查询dns mx记录
  125. mxInfo, err := net.LookupMX(args[1])
  126. address := mxDomain{
  127. domain: "smtp." + args[1],
  128. mxHost: "smtp." + args[1],
  129. }
  130. if err != nil {
  131. log.WithContext(ctx).Errorf(s.EmailAddress, "域名mx记录查询失败")
  132. }
  133. if len(mxInfo) > 0 {
  134. address = mxDomain{
  135. domain: args[1],
  136. mxHost: mxInfo[0].Host,
  137. }
  138. }
  139. toByDomain[address] = append(toByDomain[address], s)
  140. }
  141. } else {
  142. log.WithContext(ctx).Errorf("邮箱地址解析错误! %s", s)
  143. continue
  144. }
  145. }
  146. var errEmailAddress []string
  147. errMap := sync.Map{}
  148. as := async.New(ctx)
  149. for domain, tos := range toByDomain {
  150. domain := domain
  151. tos := tos
  152. as.WaitProcess(func(p any) {
  153. err := smtp.SendMail("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  154. // 使用其他方式发送
  155. if err != nil {
  156. if errors.Is(err, smtp.NoSupportSTARTTLSError) {
  157. err = smtp.SendMailWithTls("", domain.mxHost+":465", nil, e.From.EmailAddress, buildAddress(tos), b)
  158. if err != nil {
  159. log.WithContext(ctx).Warnf("Unsafe! %s Server Not Support SMTPS & STARTTLS", domain.domain)
  160. err = smtp.SendMailUnsafe("", domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  161. }
  162. }
  163. // 证书错误,从新选取证书发送
  164. if certificateErr, ok := err.(*tls.CertificateVerificationError); ok {
  165. if hostnameErr, is := certificateErr.Err.(x509.HostnameError); is {
  166. if hostnameErr.Certificate != nil {
  167. certificateHostName := hostnameErr.Certificate.DNSNames
  168. // 重新选取证书发送
  169. err = smtp.SendMail(domainMatch(domain.domain, certificateHostName), domain.mxHost+":25", nil, e.From.EmailAddress, buildAddress(tos), b)
  170. }
  171. }
  172. }
  173. }
  174. if err != nil {
  175. log.WithContext(ctx).Errorf("%v 邮件投递失败%+v", tos, err)
  176. for _, user := range tos {
  177. errEmailAddress = append(errEmailAddress, user.EmailAddress)
  178. }
  179. }
  180. errMap.Store(domain.domain, err)
  181. }, nil)
  182. }
  183. as.Wait()
  184. orgMap := map[string]error{}
  185. errMap.Range(func(key, value any) bool {
  186. if value != nil {
  187. orgMap[key.(string)] = value.(error)
  188. } else {
  189. orgMap[key.(string)] = nil
  190. }
  191. return true
  192. })
  193. if len(errEmailAddress) > 0 {
  194. return errors.New("以下收件人投递失败:" + array.Join(errEmailAddress, ",")), orgMap
  195. }
  196. return nil, orgMap
  197. }
  198. func buildAddress(u []*parsemail.User) []string {
  199. var ret []string
  200. for _, user := range u {
  201. ret = append(ret, user.EmailAddress)
  202. }
  203. return ret
  204. }
  205. func domainMatch(domain string, dnsNames []string) string {
  206. if len(dnsNames) == 0 {
  207. return domain
  208. }
  209. secondMatch := ""
  210. for _, name := range dnsNames {
  211. if strings.Contains(name, "smtp") {
  212. secondMatch = name
  213. }
  214. if name == domain {
  215. return name
  216. }
  217. if strings.Contains(name, "*") {
  218. nameArg := strings.Split(name, ".")
  219. domainArg := strings.Split(domain, ".")
  220. match := true
  221. for i := 0; i < len(nameArg); i++ {
  222. if nameArg[len(nameArg)-1-i] == "*" {
  223. continue
  224. }
  225. if len(domainArg) > i {
  226. if nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  227. continue
  228. }
  229. }
  230. match = false
  231. break
  232. }
  233. for i := 0; i < len(domainArg); i++ {
  234. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == domainArg[len(domainArg)-1-i] {
  235. continue
  236. }
  237. if len(nameArg) > i && nameArg[len(nameArg)-1-i] == "*" {
  238. continue
  239. }
  240. match = false
  241. break
  242. }
  243. if match {
  244. return domain
  245. }
  246. }
  247. }
  248. if secondMatch != "" {
  249. return strings.ReplaceAll(secondMatch, "*.", "")
  250. }
  251. return strings.ReplaceAll(dnsNames[0], "*.", "")
  252. }