smtp.go 15 KB

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