smtp.go 14 KB

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