Simple Golang SMTP relay/proxy server
go
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

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