smtp.go 12 KB

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