You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

smtp.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. // Copyright 2010 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package smtp implements the Simple Mail Transfer Protocol as defined in RFC 5321.
  5. // It also implements the following extensions:
  6. //
  7. // 8BITMIME RFC 1652
  8. // AUTH RFC 2554
  9. // STARTTLS RFC 3207
  10. //
  11. // Additional extensions may be handled by clients.
  12. //
  13. // The smtp package is frozen and is not accepting new features.
  14. // Some external packages provide more functionality. See:
  15. //
  16. // https://godoc.org/?q=smtp
  17. package smtp
  18. import (
  19. "crypto/tls"
  20. "encoding/base64"
  21. "errors"
  22. "fmt"
  23. "io"
  24. "net"
  25. "net/textproto"
  26. "strings"
  27. "time"
  28. )
  29. var (
  30. ErrTimedOut = errors.New("Timed out")
  31. )
  32. // A Client represents a client connection to an SMTP server.
  33. type Client struct {
  34. // Text is the textproto.Conn used by the Client. It is exported to allow for
  35. // clients to add extensions.
  36. Text *textproto.Conn
  37. // keep a reference to the connection so it can be used to create a TLS
  38. // connection later
  39. conn net.Conn
  40. // whether the Client is using TLS
  41. tls bool
  42. serverName string
  43. // map of supported extensions
  44. ext map[string]string
  45. // supported auth mechanisms
  46. auth []string
  47. localName string // the name to use in HELO/EHLO
  48. didHello bool // whether we've said HELO/EHLO
  49. helloError error // the error from the hello
  50. }
  51. // Dial returns a new Client connected to an SMTP server at addr.
  52. // The addr must include a port, as in "mail.example.com:smtp".
  53. func Dial(addr string, timeout time.Duration, implicitTLS bool) (*Client, error) {
  54. var conn net.Conn
  55. var err error
  56. dialer := net.Dialer{
  57. Timeout: timeout,
  58. }
  59. start := time.Now()
  60. if !implicitTLS {
  61. conn, err = dialer.Dial("tcp", addr)
  62. } else {
  63. conn, err = tls.DialWithDialer(&dialer, "tcp", addr, nil)
  64. }
  65. if err != nil {
  66. return nil, err
  67. }
  68. if timeout != 0 {
  69. remaining := timeout - time.Since(start)
  70. if remaining <= 0 {
  71. return nil, ErrTimedOut
  72. }
  73. conn.SetDeadline(time.Now().Add(remaining))
  74. }
  75. host, _, _ := net.SplitHostPort(addr)
  76. return NewClient(conn, host)
  77. }
  78. // NewClient returns a new Client using an existing connection and host as a
  79. // server name to be used when authenticating.
  80. func NewClient(conn net.Conn, host string) (*Client, error) {
  81. text := textproto.NewConn(conn)
  82. _, _, err := text.ReadResponse(220)
  83. if err != nil {
  84. text.Close()
  85. return nil, err
  86. }
  87. c := &Client{Text: text, conn: conn, serverName: host, localName: "localhost"}
  88. _, c.tls = conn.(*tls.Conn)
  89. return c, nil
  90. }
  91. // Close closes the connection.
  92. func (c *Client) Close() error {
  93. return c.Text.Close()
  94. }
  95. // hello runs a hello exchange if needed.
  96. func (c *Client) hello() error {
  97. if !c.didHello {
  98. c.didHello = true
  99. err := c.ehlo()
  100. if err != nil {
  101. c.helloError = c.helo()
  102. }
  103. }
  104. return c.helloError
  105. }
  106. // Hello sends a HELO or EHLO to the server as the given host name.
  107. // Calling this method is only necessary if the client needs control
  108. // over the host name used. The client will introduce itself as "localhost"
  109. // automatically otherwise. If Hello is called, it must be called before
  110. // any of the other methods.
  111. func (c *Client) Hello(localName string) error {
  112. if err := validateLine(localName); err != nil {
  113. return err
  114. }
  115. if c.didHello {
  116. return errors.New("smtp: Hello called after other methods")
  117. }
  118. c.localName = localName
  119. return c.hello()
  120. }
  121. // cmd is a convenience function that sends a command and returns the response
  122. func (c *Client) cmd(expectCode int, format string, args ...interface{}) (int, string, error) {
  123. id, err := c.Text.Cmd(format, args...)
  124. if err != nil {
  125. return 0, "", err
  126. }
  127. c.Text.StartResponse(id)
  128. defer c.Text.EndResponse(id)
  129. code, msg, err := c.Text.ReadResponse(expectCode)
  130. return code, msg, err
  131. }
  132. // helo sends the HELO greeting to the server. It should be used only when the
  133. // server does not support ehlo.
  134. func (c *Client) helo() error {
  135. c.ext = nil
  136. _, _, err := c.cmd(250, "HELO %s", c.localName)
  137. return err
  138. }
  139. // ehlo sends the EHLO (extended hello) greeting to the server. It
  140. // should be the preferred greeting for servers that support it.
  141. func (c *Client) ehlo() error {
  142. _, msg, err := c.cmd(250, "EHLO %s", c.localName)
  143. if err != nil {
  144. return err
  145. }
  146. ext := make(map[string]string)
  147. extList := strings.Split(msg, "\n")
  148. if len(extList) > 1 {
  149. extList = extList[1:]
  150. for _, line := range extList {
  151. args := strings.SplitN(line, " ", 2)
  152. if len(args) > 1 {
  153. ext[args[0]] = args[1]
  154. } else {
  155. ext[args[0]] = ""
  156. }
  157. }
  158. }
  159. if mechs, ok := ext["AUTH"]; ok {
  160. c.auth = strings.Split(mechs, " ")
  161. }
  162. c.ext = ext
  163. return err
  164. }
  165. // StartTLS sends the STARTTLS command and encrypts all further communication.
  166. // Only servers that advertise the STARTTLS extension support this function.
  167. func (c *Client) StartTLS(config *tls.Config) error {
  168. if err := c.hello(); err != nil {
  169. return err
  170. }
  171. _, _, err := c.cmd(220, "STARTTLS")
  172. if err != nil {
  173. return err
  174. }
  175. c.conn = tls.Client(c.conn, config)
  176. c.Text = textproto.NewConn(c.conn)
  177. c.tls = true
  178. return c.ehlo()
  179. }
  180. // TLSConnectionState returns the client's TLS connection state.
  181. // The return values are their zero values if StartTLS did
  182. // not succeed.
  183. func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool) {
  184. tc, ok := c.conn.(*tls.Conn)
  185. if !ok {
  186. return
  187. }
  188. return tc.ConnectionState(), true
  189. }
  190. // Verify checks the validity of an email address on the server.
  191. // If Verify returns nil, the address is valid. A non-nil return
  192. // does not necessarily indicate an invalid address. Many servers
  193. // will not verify addresses for security reasons.
  194. func (c *Client) Verify(addr string) error {
  195. if err := validateLine(addr); err != nil {
  196. return err
  197. }
  198. if err := c.hello(); err != nil {
  199. return err
  200. }
  201. _, _, err := c.cmd(250, "VRFY %s", addr)
  202. return err
  203. }
  204. // Auth authenticates a client using the provided authentication mechanism.
  205. // A failed authentication closes the connection.
  206. // Only servers that advertise the AUTH extension support this function.
  207. func (c *Client) Auth(a Auth) error {
  208. if err := c.hello(); err != nil {
  209. return err
  210. }
  211. encoding := base64.StdEncoding
  212. mech, resp, err := a.Start(&ServerInfo{c.serverName, c.tls, c.auth})
  213. if err != nil {
  214. c.Quit()
  215. return err
  216. }
  217. resp64 := make([]byte, encoding.EncodedLen(len(resp)))
  218. encoding.Encode(resp64, resp)
  219. code, msg64, err := c.cmd(0, strings.TrimSpace(fmt.Sprintf("AUTH %s %s", mech, resp64)))
  220. for err == nil {
  221. var msg []byte
  222. switch code {
  223. case 334:
  224. msg, err = encoding.DecodeString(msg64)
  225. case 235:
  226. // the last message isn't base64 because it isn't a challenge
  227. msg = []byte(msg64)
  228. default:
  229. err = &textproto.Error{Code: code, Msg: msg64}
  230. }
  231. if err == nil {
  232. resp, err = a.Next(msg, code == 334)
  233. }
  234. if err != nil {
  235. // abort the AUTH
  236. c.cmd(501, "*")
  237. c.Quit()
  238. break
  239. }
  240. if resp == nil {
  241. break
  242. }
  243. resp64 = make([]byte, encoding.EncodedLen(len(resp)))
  244. encoding.Encode(resp64, resp)
  245. code, msg64, err = c.cmd(0, string(resp64))
  246. }
  247. return err
  248. }
  249. // Mail issues a MAIL command to the server using the provided email address.
  250. // If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME
  251. // parameter.
  252. // This initiates a mail transaction and is followed by one or more Rcpt calls.
  253. func (c *Client) Mail(from string) error {
  254. if err := validateLine(from); err != nil {
  255. return err
  256. }
  257. if err := c.hello(); err != nil {
  258. return err
  259. }
  260. cmdStr := "MAIL FROM:<%s>"
  261. if c.ext != nil {
  262. if _, ok := c.ext["8BITMIME"]; ok {
  263. cmdStr += " BODY=8BITMIME"
  264. }
  265. }
  266. _, _, err := c.cmd(250, cmdStr, from)
  267. return err
  268. }
  269. // Rcpt issues a RCPT command to the server using the provided email address.
  270. // A call to Rcpt must be preceded by a call to Mail and may be followed by
  271. // a Data call or another Rcpt call.
  272. func (c *Client) Rcpt(to string) error {
  273. if err := validateLine(to); err != nil {
  274. return err
  275. }
  276. _, _, err := c.cmd(25, "RCPT TO:<%s>", to)
  277. return err
  278. }
  279. type dataCloser struct {
  280. c *Client
  281. io.WriteCloser
  282. }
  283. func (d *dataCloser) Close() error {
  284. d.WriteCloser.Close()
  285. _, _, err := d.c.Text.ReadResponse(250)
  286. return err
  287. }
  288. // Data issues a DATA command to the server and returns a writer that
  289. // can be used to write the mail headers and body. The caller should
  290. // close the writer before calling any more methods on c. A call to
  291. // Data must be preceded by one or more calls to Rcpt.
  292. func (c *Client) Data() (io.WriteCloser, error) {
  293. _, _, err := c.cmd(354, "DATA")
  294. if err != nil {
  295. return nil, err
  296. }
  297. return &dataCloser{c, c.Text.DotWriter()}, nil
  298. }
  299. var testHookStartTLS func(*tls.Config) // nil, except for tests
  300. // SendMail connects to the server at addr, switches to TLS if
  301. // possible, authenticates with the optional mechanism a if possible,
  302. // and then sends an email from address from, to addresses to, with
  303. // message msg.
  304. // The addr must include a port, as in "mail.example.com:smtp".
  305. //
  306. // The addresses in the to parameter are the SMTP RCPT addresses.
  307. //
  308. // The msg parameter should be an RFC 822-style email with headers
  309. // first, a blank line, and then the message body. The lines of msg
  310. // should be CRLF terminated. The msg headers should usually include
  311. // fields such as "From", "To", "Subject", and "Cc". Sending "Bcc"
  312. // messages is accomplished by including an email address in the to
  313. // parameter but not including it in the msg headers.
  314. //
  315. // The SendMail function and the net/smtp package are low-level
  316. // mechanisms and provide no support for DKIM signing, MIME
  317. // attachments (see the mime/multipart package), or other mail
  318. // functionality. Higher-level packages exist outside of the standard
  319. // library.
  320. // XXX: modified in Ergo to add `requireTLS`, `heloDomain`, and `timeout` arguments
  321. func SendMail(addr string, a Auth, heloDomain string, from string, to []string, msg []byte, requireTLS, implicitTLS bool, timeout time.Duration) error {
  322. if err := validateLine(from); err != nil {
  323. return err
  324. }
  325. for _, recp := range to {
  326. if err := validateLine(recp); err != nil {
  327. return err
  328. }
  329. }
  330. c, err := Dial(addr, timeout, implicitTLS)
  331. if err != nil {
  332. return err
  333. }
  334. defer c.Close()
  335. if err = c.Hello(heloDomain); err != nil {
  336. return err
  337. }
  338. if !implicitTLS {
  339. if ok, _ := c.Extension("STARTTLS"); ok {
  340. var config *tls.Config
  341. if requireTLS {
  342. config = &tls.Config{ServerName: c.serverName}
  343. } else {
  344. // if TLS isn't a hard requirement, don't verify the certificate either,
  345. // since a MITM attacker could just remove the STARTTLS advertisement
  346. config = &tls.Config{InsecureSkipVerify: true}
  347. }
  348. if testHookStartTLS != nil {
  349. testHookStartTLS(config)
  350. }
  351. if err = c.StartTLS(config); err != nil {
  352. return err
  353. }
  354. } else if requireTLS {
  355. return errors.New("TLS required, but not negotiated")
  356. }
  357. }
  358. if a != nil && c.ext != nil {
  359. if _, ok := c.ext["AUTH"]; !ok {
  360. return errors.New("smtp: server doesn't support AUTH")
  361. }
  362. if err = c.Auth(a); err != nil {
  363. return err
  364. }
  365. }
  366. if err = c.Mail(from); err != nil {
  367. return err
  368. }
  369. for _, addr := range to {
  370. if err = c.Rcpt(addr); err != nil {
  371. return err
  372. }
  373. }
  374. w, err := c.Data()
  375. if err != nil {
  376. return err
  377. }
  378. _, err = w.Write(msg)
  379. if err != nil {
  380. return err
  381. }
  382. err = w.Close()
  383. if err != nil {
  384. return err
  385. }
  386. return c.Quit()
  387. }
  388. // Extension reports whether an extension is support by the server.
  389. // The extension name is case-insensitive. If the extension is supported,
  390. // Extension also returns a string that contains any parameters the
  391. // server specifies for the extension.
  392. func (c *Client) Extension(ext string) (bool, string) {
  393. if err := c.hello(); err != nil {
  394. return false, ""
  395. }
  396. if c.ext == nil {
  397. return false, ""
  398. }
  399. ext = strings.ToUpper(ext)
  400. param, ok := c.ext[ext]
  401. return ok, param
  402. }
  403. // Reset sends the RSET command to the server, aborting the current mail
  404. // transaction.
  405. func (c *Client) Reset() error {
  406. if err := c.hello(); err != nil {
  407. return err
  408. }
  409. _, _, err := c.cmd(250, "RSET")
  410. return err
  411. }
  412. // Noop sends the NOOP command to the server. It does nothing but check
  413. // that the connection to the server is okay.
  414. func (c *Client) Noop() error {
  415. if err := c.hello(); err != nil {
  416. return err
  417. }
  418. _, _, err := c.cmd(250, "NOOP")
  419. return err
  420. }
  421. // Quit sends the QUIT command and closes the connection to the server.
  422. func (c *Client) Quit() error {
  423. if err := c.hello(); err != nil {
  424. return err
  425. }
  426. _, _, err := c.cmd(221, "QUIT")
  427. if err != nil {
  428. return err
  429. }
  430. return c.Text.Close()
  431. }
  432. // validateLine checks to see if a line has CR or LF as per RFC 5321
  433. func validateLine(line string) error {
  434. if strings.ContainsAny(line, "\n\r") {
  435. return errors.New("smtp: A line must not contain CR or LF")
  436. }
  437. return nil
  438. }