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

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