email.go 15 KB

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