smtp.go 14 KB

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