smtp.go 15 KB

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