smtp.go 13 KB

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