smtp.go 13 KB

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