email.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  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. "encoding/base64"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "math"
  13. "math/big"
  14. "mime"
  15. "mime/multipart"
  16. "mime/quotedprintable"
  17. "net/mail"
  18. "net/smtp"
  19. "net/textproto"
  20. "os"
  21. "path/filepath"
  22. "strings"
  23. "time"
  24. )
  25. const (
  26. MaxLineLength = 76 // MaxLineLength is the maximum line length per RFC 2045
  27. defaultContentType = "text/plain; charset=us-ascii" // defaultContentType is the default Content-Type according to RFC 2045, section 5.2
  28. )
  29. // ErrMissingBoundary is returned when there is no boundary given for a multipart entity
  30. var ErrMissingBoundary = errors.New("No boundary found for multipart entity")
  31. // ErrMissingContentType is returned when there is no "Content-Type" header for a MIME entity
  32. var ErrMissingContentType = errors.New("No Content-Type found for MIME entity")
  33. // Email is the type used for email messages
  34. type Email struct {
  35. From string
  36. To []string
  37. Bcc []string
  38. Cc []string
  39. Subject string
  40. Text []byte // Plaintext message (optional)
  41. HTML []byte // Html message (optional)
  42. Headers textproto.MIMEHeader
  43. Attachments []*Attachment
  44. ReadReceipt []string
  45. }
  46. // part is a copyable representation of a multipart.Part
  47. type part struct {
  48. header textproto.MIMEHeader
  49. body []byte
  50. }
  51. // NewEmail creates an Email, and returns the pointer to it.
  52. func NewEmail() *Email {
  53. return &Email{Headers: textproto.MIMEHeader{}}
  54. }
  55. // NewEmailFromReader reads a stream of bytes from an io.Reader, r,
  56. // and returns an email struct containing the parsed data.
  57. // This function expects the data in RFC 5322 format.
  58. func NewEmailFromReader(r io.Reader) (*Email, error) {
  59. e := NewEmail()
  60. tp := textproto.NewReader(bufio.NewReader(r))
  61. // Parse the main headers
  62. hdrs, err := tp.ReadMIMEHeader()
  63. if err != nil {
  64. return e, err
  65. }
  66. // Set the subject, to, cc, bcc, and from
  67. for h, v := range hdrs {
  68. switch {
  69. case h == "Subject":
  70. e.Subject = v[0]
  71. delete(hdrs, h)
  72. case h == "To":
  73. e.To = v
  74. delete(hdrs, h)
  75. case h == "Cc":
  76. e.Cc = v
  77. delete(hdrs, h)
  78. case h == "Bcc":
  79. e.Bcc = v
  80. delete(hdrs, h)
  81. case h == "From":
  82. e.From = v[0]
  83. delete(hdrs, h)
  84. }
  85. }
  86. e.Headers = hdrs
  87. body := tp.R
  88. // Recursively parse the MIME parts
  89. ps, err := parseMIMEParts(e.Headers, body)
  90. if err != nil {
  91. return e, err
  92. }
  93. for _, p := range ps {
  94. if ct := p.header.Get("Content-Type"); ct == "" {
  95. return e, ErrMissingContentType
  96. }
  97. ct, _, err := mime.ParseMediaType(p.header.Get("Content-Type"))
  98. if err != nil {
  99. return e, err
  100. }
  101. switch {
  102. case ct == "text/plain":
  103. e.Text = p.body
  104. case ct == "text/html":
  105. e.HTML = p.body
  106. }
  107. }
  108. return e, nil
  109. }
  110. // parseMIMEParts will recursively walk a MIME entity and return a []mime.Part containing
  111. // each (flattened) mime.Part found.
  112. // It is important to note that there are no limits to the number of recursions, so be
  113. // careful when parsing unknown MIME structures!
  114. func parseMIMEParts(hs textproto.MIMEHeader, b io.Reader) ([]*part, error) {
  115. var ps []*part
  116. // If no content type is given, set it to the default
  117. if _, ok := hs["Content-Type"]; !ok {
  118. hs.Set("Content-Type", defaultContentType)
  119. }
  120. ct, params, err := mime.ParseMediaType(hs.Get("Content-Type"))
  121. if err != nil {
  122. return ps, err
  123. }
  124. // If it's a multipart email, recursively parse the parts
  125. if strings.HasPrefix(ct, "multipart/") {
  126. if _, ok := params["boundary"]; !ok {
  127. return ps, ErrMissingBoundary
  128. }
  129. mr := multipart.NewReader(b, params["boundary"])
  130. for {
  131. var buf bytes.Buffer
  132. p, err := mr.NextPart()
  133. if err == io.EOF {
  134. break
  135. }
  136. if err != nil {
  137. return ps, err
  138. }
  139. if _, ok := p.Header["Content-Type"]; !ok {
  140. p.Header.Set("Content-Type", defaultContentType)
  141. }
  142. subct, _, err := mime.ParseMediaType(p.Header.Get("Content-Type"))
  143. if strings.HasPrefix(subct, "multipart/") {
  144. sps, err := parseMIMEParts(p.Header, p)
  145. if err != nil {
  146. return ps, err
  147. }
  148. ps = append(ps, sps...)
  149. } else {
  150. // Otherwise, just append the part to the list
  151. // Copy the part data into the buffer
  152. if _, err := io.Copy(&buf, p); err != nil {
  153. return ps, err
  154. }
  155. ps = append(ps, &part{body: buf.Bytes(), header: p.Header})
  156. }
  157. }
  158. } else {
  159. // If it is not a multipart email, parse the body content as a single "part"
  160. var buf bytes.Buffer
  161. if _, err := io.Copy(&buf, b); err != nil {
  162. return ps, err
  163. }
  164. ps = append(ps, &part{body: buf.Bytes(), header: hs})
  165. }
  166. return ps, nil
  167. }
  168. // Attach is used to attach content from an io.Reader to the email.
  169. // Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type
  170. // The function will return the created Attachment for reference, as well as nil for the error, if successful.
  171. func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
  172. var buffer bytes.Buffer
  173. if _, err = io.Copy(&buffer, r); err != nil {
  174. return
  175. }
  176. at := &Attachment{
  177. Filename: filename,
  178. Header: textproto.MIMEHeader{},
  179. Content: buffer.Bytes(),
  180. }
  181. // Get the Content-Type to be used in the MIMEHeader
  182. if c != "" {
  183. at.Header.Set("Content-Type", c)
  184. } else {
  185. // If the Content-Type is blank, set the Content-Type to "application/octet-stream"
  186. at.Header.Set("Content-Type", "application/octet-stream")
  187. }
  188. at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
  189. at.Header.Set("Content-ID", fmt.Sprintf("<%s>", filename))
  190. at.Header.Set("Content-Transfer-Encoding", "base64")
  191. e.Attachments = append(e.Attachments, at)
  192. return at, nil
  193. }
  194. // AttachFile is used to attach content to the email.
  195. // It attempts to open the file referenced by filename and, if successful, creates an Attachment.
  196. // This Attachment is then appended to the slice of Email.Attachments.
  197. // The function will then return the Attachment for reference, as well as nil for the error, if successful.
  198. func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
  199. f, err := os.Open(filename)
  200. if err != nil {
  201. return
  202. }
  203. ct := mime.TypeByExtension(filepath.Ext(filename))
  204. basename := filepath.Base(filename)
  205. return e.Attach(f, basename, ct)
  206. }
  207. // msgHeaders merges the Email's various fields and custom headers together in a
  208. // standards compliant way to create a MIMEHeader to be used in the resulting
  209. // message. It does not alter e.Headers.
  210. //
  211. // "e"'s fields To, Cc, From, Subject will be used unless they are present in
  212. // e.Headers. Unless set in e.Headers, "Date" will filled with the current time.
  213. func (e *Email) msgHeaders() (textproto.MIMEHeader, error) {
  214. res := make(textproto.MIMEHeader, len(e.Headers)+4)
  215. if e.Headers != nil {
  216. for _, h := range []string{"To", "Cc", "From", "Subject", "Date", "Message-Id"} {
  217. if v, ok := e.Headers[h]; ok {
  218. res[h] = v
  219. }
  220. }
  221. }
  222. // Set headers if there are values.
  223. if _, ok := res["To"]; !ok && len(e.To) > 0 {
  224. res.Set("To", strings.Join(e.To, ", "))
  225. }
  226. if _, ok := res["Cc"]; !ok && len(e.Cc) > 0 {
  227. res.Set("Cc", strings.Join(e.Cc, ", "))
  228. }
  229. if _, ok := res["Subject"]; !ok && e.Subject != "" {
  230. res.Set("Subject", e.Subject)
  231. }
  232. if _, ok := res["Message-Id"]; !ok {
  233. id, err := generateMessageID()
  234. if err != nil {
  235. return nil, err
  236. }
  237. res.Set("Message-Id", id)
  238. }
  239. // Date and From are required headers.
  240. if _, ok := res["From"]; !ok {
  241. res.Set("From", e.From)
  242. }
  243. if _, ok := res["Date"]; !ok {
  244. res.Set("Date", time.Now().Format(time.RFC1123Z))
  245. }
  246. if _, ok := res["Mime-Version"]; !ok {
  247. res.Set("Mime-Version", "1.0")
  248. }
  249. for field, vals := range e.Headers {
  250. if _, ok := res[field]; !ok {
  251. res[field] = vals
  252. }
  253. }
  254. return res, nil
  255. }
  256. // Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
  257. func (e *Email) Bytes() ([]byte, error) {
  258. // TODO: better guess buffer size
  259. buff := bytes.NewBuffer(make([]byte, 0, 4096))
  260. headers, err := e.msgHeaders()
  261. if err != nil {
  262. return nil, err
  263. }
  264. w := multipart.NewWriter(buff)
  265. // TODO: determine the content type based on message/attachment mix.
  266. headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary())
  267. headerToBytes(buff, headers)
  268. io.WriteString(buff, "\r\n")
  269. // Start the multipart/mixed part
  270. fmt.Fprintf(buff, "--%s\r\n", w.Boundary())
  271. header := textproto.MIMEHeader{}
  272. // Check to see if there is a Text or HTML field
  273. if len(e.Text) > 0 || len(e.HTML) > 0 {
  274. subWriter := multipart.NewWriter(buff)
  275. // Create the multipart alternative part
  276. header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary()))
  277. // Write the header
  278. headerToBytes(buff, header)
  279. // Create the body sections
  280. if len(e.Text) > 0 {
  281. header.Set("Content-Type", fmt.Sprintf("text/plain; charset=UTF-8"))
  282. header.Set("Content-Transfer-Encoding", "quoted-printable")
  283. if _, err := subWriter.CreatePart(header); err != nil {
  284. return nil, err
  285. }
  286. qp := quotedprintable.NewWriter(buff)
  287. // Write the text
  288. if _, err := qp.Write(e.Text); err != nil {
  289. return nil, err
  290. }
  291. if err := qp.Close(); err != nil {
  292. return nil, err
  293. }
  294. }
  295. if len(e.HTML) > 0 {
  296. header.Set("Content-Type", fmt.Sprintf("text/html; charset=UTF-8"))
  297. header.Set("Content-Transfer-Encoding", "quoted-printable")
  298. if _, err := subWriter.CreatePart(header); err != nil {
  299. return nil, err
  300. }
  301. qp := quotedprintable.NewWriter(buff)
  302. // Write the HTML
  303. if _, err := qp.Write(e.HTML); err != nil {
  304. return nil, err
  305. }
  306. if err := qp.Close(); err != nil {
  307. return nil, err
  308. }
  309. }
  310. if err := subWriter.Close(); err != nil {
  311. return nil, err
  312. }
  313. }
  314. // Create attachment part, if necessary
  315. for _, a := range e.Attachments {
  316. ap, err := w.CreatePart(a.Header)
  317. if err != nil {
  318. return nil, err
  319. }
  320. // Write the base64Wrapped content to the part
  321. base64Wrap(ap, a.Content)
  322. }
  323. if err := w.Close(); err != nil {
  324. return nil, err
  325. }
  326. return buff.Bytes(), nil
  327. }
  328. // Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
  329. // This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
  330. func (e *Email) Send(addr string, a smtp.Auth) error {
  331. // Merge the To, Cc, and Bcc fields
  332. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  333. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  334. for i := 0; i < len(to); i++ {
  335. addr, err := mail.ParseAddress(to[i])
  336. if err != nil {
  337. return err
  338. }
  339. to[i] = addr.Address
  340. }
  341. // Check to make sure there is at least one recipient and one "From" address
  342. if e.From == "" || len(to) == 0 {
  343. return errors.New("Must specify at least one From address and one To address")
  344. }
  345. from, err := mail.ParseAddress(e.From)
  346. if err != nil {
  347. return err
  348. }
  349. raw, err := e.Bytes()
  350. if err != nil {
  351. return err
  352. }
  353. return smtp.SendMail(addr, a, from.Address, to, raw)
  354. }
  355. // Attachment is a struct representing an email attachment.
  356. // Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
  357. type Attachment struct {
  358. Filename string
  359. Header textproto.MIMEHeader
  360. Content []byte
  361. }
  362. // base64Wrap encodes the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
  363. // The output is then written to the specified io.Writer
  364. func base64Wrap(w io.Writer, b []byte) {
  365. // 57 raw bytes per 76-byte base64 line.
  366. const maxRaw = 57
  367. // Buffer for each line, including trailing CRLF.
  368. buffer := make([]byte, MaxLineLength+len("\r\n"))
  369. copy(buffer[MaxLineLength:], "\r\n")
  370. // Process raw chunks until there's no longer enough to fill a line.
  371. for len(b) >= maxRaw {
  372. base64.StdEncoding.Encode(buffer, b[:maxRaw])
  373. w.Write(buffer)
  374. b = b[maxRaw:]
  375. }
  376. // Handle the last chunk of bytes.
  377. if len(b) > 0 {
  378. out := buffer[:base64.StdEncoding.EncodedLen(len(b))]
  379. base64.StdEncoding.Encode(out, b)
  380. out = append(out, "\r\n"...)
  381. w.Write(out)
  382. }
  383. }
  384. // headerToBytes renders "header" to "buff". If there are multiple values for a
  385. // field, multiple "Field: value\r\n" lines will be emitted.
  386. func headerToBytes(buff *bytes.Buffer, header textproto.MIMEHeader) {
  387. for field, vals := range header {
  388. for _, subval := range vals {
  389. // bytes.Buffer.Write() never returns an error.
  390. io.WriteString(buff, field)
  391. io.WriteString(buff, ": ")
  392. // Write the encoded header if needed
  393. switch {
  394. case field == "Content-Type" || field == "Content-Disposition":
  395. buff.Write([]byte(subval))
  396. default:
  397. buff.Write([]byte(mime.QEncoding.Encode("UTF-8", subval)))
  398. }
  399. io.WriteString(buff, "\r\n")
  400. }
  401. }
  402. }
  403. var maxBigInt = big.NewInt(math.MaxInt64)
  404. // generateMessageID generates and returns a string suitable for an RFC 2822
  405. // compliant Message-ID, e.g.:
  406. // <1444789264909237300.3464.1819418242800517193@DESKTOP01>
  407. //
  408. // The following parameters are used to generate a Message-ID:
  409. // - The nanoseconds since Epoch
  410. // - The calling PID
  411. // - A cryptographically random int64
  412. // - The sending hostname
  413. func generateMessageID() (string, error) {
  414. t := time.Now().UnixNano()
  415. pid := os.Getpid()
  416. rint, err := rand.Int(rand.Reader, maxBigInt)
  417. if err != nil {
  418. return "", err
  419. }
  420. h, err := os.Hostname()
  421. // If we can't get the hostname, we'll use localhost
  422. if err != nil {
  423. h = "localhost.localdomain"
  424. }
  425. msgid := fmt.Sprintf("<%d.%d.%d@%s>", t, pid, rint, h)
  426. return msgid, nil
  427. }