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