send.go 8.2 KB

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