smtp.go 15 KB

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