email.go 13 KB

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