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

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