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 13KB

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