email.go 17 KB

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