smtp.go 13 KB

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