email.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. // Package email is designed to provide an "email interface for humans."
  2. // Designed to be robust and flexible, the email package aims to make sending email easy without getting in the way.
  3. package email
  4. import (
  5. "bufio"
  6. "bytes"
  7. "crypto/rand"
  8. "crypto/tls"
  9. "encoding/base64"
  10. "errors"
  11. "fmt"
  12. "io"
  13. "math"
  14. "math/big"
  15. "mime"
  16. "mime/multipart"
  17. "mime/quotedprintable"
  18. "net/mail"
  19. "net/smtp"
  20. "net/textproto"
  21. "os"
  22. "path/filepath"
  23. "strings"
  24. "time"
  25. "unicode"
  26. )
  27. const (
  28. MaxLineLength = 76 // MaxLineLength is the maximum line length per RFC 2045
  29. defaultContentType = "text/plain; charset=us-ascii" // defaultContentType is the default Content-Type according to RFC 2045, section 5.2
  30. )
  31. // ErrMissingBoundary is returned when there is no boundary given for a multipart entity
  32. var ErrMissingBoundary = errors.New("No boundary found for multipart entity")
  33. // ErrMissingContentType is returned when there is no "Content-Type" header for a MIME entity
  34. var ErrMissingContentType = errors.New("No Content-Type found for MIME entity")
  35. // Email is the type used for email messages
  36. type Email struct {
  37. ReplyTo []string
  38. From string
  39. To []string
  40. Bcc []string
  41. Cc []string
  42. Subject string
  43. Text []byte // Plaintext message (optional)
  44. HTML []byte // Html message (optional)
  45. Sender string // override From as SMTP envelope sender (optional)
  46. Headers textproto.MIMEHeader
  47. Attachments []*Attachment
  48. ReadReceipt []string
  49. }
  50. // part is a copyable representation of a multipart.Part
  51. type part struct {
  52. header textproto.MIMEHeader
  53. body []byte
  54. }
  55. // NewEmail creates an Email, and returns the pointer to it.
  56. func NewEmail() *Email {
  57. return &Email{Headers: textproto.MIMEHeader{}}
  58. }
  59. // trimReader is a custom io.Reader that will trim any leading
  60. // whitespace, as this can cause email imports to fail.
  61. type trimReader struct {
  62. rd io.Reader
  63. }
  64. // Read trims off any unicode whitespace from the originating reader
  65. func (tr trimReader) Read(buf []byte) (int, error) {
  66. n, err := tr.rd.Read(buf)
  67. t := bytes.TrimLeftFunc(buf[:n], unicode.IsSpace)
  68. n = copy(buf, t)
  69. return n, err
  70. }
  71. // NewEmailFromReader reads a stream of bytes from an io.Reader, r,
  72. // and returns an email struct containing the parsed data.
  73. // This function expects the data in RFC 5322 format.
  74. func NewEmailFromReader(r io.Reader) (*Email, error) {
  75. e := NewEmail()
  76. s := trimReader{rd: r}
  77. tp := textproto.NewReader(bufio.NewReader(s))
  78. // Parse the main headers
  79. hdrs, err := tp.ReadMIMEHeader()
  80. if err != nil {
  81. return e, err
  82. }
  83. // Set the subject, to, cc, bcc, and from
  84. for h, v := range hdrs {
  85. switch {
  86. case h == "Subject":
  87. e.Subject = v[0]
  88. subj, err := (&mime.WordDecoder{}).DecodeHeader(e.Subject)
  89. if err == nil && len(subj) > 0 {
  90. e.Subject = subj
  91. }
  92. delete(hdrs, h)
  93. case h == "To":
  94. for _, to := range v {
  95. tt, err := (&mime.WordDecoder{}).DecodeHeader(to)
  96. if err == nil {
  97. e.To = append(e.To, tt)
  98. } else {
  99. e.To = append(e.To, to)
  100. }
  101. }
  102. delete(hdrs, h)
  103. case h == "Cc":
  104. for _, cc := range v {
  105. tcc, err := (&mime.WordDecoder{}).DecodeHeader(cc)
  106. if err == nil {
  107. e.Cc = append(e.Cc, tcc)
  108. } else {
  109. e.Cc = append(e.Cc, cc)
  110. }
  111. }
  112. delete(hdrs, h)
  113. case h == "Bcc":
  114. for _, bcc := range v {
  115. tbcc, err := (&mime.WordDecoder{}).DecodeHeader(bcc)
  116. if err == nil {
  117. e.Bcc = append(e.Bcc, tbcc)
  118. } else {
  119. e.Bcc = append(e.Bcc, bcc)
  120. }
  121. }
  122. delete(hdrs, h)
  123. case h == "From":
  124. e.From = v[0]
  125. fr, err := (&mime.WordDecoder{}).DecodeHeader(e.From)
  126. if err == nil && len(fr) > 0 {
  127. e.From = fr
  128. }
  129. delete(hdrs, h)
  130. }
  131. }
  132. e.Headers = hdrs
  133. body := tp.R
  134. // Recursively parse the MIME parts
  135. ps, err := parseMIMEParts(e.Headers, body)
  136. if err != nil {
  137. return e, err
  138. }
  139. for _, p := range ps {
  140. if ct := p.header.Get("Content-Type"); ct == "" {
  141. return e, ErrMissingContentType
  142. }
  143. ct, _, err := mime.ParseMediaType(p.header.Get("Content-Type"))
  144. if err != nil {
  145. return e, err
  146. }
  147. switch {
  148. case ct == "text/plain":
  149. e.Text = p.body
  150. case ct == "text/html":
  151. e.HTML = p.body
  152. }
  153. }
  154. return e, nil
  155. }
  156. // parseMIMEParts will recursively walk a MIME entity and return a []mime.Part containing
  157. // each (flattened) mime.Part found.
  158. // It is important to note that there are no limits to the number of recursions, so be
  159. // careful when parsing unknown MIME structures!
  160. func parseMIMEParts(hs textproto.MIMEHeader, b io.Reader) ([]*part, error) {
  161. var ps []*part
  162. // If no content type is given, set it to the default
  163. if _, ok := hs["Content-Type"]; !ok {
  164. hs.Set("Content-Type", defaultContentType)
  165. }
  166. ct, params, err := mime.ParseMediaType(hs.Get("Content-Type"))
  167. if err != nil {
  168. return ps, err
  169. }
  170. // If it's a multipart email, recursively parse the parts
  171. if strings.HasPrefix(ct, "multipart/") {
  172. if _, ok := params["boundary"]; !ok {
  173. return ps, ErrMissingBoundary
  174. }
  175. mr := multipart.NewReader(b, params["boundary"])
  176. for {
  177. var buf bytes.Buffer
  178. p, err := mr.NextPart()
  179. if err == io.EOF {
  180. break
  181. }
  182. if err != nil {
  183. return ps, err
  184. }
  185. if _, ok := p.Header["Content-Type"]; !ok {
  186. p.Header.Set("Content-Type", defaultContentType)
  187. }
  188. subct, _, err := mime.ParseMediaType(p.Header.Get("Content-Type"))
  189. if err != nil {
  190. return ps, err
  191. }
  192. if strings.HasPrefix(subct, "multipart/") {
  193. sps, err := parseMIMEParts(p.Header, p)
  194. if err != nil {
  195. return ps, err
  196. }
  197. ps = append(ps, sps...)
  198. } else {
  199. var reader io.Reader
  200. reader = p
  201. const cte = "Content-Transfer-Encoding"
  202. if p.Header.Get(cte) == "base64" {
  203. reader = base64.NewDecoder(base64.StdEncoding, reader)
  204. }
  205. // Otherwise, just append the part to the list
  206. // Copy the part data into the buffer
  207. if _, err := io.Copy(&buf, reader); err != nil {
  208. return ps, err
  209. }
  210. ps = append(ps, &part{body: buf.Bytes(), header: p.Header})
  211. }
  212. }
  213. } else {
  214. // If it is not a multipart email, parse the body content as a single "part"
  215. var buf bytes.Buffer
  216. if _, err := io.Copy(&buf, b); err != nil {
  217. return ps, err
  218. }
  219. ps = append(ps, &part{body: buf.Bytes(), header: hs})
  220. }
  221. return ps, nil
  222. }
  223. // Attach is used to attach content from an io.Reader to the email.
  224. // Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type
  225. // The function will return the created Attachment for reference, as well as nil for the error, if successful.
  226. func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
  227. var buffer bytes.Buffer
  228. if _, err = io.Copy(&buffer, r); err != nil {
  229. return
  230. }
  231. at := &Attachment{
  232. Filename: filename,
  233. Header: textproto.MIMEHeader{},
  234. Content: buffer.Bytes(),
  235. }
  236. // Get the Content-Type to be used in the MIMEHeader
  237. if c != "" {
  238. at.Header.Set("Content-Type", c)
  239. } else {
  240. // If the Content-Type is blank, set the Content-Type to "application/octet-stream"
  241. at.Header.Set("Content-Type", "application/octet-stream")
  242. }
  243. at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
  244. at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))
  245. at.Header.Set("Content-Transfer-Encoding", "base64")
  246. e.Attachments = append(e.Attachments, at)
  247. return at, nil
  248. }
  249. // AttachFile is used to attach content to the email.
  250. // It attempts to open the file referenced by filename and, if successful, creates an Attachment.
  251. // This Attachment is then appended to the slice of Email.Attachments.
  252. // The function will then return the Attachment for reference, as well as nil for the error, if successful.
  253. func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
  254. f, err := os.Open(filename)
  255. if err != nil {
  256. return
  257. }
  258. defer f.Close()
  259. ct := mime.TypeByExtension(filepath.Ext(filename))
  260. basename := filepath.Base(filename)
  261. return e.Attach(f, basename, ct)
  262. }
  263. // msgHeaders merges the Email's various fields and custom headers together in a
  264. // standards compliant way to create a MIMEHeader to be used in the resulting
  265. // message. It does not alter e.Headers.
  266. //
  267. // "e"'s fields To, Cc, From, Subject will be used unless they are present in
  268. // e.Headers. Unless set in e.Headers, "Date" will filled with the current time.
  269. func (e *Email) msgHeaders() (textproto.MIMEHeader, error) {
  270. res := make(textproto.MIMEHeader, len(e.Headers)+4)
  271. if e.Headers != nil {
  272. for _, h := range []string{"Reply-To", "To", "Cc", "From", "Subject", "Date", "Message-Id", "MIME-Version"} {
  273. if v, ok := e.Headers[h]; ok {
  274. res[h] = v
  275. }
  276. }
  277. }
  278. // Set headers if there are values.
  279. if _, ok := res["Reply-To"]; !ok && len(e.ReplyTo) > 0 {
  280. res.Set("Reply-To", strings.Join(e.ReplyTo, ", "))
  281. }
  282. if _, ok := res["To"]; !ok && len(e.To) > 0 {
  283. res.Set("To", strings.Join(e.To, ", "))
  284. }
  285. if _, ok := res["Cc"]; !ok && len(e.Cc) > 0 {
  286. res.Set("Cc", strings.Join(e.Cc, ", "))
  287. }
  288. if _, ok := res["Subject"]; !ok && e.Subject != "" {
  289. res.Set("Subject", e.Subject)
  290. }
  291. if _, ok := res["Message-Id"]; !ok {
  292. id, err := generateMessageID()
  293. if err != nil {
  294. return nil, err
  295. }
  296. res.Set("Message-Id", id)
  297. }
  298. // Date and From are required headers.
  299. if _, ok := res["From"]; !ok {
  300. res.Set("From", e.From)
  301. }
  302. if _, ok := res["Date"]; !ok {
  303. res.Set("Date", time.Now().Format(time.RFC1123Z))
  304. }
  305. if _, ok := res["MIME-Version"]; !ok {
  306. res.Set("MIME-Version", "1.0")
  307. }
  308. for field, vals := range e.Headers {
  309. if _, ok := res[field]; !ok {
  310. res[field] = vals
  311. }
  312. }
  313. return res, nil
  314. }
  315. func writeMessage(buff io.Writer, msg []byte, multipart bool, mediaType string, w *multipart.Writer) error {
  316. if multipart {
  317. header := textproto.MIMEHeader{
  318. "Content-Type": {mediaType + "; charset=UTF-8"},
  319. "Content-Transfer-Encoding": {"quoted-printable"},
  320. }
  321. if _, err := w.CreatePart(header); err != nil {
  322. return err
  323. }
  324. }
  325. qp := quotedprintable.NewWriter(buff)
  326. // Write the text
  327. if _, err := qp.Write(msg); err != nil {
  328. return err
  329. }
  330. return qp.Close()
  331. }
  332. // Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
  333. func (e *Email) Bytes() ([]byte, error) {
  334. // TODO: better guess buffer size
  335. buff := bytes.NewBuffer(make([]byte, 0, 4096))
  336. headers, err := e.msgHeaders()
  337. if err != nil {
  338. return nil, err
  339. }
  340. var (
  341. isMixed = len(e.Attachments) > 0
  342. isAlternative = len(e.Text) > 0 && len(e.HTML) > 0
  343. )
  344. var w *multipart.Writer
  345. if isMixed || isAlternative {
  346. w = multipart.NewWriter(buff)
  347. }
  348. switch {
  349. case isMixed:
  350. headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary())
  351. case isAlternative:
  352. headers.Set("Content-Type", "multipart/alternative;\r\n boundary="+w.Boundary())
  353. case len(e.HTML) > 0:
  354. headers.Set("Content-Type", "text/html; charset=UTF-8")
  355. headers.Set("Content-Transfer-Encoding", "quoted-printable")
  356. default:
  357. headers.Set("Content-Type", "text/plain; charset=UTF-8")
  358. headers.Set("Content-Transfer-Encoding", "quoted-printable")
  359. }
  360. headerToBytes(buff, headers)
  361. _, err = io.WriteString(buff, "\r\n")
  362. if err != nil {
  363. return nil, err
  364. }
  365. // Check to see if there is a Text or HTML field
  366. if len(e.Text) > 0 || len(e.HTML) > 0 {
  367. var subWriter *multipart.Writer
  368. if isMixed && isAlternative {
  369. // Create the multipart alternative part
  370. subWriter = multipart.NewWriter(buff)
  371. header := textproto.MIMEHeader{
  372. "Content-Type": {"multipart/alternative;\r\n boundary=" + subWriter.Boundary()},
  373. }
  374. if _, err := w.CreatePart(header); err != nil {
  375. return nil, err
  376. }
  377. } else {
  378. subWriter = w
  379. }
  380. // Create the body sections
  381. if len(e.Text) > 0 {
  382. // Write the text
  383. if err := writeMessage(buff, e.Text, isMixed || isAlternative, "text/plain", subWriter); err != nil {
  384. return nil, err
  385. }
  386. }
  387. if len(e.HTML) > 0 {
  388. // Write the HTML
  389. if err := writeMessage(buff, e.HTML, isMixed || isAlternative, "text/html", subWriter); err != nil {
  390. return nil, err
  391. }
  392. }
  393. if isMixed && isAlternative {
  394. if err := subWriter.Close(); err != nil {
  395. return nil, err
  396. }
  397. }
  398. }
  399. // Create attachment part, if necessary
  400. for _, a := range e.Attachments {
  401. ap, err := w.CreatePart(a.Header)
  402. if err != nil {
  403. return nil, err
  404. }
  405. // Write the base64Wrapped content to the part
  406. base64Wrap(ap, a.Content)
  407. }
  408. if isMixed || isAlternative {
  409. if err := w.Close(); err != nil {
  410. return nil, err
  411. }
  412. }
  413. return buff.Bytes(), nil
  414. }
  415. // Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
  416. // This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
  417. func (e *Email) Send(addr string, a smtp.Auth) error {
  418. // Merge the To, Cc, and Bcc fields
  419. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  420. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  421. for i := 0; i < len(to); i++ {
  422. addr, err := mail.ParseAddress(to[i])
  423. if err != nil {
  424. return err
  425. }
  426. to[i] = addr.Address
  427. }
  428. // Check to make sure there is at least one recipient and one "From" address
  429. if e.From == "" || len(to) == 0 {
  430. return errors.New("Must specify at least one From address and one To address")
  431. }
  432. sender, err := e.parseSender()
  433. if err != nil {
  434. return err
  435. }
  436. raw, err := e.Bytes()
  437. if err != nil {
  438. return err
  439. }
  440. return smtp.SendMail(addr, a, sender, to, raw)
  441. }
  442. // Select and parse an SMTP envelope sender address. Choose Email.Sender if set, or fallback to Email.From.
  443. func (e *Email) parseSender() (string, error) {
  444. if e.Sender != "" {
  445. sender, err := mail.ParseAddress(e.Sender)
  446. if err != nil {
  447. return "", err
  448. }
  449. return sender.Address, nil
  450. } else {
  451. from, err := mail.ParseAddress(e.From)
  452. if err != nil {
  453. return "", err
  454. }
  455. return from.Address, nil
  456. }
  457. }
  458. // SendWithTLS sends an email with an optional TLS config.
  459. // This is helpful if you need to connect to a host that is used an untrusted
  460. // certificate.
  461. func (e *Email) SendWithTLS(addr string, a smtp.Auth, t *tls.Config) error {
  462. // Merge the To, Cc, and Bcc fields
  463. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  464. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  465. for i := 0; i < len(to); i++ {
  466. addr, err := mail.ParseAddress(to[i])
  467. if err != nil {
  468. return err
  469. }
  470. to[i] = addr.Address
  471. }
  472. // Check to make sure there is at least one recipient and one "From" address
  473. if e.From == "" || len(to) == 0 {
  474. return errors.New("Must specify at least one From address and one To address")
  475. }
  476. sender, err := e.parseSender()
  477. if err != nil {
  478. return err
  479. }
  480. raw, err := e.Bytes()
  481. if err != nil {
  482. return err
  483. }
  484. conn, err := tls.Dial("tcp", addr, t)
  485. if err != nil {
  486. return err
  487. }
  488. c, err := smtp.NewClient(conn, t.ServerName)
  489. if err != nil {
  490. return err
  491. }
  492. defer c.Close()
  493. if err = c.Hello("localhost"); err != nil {
  494. return err
  495. }
  496. // Use TLS if available
  497. if ok, _ := c.Extension("STARTTLS"); ok {
  498. if err = c.StartTLS(t); err != nil {
  499. return err
  500. }
  501. }
  502. if a != nil {
  503. if ok, _ := c.Extension("AUTH"); ok {
  504. if err = c.Auth(a); err != nil {
  505. return err
  506. }
  507. }
  508. }
  509. if err = c.Mail(sender); err != nil {
  510. return err
  511. }
  512. for _, addr := range to {
  513. if err = c.Rcpt(addr); err != nil {
  514. return err
  515. }
  516. }
  517. w, err := c.Data()
  518. if err != nil {
  519. return err
  520. }
  521. _, err = w.Write(raw)
  522. if err != nil {
  523. return err
  524. }
  525. err = w.Close()
  526. if err != nil {
  527. return err
  528. }
  529. return c.Quit()
  530. }
  531. // Attachment is a struct representing an email attachment.
  532. // Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
  533. type Attachment struct {
  534. Filename string
  535. Header textproto.MIMEHeader
  536. Content []byte
  537. }
  538. // base64Wrap encodes the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
  539. // The output is then written to the specified io.Writer
  540. func base64Wrap(w io.Writer, b []byte) {
  541. // 57 raw bytes per 76-byte base64 line.
  542. const maxRaw = 57
  543. // Buffer for each line, including trailing CRLF.
  544. buffer := make([]byte, MaxLineLength+len("\r\n"))
  545. copy(buffer[MaxLineLength:], "\r\n")
  546. // Process raw chunks until there's no longer enough to fill a line.
  547. for len(b) >= maxRaw {
  548. base64.StdEncoding.Encode(buffer, b[:maxRaw])
  549. w.Write(buffer)
  550. b = b[maxRaw:]
  551. }
  552. // Handle the last chunk of bytes.
  553. if len(b) > 0 {
  554. out := buffer[:base64.StdEncoding.EncodedLen(len(b))]
  555. base64.StdEncoding.Encode(out, b)
  556. out = append(out, "\r\n"...)
  557. w.Write(out)
  558. }
  559. }
  560. // headerToBytes renders "header" to "buff". If there are multiple values for a
  561. // field, multiple "Field: value\r\n" lines will be emitted.
  562. func headerToBytes(buff io.Writer, header textproto.MIMEHeader) {
  563. for field, vals := range header {
  564. for _, subval := range vals {
  565. // bytes.Buffer.Write() never returns an error.
  566. io.WriteString(buff, field)
  567. io.WriteString(buff, ": ")
  568. // Write the encoded header if needed
  569. switch {
  570. case field == "Content-Type" || field == "Content-Disposition":
  571. buff.Write([]byte(subval))
  572. default:
  573. buff.Write([]byte(mime.QEncoding.Encode("UTF-8", subval)))
  574. }
  575. io.WriteString(buff, "\r\n")
  576. }
  577. }
  578. }
  579. var maxBigInt = big.NewInt(math.MaxInt64)
  580. // generateMessageID generates and returns a string suitable for an RFC 2822
  581. // compliant Message-ID, e.g.:
  582. // <1444789264909237300.3464.1819418242800517193@DESKTOP01>
  583. //
  584. // The following parameters are used to generate a Message-ID:
  585. // - The nanoseconds since Epoch
  586. // - The calling PID
  587. // - A cryptographically random int64
  588. // - The sending hostname
  589. func generateMessageID() (string, error) {
  590. t := time.Now().UnixNano()
  591. pid := os.Getpid()
  592. rint, err := rand.Int(rand.Reader, maxBigInt)
  593. if err != nil {
  594. return "", err
  595. }
  596. h, err := os.Hostname()
  597. // If we can't get the hostname, we'll use localhost
  598. if err != nil {
  599. h = "localhost.localdomain"
  600. }
  601. msgid := fmt.Sprintf("<%d.%d.%d@%s>", t, pid, rint, h)
  602. return msgid, nil
  603. }