smtp.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package email
  2. import (
  3. "crypto/tls"
  4. "fmt"
  5. "github.com/gogf/gf/frame/g"
  6. "io"
  7. "net"
  8. "net/smtp"
  9. "strings"
  10. "time"
  11. )
  12. var Client *ClientImpl
  13. func init() {
  14. Client = NewClient()
  15. }
  16. // A ClientImpl is a dialer to an SMTP server.
  17. type ClientImpl struct {
  18. // Host represents the host of the SMTP server.
  19. Host string
  20. // Port represents the port of the SMTP server.
  21. Port int
  22. // Username is the username to use to authenticate to the SMTP server.
  23. Username string
  24. // Password is the password to use to authenticate to the SMTP server.
  25. Password string
  26. // Auth represents the authentication mechanism used to authenticate to the
  27. // SMTP server.
  28. Auth smtp.Auth
  29. // SSL defines whether an SSL connection is used. It should be false in
  30. // most cases since the authentication mechanism should use the STARTTLS
  31. // extension instead.
  32. SSL bool
  33. // TSLConfig represents the TLS configuration used for the TLS (when the
  34. // STARTTLS extension is used) or SSL connection.
  35. TLSConfig *tls.Config
  36. // LocalName is the hostname sent to the SMTP server with the HELO command.
  37. // By default, "localhost" is sent.
  38. LocalName string
  39. }
  40. // NewClient returns a new SMTP ClientImpl. The given parameters are used to connect
  41. // to the SMTP server.
  42. func NewClient() *ClientImpl {
  43. var config = Config{
  44. MailHost: g.Config().GetString("email.host"),
  45. MailPort: g.Config().GetInt("email.port"),
  46. MailUser: g.Config().GetString("email.user"),
  47. MailPassword: g.Config().GetString("email.password"),
  48. }
  49. return newClient(config)
  50. }
  51. // NewClient returns a new SMTP ClientImpl. The given parameters are used to connect
  52. // to the SMTP server.
  53. func newClient(cfg Config) *ClientImpl {
  54. return &ClientImpl{
  55. Host: cfg.MailHost,
  56. Port: cfg.MailPort,
  57. Username: cfg.MailUser,
  58. Password: cfg.MailPassword,
  59. SSL: cfg.MailPort == 465,
  60. }
  61. }
  62. // Dial dials and authenticates to an SMTP server. The returned SendCloser
  63. // should be closed when done using it.
  64. func (d *ClientImpl) Dial() (SendCloser, error) {
  65. conn, err := netDialTimeout("tcp", addr(d.Host, d.Port), 10*time.Second)
  66. if err != nil {
  67. return nil, err
  68. }
  69. if d.SSL {
  70. conn = tlsClient(conn, d.tlsConfig())
  71. }
  72. c, err := smtpNewClient(conn, d.Host)
  73. if err != nil {
  74. return nil, err
  75. }
  76. if d.LocalName != "" {
  77. if err := c.Hello(d.LocalName); err != nil {
  78. return nil, err
  79. }
  80. }
  81. if !d.SSL {
  82. if ok, _ := c.Extension("STARTTLS"); ok {
  83. if err := c.StartTLS(d.tlsConfig()); err != nil {
  84. c.Close()
  85. return nil, err
  86. }
  87. }
  88. }
  89. if d.Auth == nil && d.Username != "" {
  90. if ok, auths := c.Extension("AUTH"); ok {
  91. if strings.Contains(auths, "CRAM-MD5") {
  92. d.Auth = smtp.CRAMMD5Auth(d.Username, d.Password)
  93. } else if strings.Contains(auths, "LOGIN") &&
  94. !strings.Contains(auths, "PLAIN") {
  95. d.Auth = &loginAuth{
  96. username: d.Username,
  97. password: d.Password,
  98. host: d.Host,
  99. }
  100. } else {
  101. d.Auth = smtp.PlainAuth("", d.Username, d.Password, d.Host)
  102. }
  103. }
  104. }
  105. if d.Auth != nil {
  106. if err = c.Auth(d.Auth); err != nil {
  107. c.Close()
  108. return nil, err
  109. }
  110. }
  111. return &smtpSender{c, d}, nil
  112. }
  113. func (d *ClientImpl) tlsConfig() *tls.Config {
  114. if d.TLSConfig == nil {
  115. return &tls.Config{ServerName: d.Host}
  116. }
  117. return d.TLSConfig
  118. }
  119. func addr(host string, port int) string {
  120. return fmt.Sprintf("%s:%d", host, port)
  121. }
  122. // DialAndSend opens a connection to the SMTP server, sends the given emails and
  123. // closes the connection.
  124. func (d *ClientImpl) DialAndSend(m ...*Message) error {
  125. s, err := d.Dial()
  126. if err != nil {
  127. return err
  128. }
  129. defer s.Close()
  130. return Send(s, m...)
  131. }
  132. type smtpSender struct {
  133. smtpClient
  134. d *ClientImpl
  135. }
  136. func (c *smtpSender) Send(from string, to []string, msg io.WriterTo) error {
  137. if err := c.Mail(from); err != nil {
  138. if err == io.EOF {
  139. // This is probably due to a timeout, so reconnect and try again.
  140. sc, derr := c.d.Dial()
  141. if derr == nil {
  142. if s, ok := sc.(*smtpSender); ok {
  143. *c = *s
  144. return c.Send(from, to, msg)
  145. }
  146. }
  147. }
  148. return err
  149. }
  150. for _, addr := range to {
  151. if err := c.Rcpt(addr); err != nil {
  152. return err
  153. }
  154. }
  155. w, err := c.Data()
  156. if err != nil {
  157. return err
  158. }
  159. if _, err = msg.WriteTo(w); err != nil {
  160. w.Close()
  161. return err
  162. }
  163. return w.Close()
  164. }
  165. func (c *smtpSender) Close() error {
  166. return c.Quit()
  167. }
  168. // Stubbed out for tests.
  169. var (
  170. netDialTimeout = net.DialTimeout
  171. tlsClient = tls.Client
  172. smtpNewClient = func(conn net.Conn, host string) (smtpClient, error) {
  173. return smtp.NewClient(conn, host)
  174. }
  175. )
  176. type smtpClient interface {
  177. Hello(string) error
  178. Extension(string) (bool, string)
  179. StartTLS(*tls.Config) error
  180. Auth(smtp.Auth) error
  181. Mail(string) error
  182. Rcpt(string) error
  183. Data() (io.WriteCloser, error)
  184. Quit() error
  185. Close() error
  186. }