email.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  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. if c != "" {
  237. at.Header.Set("Content-Type", c)
  238. } else {
  239. at.Header.Set("Content-Type", "application/octet-stream")
  240. }
  241. at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
  242. at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))
  243. at.Header.Set("Content-Transfer-Encoding", "base64")
  244. e.Attachments = append(e.Attachments, at)
  245. return at, nil
  246. }
  247. // AttachFile is used to attach content to the email.
  248. // It attempts to open the file referenced by filename and, if successful, creates an Attachment.
  249. // This Attachment is then appended to the slice of Email.Attachments.
  250. // The function will then return the Attachment for reference, as well as nil for the error, if successful.
  251. func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
  252. f, err := os.Open(filename)
  253. if err != nil {
  254. return
  255. }
  256. defer f.Close()
  257. ct := mime.TypeByExtension(filepath.Ext(filename))
  258. basename := filepath.Base(filename)
  259. return e.Attach(f, basename, ct)
  260. }
  261. // msgHeaders merges the Email's various fields and custom headers together in a
  262. // standards compliant way to create a MIMEHeader to be used in the resulting
  263. // message. It does not alter e.Headers.
  264. //
  265. // "e"'s fields To, Cc, From, Subject will be used unless they are present in
  266. // e.Headers. Unless set in e.Headers, "Date" will filled with the current time.
  267. func (e *Email) msgHeaders() (textproto.MIMEHeader, error) {
  268. res := make(textproto.MIMEHeader, len(e.Headers)+4)
  269. if e.Headers != nil {
  270. for _, h := range []string{"Reply-To", "To", "Cc", "From", "Subject", "Date", "Message-Id", "MIME-Version"} {
  271. if v, ok := e.Headers[h]; ok {
  272. res[h] = v
  273. }
  274. }
  275. }
  276. // Set headers if there are values.
  277. if _, ok := res["Reply-To"]; !ok && len(e.ReplyTo) > 0 {
  278. res.Set("Reply-To", strings.Join(e.ReplyTo, ", "))
  279. }
  280. if _, ok := res["To"]; !ok && len(e.To) > 0 {
  281. res.Set("To", strings.Join(e.To, ", "))
  282. }
  283. if _, ok := res["Cc"]; !ok && len(e.Cc) > 0 {
  284. res.Set("Cc", strings.Join(e.Cc, ", "))
  285. }
  286. if _, ok := res["Subject"]; !ok && e.Subject != "" {
  287. res.Set("Subject", e.Subject)
  288. }
  289. if _, ok := res["Message-Id"]; !ok {
  290. id, err := generateMessageID()
  291. if err != nil {
  292. return nil, err
  293. }
  294. res.Set("Message-Id", id)
  295. }
  296. // Date and From are required headers.
  297. if _, ok := res["From"]; !ok {
  298. res.Set("From", e.From)
  299. }
  300. if _, ok := res["Date"]; !ok {
  301. res.Set("Date", time.Now().Format(time.RFC1123Z))
  302. }
  303. if _, ok := res["MIME-Version"]; !ok {
  304. res.Set("MIME-Version", "1.0")
  305. }
  306. for field, vals := range e.Headers {
  307. if _, ok := res[field]; !ok {
  308. res[field] = vals
  309. }
  310. }
  311. return res, nil
  312. }
  313. func writeMessage(buff io.Writer, msg []byte, multipart bool, mediaType string, w *multipart.Writer) error {
  314. if multipart {
  315. header := textproto.MIMEHeader{
  316. "Content-Type": {mediaType + "; charset=UTF-8"},
  317. "Content-Transfer-Encoding": {"quoted-printable"},
  318. }
  319. if _, err := w.CreatePart(header); err != nil {
  320. return err
  321. }
  322. }
  323. qp := quotedprintable.NewWriter(buff)
  324. // Write the text
  325. if _, err := qp.Write(msg); err != nil {
  326. return err
  327. }
  328. return qp.Close()
  329. }
  330. // Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
  331. func (e *Email) Bytes() ([]byte, error) {
  332. // TODO: better guess buffer size
  333. buff := bytes.NewBuffer(make([]byte, 0, 4096))
  334. headers, err := e.msgHeaders()
  335. if err != nil {
  336. return nil, err
  337. }
  338. var (
  339. isMixed = len(e.Attachments) > 0
  340. isAlternative = len(e.Text) > 0 && len(e.HTML) > 0
  341. )
  342. var w *multipart.Writer
  343. if isMixed || isAlternative {
  344. w = multipart.NewWriter(buff)
  345. }
  346. switch {
  347. case isMixed:
  348. headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary())
  349. case isAlternative:
  350. headers.Set("Content-Type", "multipart/alternative;\r\n boundary="+w.Boundary())
  351. case len(e.HTML) > 0:
  352. headers.Set("Content-Type", "text/html; charset=UTF-8")
  353. headers.Set("Content-Transfer-Encoding", "quoted-printable")
  354. default:
  355. headers.Set("Content-Type", "text/plain; charset=UTF-8")
  356. headers.Set("Content-Transfer-Encoding", "quoted-printable")
  357. }
  358. headerToBytes(buff, headers)
  359. _, err = io.WriteString(buff, "\r\n")
  360. if err != nil {
  361. return nil, err
  362. }
  363. // Check to see if there is a Text or HTML field
  364. if len(e.Text) > 0 || len(e.HTML) > 0 {
  365. var subWriter *multipart.Writer
  366. if isMixed && isAlternative {
  367. // Create the multipart alternative part
  368. subWriter = multipart.NewWriter(buff)
  369. header := textproto.MIMEHeader{
  370. "Content-Type": {"multipart/alternative;\r\n boundary=" + subWriter.Boundary()},
  371. }
  372. if _, err := w.CreatePart(header); err != nil {
  373. return nil, err
  374. }
  375. } else {
  376. subWriter = w
  377. }
  378. // Create the body sections
  379. if len(e.Text) > 0 {
  380. // Write the text
  381. if err := writeMessage(buff, e.Text, isMixed || isAlternative, "text/plain", subWriter); err != nil {
  382. return nil, err
  383. }
  384. }
  385. if len(e.HTML) > 0 {
  386. // Write the HTML
  387. if err := writeMessage(buff, e.HTML, isMixed || isAlternative, "text/html", subWriter); err != nil {
  388. return nil, err
  389. }
  390. }
  391. if isMixed && isAlternative {
  392. if err := subWriter.Close(); err != nil {
  393. return nil, err
  394. }
  395. }
  396. }
  397. // Create attachment part, if necessary
  398. for _, a := range e.Attachments {
  399. ap, err := w.CreatePart(a.Header)
  400. if err != nil {
  401. return nil, err
  402. }
  403. // Write the base64Wrapped content to the part
  404. base64Wrap(ap, a.Content)
  405. }
  406. if isMixed || isAlternative {
  407. if err := w.Close(); err != nil {
  408. return nil, err
  409. }
  410. }
  411. return buff.Bytes(), nil
  412. }
  413. // Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
  414. // This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
  415. func (e *Email) Send(addr string, a smtp.Auth) error {
  416. // Merge the To, Cc, and Bcc fields
  417. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  418. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  419. for i := 0; i < len(to); i++ {
  420. addr, err := mail.ParseAddress(to[i])
  421. if err != nil {
  422. return err
  423. }
  424. to[i] = addr.Address
  425. }
  426. // Check to make sure there is at least one recipient and one "From" address
  427. if e.From == "" || len(to) == 0 {
  428. return errors.New("Must specify at least one From address and one To address")
  429. }
  430. sender, err := e.parseSender()
  431. if err != nil {
  432. return err
  433. }
  434. raw, err := e.Bytes()
  435. if err != nil {
  436. return err
  437. }
  438. return smtp.SendMail(addr, a, sender, to, raw)
  439. }
  440. // Select and parse an SMTP envelope sender address. Choose Email.Sender if set, or fallback to Email.From.
  441. func (e *Email) parseSender() (string, error) {
  442. if e.Sender != "" {
  443. sender, err := mail.ParseAddress(e.Sender)
  444. if err != nil {
  445. return "", err
  446. }
  447. return sender.Address, nil
  448. } else {
  449. from, err := mail.ParseAddress(e.From)
  450. if err != nil {
  451. return "", err
  452. }
  453. return from.Address, nil
  454. }
  455. }
  456. // SendWithTLS sends an email with an optional TLS config.
  457. // This is helpful if you need to connect to a host that is used an untrusted
  458. // certificate.
  459. func (e *Email) SendWithTLS(addr string, a smtp.Auth, t *tls.Config) error {
  460. // Merge the To, Cc, and Bcc fields
  461. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  462. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  463. for i := 0; i < len(to); i++ {
  464. addr, err := mail.ParseAddress(to[i])
  465. if err != nil {
  466. return err
  467. }
  468. to[i] = addr.Address
  469. }
  470. // Check to make sure there is at least one recipient and one "From" address
  471. if e.From == "" || len(to) == 0 {
  472. return errors.New("Must specify at least one From address and one To address")
  473. }
  474. sender, err := e.parseSender()
  475. if err != nil {
  476. return err
  477. }
  478. raw, err := e.Bytes()
  479. if err != nil {
  480. return err
  481. }
  482. conn, err := tls.Dial("tcp", addr, t)
  483. if err != nil {
  484. return err
  485. }
  486. c, err := smtp.NewClient(conn, t.ServerName)
  487. if err != nil {
  488. return err
  489. }
  490. defer c.Close()
  491. if err = c.Hello("localhost"); err != nil {
  492. return err
  493. }
  494. // Use TLS if available
  495. if ok, _ := c.Extension("STARTTLS"); ok {
  496. if err = c.StartTLS(t); err != nil {
  497. return err
  498. }
  499. }
  500. if a != nil {
  501. if ok, _ := c.Extension("AUTH"); ok {
  502. if err = c.Auth(a); err != nil {
  503. return err
  504. }
  505. }
  506. }
  507. if err = c.Mail(sender); err != nil {
  508. return err
  509. }
  510. for _, addr := range to {
  511. if err = c.Rcpt(addr); err != nil {
  512. return err
  513. }
  514. }
  515. w, err := c.Data()
  516. if err != nil {
  517. return err
  518. }
  519. _, err = w.Write(raw)
  520. if err != nil {
  521. return err
  522. }
  523. err = w.Close()
  524. if err != nil {
  525. return err
  526. }
  527. return c.Quit()
  528. }
  529. // Attachment is a struct representing an email attachment.
  530. // Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
  531. type Attachment struct {
  532. Filename string
  533. Header textproto.MIMEHeader
  534. Content []byte
  535. }
  536. // base64Wrap encodes the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
  537. // The output is then written to the specified io.Writer
  538. func base64Wrap(w io.Writer, b []byte) {
  539. // 57 raw bytes per 76-byte base64 line.
  540. const maxRaw = 57
  541. // Buffer for each line, including trailing CRLF.
  542. buffer := make([]byte, MaxLineLength+len("\r\n"))
  543. copy(buffer[MaxLineLength:], "\r\n")
  544. // Process raw chunks until there's no longer enough to fill a line.
  545. for len(b) >= maxRaw {
  546. base64.StdEncoding.Encode(buffer, b[:maxRaw])
  547. w.Write(buffer)
  548. b = b[maxRaw:]
  549. }
  550. // Handle the last chunk of bytes.
  551. if len(b) > 0 {
  552. out := buffer[:base64.StdEncoding.EncodedLen(len(b))]
  553. base64.StdEncoding.Encode(out, b)
  554. out = append(out, "\r\n"...)
  555. w.Write(out)
  556. }
  557. }
  558. // headerToBytes renders "header" to "buff". If there are multiple values for a
  559. // field, multiple "Field: value\r\n" lines will be emitted.
  560. func headerToBytes(buff io.Writer, header textproto.MIMEHeader) {
  561. for field, vals := range header {
  562. for _, subval := range vals {
  563. // bytes.Buffer.Write() never returns an error.
  564. io.WriteString(buff, field)
  565. io.WriteString(buff, ": ")
  566. // Write the encoded header if needed
  567. switch {
  568. case field == "Content-Type" || field == "Content-Disposition":
  569. buff.Write([]byte(subval))
  570. default:
  571. buff.Write([]byte(mime.QEncoding.Encode("UTF-8", subval)))
  572. }
  573. io.WriteString(buff, "\r\n")
  574. }
  575. }
  576. }
  577. var maxBigInt = big.NewInt(math.MaxInt64)
  578. // generateMessageID generates and returns a string suitable for an RFC 2822
  579. // compliant Message-ID, e.g.:
  580. // <1444789264909237300.3464.1819418242800517193@DESKTOP01>
  581. //
  582. // The following parameters are used to generate a Message-ID:
  583. // - The nanoseconds since Epoch
  584. // - The calling PID
  585. // - A cryptographically random int64
  586. // - The sending hostname
  587. func generateMessageID() (string, error) {
  588. t := time.Now().UnixNano()
  589. pid := os.Getpid()
  590. rint, err := rand.Int(rand.Reader, maxBigInt)
  591. if err != nil {
  592. return "", err
  593. }
  594. h, err := os.Hostname()
  595. // If we can't get the hostname, we'll use localhost
  596. if err != nil {
  597. h = "localhost.localdomain"
  598. }
  599. msgid := fmt.Sprintf("<%d.%d.%d@%s>", t, pid, rint, h)
  600. return msgid, nil
  601. }