smtp.go 13 KB

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