mysmtp.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. //
  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. type LoginAuth struct {
  30. userName string
  31. password string
  32. host string
  33. }
  34. func NewLoginAuth(userName, password, host string) smtp.Auth {
  35. return &(LoginAuth{userName, password, host})
  36. }
  37. func (auth *LoginAuth) Start(server *smtp.ServerInfo) (proto string, toServer []byte, err error) {
  38. if server.Name != auth.host {
  39. return "", nil, errors.New("wrong host name")
  40. }
  41. resp := []byte(auth.userName)
  42. return "LOGIN", resp, nil
  43. }
  44. func (auth *LoginAuth) Next(fromServer []byte, more bool) (toServer []byte, err error) {
  45. if more {
  46. return []byte(auth.password), nil
  47. }
  48. return nil, nil
  49. }
  50. // A Client represents a client connection to an SMTP server.
  51. type Client struct {
  52. // Text is the textproto.Conn used by the Client. It is exported to allow for
  53. // clients to add extensions.
  54. Text *textproto.Conn
  55. // keep a reference to the connection so it can be used to create a TLS
  56. // connection later
  57. conn net.Conn
  58. // whether the Client is using TLS
  59. tls bool
  60. serverName string
  61. // map of supported extensions
  62. ext map[string]string
  63. // supported auth mechanisms
  64. auth []string
  65. localName string // the name to use in HELO/EHLO
  66. didHello bool // whether we've said HELO/EHLO
  67. helloError error // the error from the hello
  68. }
  69. // Dial returns a new Client connected to an SMTP server at addr.
  70. // The addr must include a port, as in "mail.example.com:smtp".
  71. func Dial(addr string) (*Client, error) {
  72. conn, err := net.Dial("tcp", addr)
  73. if err != nil {
  74. return nil, err
  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 ...any) (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. k, v, _ := strings.Cut(line, " ")
  153. ext[k] = v
  154. }
  155. }
  156. if mechs, ok := ext["AUTH"]; ok {
  157. c.auth = strings.Split(mechs, " ")
  158. }
  159. c.ext = ext
  160. return err
  161. }
  162. // StartTLS sends the STARTTLS command and encrypts all further communication.
  163. // Only servers that advertise the STARTTLS extension support this function.
  164. func (c *Client) StartTLS(config *tls.Config) error {
  165. if err := c.hello(); err != nil {
  166. return err
  167. }
  168. _, _, err := c.cmd(220, "STARTTLS")
  169. if err != nil {
  170. return err
  171. }
  172. c.conn = tls.Client(c.conn, config)
  173. c.Text = textproto.NewConn(c.conn)
  174. c.tls = true
  175. return c.ehlo()
  176. }
  177. // TLSConnectionState returns the client's TLS connection state.
  178. // The return values are their zero values if StartTLS did
  179. // not succeed.
  180. func (c *Client) TLSConnectionState() (state tls.ConnectionState, ok bool) {
  181. tc, ok := c.conn.(*tls.Conn)
  182. if !ok {
  183. return
  184. }
  185. return tc.ConnectionState(), true
  186. }
  187. // Verify checks the validity of an email address on the server.
  188. // If Verify returns nil, the address is valid. A non-nil return
  189. // does not necessarily indicate an invalid address. Many servers
  190. // will not verify addresses for security reasons.
  191. func (c *Client) Verify(addr string) error {
  192. if err := validateLine(addr); err != nil {
  193. return err
  194. }
  195. if err := c.hello(); err != nil {
  196. return err
  197. }
  198. _, _, err := c.cmd(250, "VRFY %s", addr)
  199. return err
  200. }
  201. // Auth authenticates a client using the provided authentication mechanism.
  202. // A failed authentication closes the connection.
  203. // Only servers that advertise the AUTH extension support this function.
  204. func (c *Client) Auth(a smtp.Auth) error {
  205. if err := c.hello(); err != nil {
  206. return err
  207. }
  208. encoding := base64.StdEncoding
  209. mech, resp, err := a.Start(&smtp.ServerInfo{Name: c.serverName, TLS: c.tls, Auth: c.auth})
  210. if err != nil {
  211. c.Quit()
  212. return err
  213. }
  214. resp64 := make([]byte, encoding.EncodedLen(len(resp)))
  215. encoding.Encode(resp64, resp)
  216. code, msg64, err := c.cmd(0, strings.TrimSpace(fmt.Sprintf("AUTH %s %s", mech, resp64)))
  217. for err == nil {
  218. var msg []byte
  219. switch code {
  220. case 334:
  221. msg, err = encoding.DecodeString(msg64)
  222. case 235:
  223. // the last message isn't base64 because it isn't a challenge
  224. msg = []byte(msg64)
  225. default:
  226. err = &textproto.Error{Code: code, Msg: msg64}
  227. }
  228. if err == nil {
  229. resp, err = a.Next(msg, code == 334)
  230. }
  231. if err != nil {
  232. // abort the AUTH
  233. c.cmd(501, "*")
  234. c.Quit()
  235. break
  236. }
  237. if resp == nil {
  238. break
  239. }
  240. resp64 = make([]byte, encoding.EncodedLen(len(resp)))
  241. encoding.Encode(resp64, resp)
  242. code, msg64, err = c.cmd(0, string(resp64))
  243. }
  244. return err
  245. }
  246. // Mail issues a MAIL command to the server using the provided email address.
  247. // If the server supports the 8BITMIME extension, Mail adds the BODY=8BITMIME
  248. // parameter. If the server supports the SMTPUTF8 extension, Mail adds the
  249. // SMTPUTF8 parameter.
  250. // This initiates a mail transaction and is followed by one or more Rcpt calls.
  251. func (c *Client) Mail(from string) error {
  252. if err := validateLine(from); err != nil {
  253. return err
  254. }
  255. if err := c.hello(); err != nil {
  256. return err
  257. }
  258. cmdStr := "MAIL FROM:<%s>"
  259. if c.ext != nil {
  260. if _, ok := c.ext["8BITMIME"]; ok {
  261. cmdStr += " BODY=8BITMIME"
  262. }
  263. if _, ok := c.ext["SMTPUTF8"]; ok {
  264. cmdStr += " SMTPUTF8"
  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. // SendMail connects to the server at addr, switches to TLS if
  301. // possible, authenticates with the optional mechanism a if possible,
  302. // and then sends an email from address from, to addresses to, with
  303. // message msg.
  304. // The addr must include a port, as in "mail.example.com:smtp".
  305. //
  306. // The addresses in the to parameter are the SMTP RCPT addresses.
  307. //
  308. // The msg parameter should be an RFC 822-style email with headers
  309. // first, a blank line, and then the message body. The lines of msg
  310. // should be CRLF terminated. The msg headers should usually include
  311. // fields such as "From", "To", "Subject", and "Cc". Sending "Bcc"
  312. // messages is accomplished by including an email address in the to
  313. // parameter but not including it in the msg headers.
  314. //
  315. // The SendMail function and the net/smtp package are low-level
  316. // mechanisms and provide no support for DKIM signing, MIME
  317. // attachments (see the mime/multipart package), or other mail
  318. // functionality. Higher-level packages exist outside of the standard
  319. // library.
  320. func SendMail(addr string, a smtp.Auth, from string, to []string, msg []byte) error {
  321. if err := validateLine(from); err != nil {
  322. return err
  323. }
  324. for _, recp := range to {
  325. if err := validateLine(recp); err != nil {
  326. return err
  327. }
  328. }
  329. c, err := Dial(addr)
  330. if err != nil {
  331. return err
  332. }
  333. defer c.Close()
  334. if err = c.hello(); err != nil {
  335. return err
  336. }
  337. if a != nil && c.ext != nil {
  338. if _, ok := c.ext["AUTH"]; !ok {
  339. return errors.New("smtp: server doesn't support AUTH")
  340. }
  341. if err = c.Auth(a); err != nil {
  342. return err
  343. }
  344. }
  345. if err = c.Mail(from); err != nil {
  346. return err
  347. }
  348. for _, addr := range to {
  349. if err = c.Rcpt(addr); err != nil {
  350. return err
  351. }
  352. }
  353. w, err := c.Data()
  354. if err != nil {
  355. return err
  356. }
  357. _, err = w.Write(msg)
  358. if err != nil {
  359. return err
  360. }
  361. err = w.Close()
  362. if err != nil {
  363. return err
  364. }
  365. return c.Quit()
  366. }
  367. // Extension reports whether an extension is support by the server.
  368. // The extension name is case-insensitive. If the extension is supported,
  369. // Extension also returns a string that contains any parameters the
  370. // server specifies for the extension.
  371. func (c *Client) Extension(ext string) (bool, string) {
  372. if err := c.hello(); err != nil {
  373. return false, ""
  374. }
  375. if c.ext == nil {
  376. return false, ""
  377. }
  378. ext = strings.ToUpper(ext)
  379. param, ok := c.ext[ext]
  380. return ok, param
  381. }
  382. // Reset sends the RSET command to the server, aborting the current mail
  383. // transaction.
  384. func (c *Client) Reset() error {
  385. if err := c.hello(); err != nil {
  386. return err
  387. }
  388. _, _, err := c.cmd(250, "RSET")
  389. return err
  390. }
  391. // Noop sends the NOOP command to the server. It does nothing but check
  392. // that the connection to the server is okay.
  393. func (c *Client) Noop() error {
  394. if err := c.hello(); err != nil {
  395. return err
  396. }
  397. _, _, err := c.cmd(250, "NOOP")
  398. return err
  399. }
  400. // Quit sends the QUIT command and closes the connection to the server.
  401. func (c *Client) Quit() error {
  402. if err := c.hello(); err != nil {
  403. return err
  404. }
  405. _, _, err := c.cmd(221, "QUIT")
  406. if err != nil {
  407. return err
  408. }
  409. return c.Text.Close()
  410. }
  411. // validateLine checks to see if a line has CR or LF as per RFC 5321
  412. func validateLine(line string) error {
  413. if strings.ContainsAny(line, "\n\r") {
  414. return errors.New("smtp: A line must not contain CR or LF")
  415. }
  416. return nil
  417. }