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

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