smtpsend.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. package email
  2. /*
  3. smtpsend.go
  4. Talking to SMTP submission servers.
  5. */
  6. import (
  7. "bytes"
  8. "context"
  9. "errors"
  10. "fmt"
  11. "strings"
  12. "time"
  13. "github.com/emersion/go-sasl"
  14. "github.com/emersion/go-smtp"
  15. )
  16. // dialSMTP connects to and authenticates with an account's SMTP server.
  17. func (m *Manager) dialSMTP(ctx context.Context, p Principal, account *Account) (*smtp.Client, error) {
  18. server := account.SMTP
  19. if server.Security == SecurityNone && !m.allowInsecure(p) {
  20. return nil, ErrInsecureBlocked
  21. }
  22. allowPrivate := m.allowPrivate(p)
  23. var client *smtp.Client
  24. switch server.Security {
  25. case SecuritySSL, "":
  26. conn, err := dialTLS(ctx, server.Host, server.Port, allowPrivate, "")
  27. if err != nil {
  28. return nil, describeDialError("SMTP", server, err)
  29. }
  30. client = smtp.NewClient(conn)
  31. case SecuritySTARTTLS:
  32. conn, err := dialGuarded(ctx, server.Host, server.Port, allowPrivate)
  33. if err != nil {
  34. return nil, describeDialError("SMTP", server, err)
  35. }
  36. client, err = smtp.NewClientStartTLS(conn, tlsConfigFor(server.Host, ""))
  37. if err != nil {
  38. return nil, describeDialError("SMTP", server, describeTLSError(err))
  39. }
  40. case SecurityNone:
  41. conn, err := dialGuarded(ctx, server.Host, server.Port, allowPrivate)
  42. if err != nil {
  43. return nil, describeDialError("SMTP", server, err)
  44. }
  45. client = smtp.NewClient(conn)
  46. default:
  47. return nil, fmt.Errorf("unknown connection security %q", server.Security)
  48. }
  49. client.CommandTimeout = 2 * time.Minute
  50. if err := client.Hello(ehloName(m.options.Hostname)); err != nil {
  51. client.Close()
  52. return nil, describeDialError("SMTP", server, err)
  53. }
  54. if err := m.authenticateSMTP(ctx, client, account); err != nil {
  55. client.Close()
  56. return nil, err
  57. }
  58. return client, nil
  59. }
  60. // ehloName picks the name announced in EHLO. Several providers reject a bare
  61. // word, so anything that is not a dotted host name becomes an address literal.
  62. func ehloName(hostname string) string {
  63. hostname = strings.TrimSpace(strings.ToLower(hostname))
  64. if hostname != "" && strings.Contains(hostname, ".") && !strings.ContainsAny(hostname, " _/") {
  65. return hostname
  66. }
  67. return "[127.0.0.1]"
  68. }
  69. func (m *Manager) authenticateSMTP(ctx context.Context, client *smtp.Client, account *Account) error {
  70. username := account.SMTP.Username
  71. if username == "" {
  72. username = account.Email
  73. }
  74. var saslClient sasl.Client
  75. switch account.Auth {
  76. case AuthOAuth2:
  77. token, err := m.oauth.accessToken(ctx, account)
  78. if err != nil {
  79. return err
  80. }
  81. saslClient = newXOAuth2Client(username, token)
  82. default:
  83. secret := account.SMTPSecret
  84. if secret == "" {
  85. secret = account.Secret
  86. }
  87. password, err := m.box.Open(secret)
  88. if err != nil {
  89. return &AuthError{Server: "SMTP", Detail: err.Error()}
  90. }
  91. if password == "" {
  92. return nil //Relay without authentication (LAN servers)
  93. }
  94. if ok, _ := client.Extension("AUTH"); !ok {
  95. //The server offers no authentication at all; send unauthenticated
  96. return nil
  97. }
  98. if client.SupportsAuth(sasl.Plain) {
  99. saslClient = sasl.NewPlainClient("", username, password)
  100. } else if client.SupportsAuth(sasl.Login) {
  101. saslClient = sasl.NewLoginClient(username, password)
  102. } else {
  103. return errors.New("the SMTP server offers no supported password authentication")
  104. }
  105. }
  106. if err := client.Auth(saslClient); err != nil {
  107. var smtpErr *smtp.SMTPError
  108. if errors.As(err, &smtpErr) && (smtpErr.Code == 535 || smtpErr.Code == 534 || smtpErr.Code == 530 || smtpErr.Code == 454) {
  109. hint := authHintFor(account.Provider)
  110. if account.Auth == AuthOAuth2 {
  111. hint = "Your sign-in has expired or was revoked. Reconnect the account to sign in again."
  112. }
  113. return &AuthError{Server: "SMTP", Detail: smtpErr.Message, Hint: hint}
  114. }
  115. if looksLikeAuthFailure(err.Error()) {
  116. return &AuthError{Server: "SMTP", Detail: err.Error(), Hint: authHintFor(account.Provider)}
  117. }
  118. return err
  119. }
  120. return nil
  121. }
  122. // checkSMTP verifies SMTP settings and credentials.
  123. func (m *Manager) checkSMTP(ctx context.Context, p Principal, account *Account) error {
  124. client, err := m.dialSMTP(ctx, p, account)
  125. if err != nil {
  126. return err
  127. }
  128. client.Quit()
  129. client.Close()
  130. return nil
  131. }
  132. // sendRaw delivers a rendered message.
  133. func (m *Manager) sendRaw(ctx context.Context, p Principal, account *Account, from string, recipients []string, raw []byte) error {
  134. if len(recipients) == 0 {
  135. return errors.New("no recipients")
  136. }
  137. client, err := m.dialSMTP(ctx, p, account)
  138. if err != nil {
  139. return err
  140. }
  141. defer client.Close()
  142. if max, ok := client.MaxMessageSize(); ok && max > 0 && len(raw) > max {
  143. return fmt.Errorf("%w: the server accepts at most %s and this message is %s", ErrTooLarge, humanSize(int64(max)), humanSize(int64(len(raw))))
  144. }
  145. if err := client.SendMail(from, recipients, bytes.NewReader(raw)); err != nil {
  146. var smtpErr *smtp.SMTPError
  147. if errors.As(err, &smtpErr) {
  148. return fmt.Errorf("the mail server refused the message: %s (%d)", smtpErr.Message, smtpErr.Code)
  149. }
  150. return err
  151. }
  152. client.Quit()
  153. return nil
  154. }