email.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  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. "bytes"
  6. "encoding/base64"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime"
  11. "mime/multipart"
  12. "net/mail"
  13. "net/smtp"
  14. "net/textproto"
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. )
  19. const (
  20. // MaxLineLength is the maximum line length per RFC 2045
  21. MaxLineLength = 76
  22. )
  23. // Email is the type used for email messages
  24. type Email struct {
  25. From string
  26. To []string
  27. Bcc []string
  28. Cc []string
  29. Subject string
  30. Text string // Plaintext message (optional)
  31. HTML string // Html message (optional)
  32. Headers textproto.MIMEHeader
  33. Attachments map[string]*Attachment
  34. ReadReceipt []string
  35. }
  36. // NewEmail creates an Email, and returns the pointer to it.
  37. func NewEmail() *Email {
  38. return &Email{Attachments: make(map[string]*Attachment), Headers: textproto.MIMEHeader{}}
  39. }
  40. // Attach is used to attach content from an io.Reader to the email.
  41. // Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type
  42. // The function will return the created Attachment for reference, as well as nil for the error, if successful.
  43. func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
  44. buffer := new(bytes.Buffer)
  45. _, err = buffer.ReadFrom(r)
  46. if err != nil {
  47. return nil, err
  48. }
  49. e.Attachments[filename] = &Attachment{
  50. Filename: filename,
  51. Header: textproto.MIMEHeader{},
  52. Content: buffer.Bytes()}
  53. at := e.Attachments[filename]
  54. // Get the Content-Type to be used in the MIMEHeader
  55. if c != "" {
  56. at.Header.Set("Content-Type", c)
  57. } else {
  58. // If the Content-Type is blank, set the Content-Type to "application/octet-stream"
  59. at.Header.Set("Content-Type", "application/octet-stream")
  60. }
  61. at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
  62. at.Header.Set("Content-Transfer-Encoding", "base64")
  63. return at, nil
  64. }
  65. // AttachFile is used to attach content to the email.
  66. // It attempts to open the file referenced by filename and, if successful, creates an Attachment.
  67. // This Attachment is then appended to the slice of Email.Attachments.
  68. // The function will then return the Attachment for reference, as well as nil for the error, if successful.
  69. func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
  70. // Check if the file exists, return any error
  71. if _, err := os.Stat(filename); os.IsNotExist(err) {
  72. return nil, err
  73. }
  74. f, err := os.Open(filename)
  75. if err != nil {
  76. return nil, err
  77. }
  78. // Get the Content-Type to be used in the MIMEHeader
  79. ct := mime.TypeByExtension(filepath.Ext(filename))
  80. return e.Attach(f, filename, ct)
  81. }
  82. // Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
  83. func (e *Email) Bytes() ([]byte, error) {
  84. buff := &bytes.Buffer{}
  85. w := multipart.NewWriter(buff)
  86. // Set the appropriate headers (overwriting any conflicts)
  87. // Leave out Bcc (only included in envelope headers)
  88. e.Headers.Set("To", strings.Join(e.To, ","))
  89. if e.Cc != nil {
  90. e.Headers.Set("Cc", strings.Join(e.Cc, ","))
  91. }
  92. e.Headers.Set("From", e.From)
  93. e.Headers.Set("Subject", e.Subject)
  94. if len(e.ReadReceipt) != 0 {
  95. e.Headers.Set("Disposition-Notification-To", strings.Join(e.ReadReceipt, ","))
  96. }
  97. e.Headers.Set("MIME-Version", "1.0")
  98. e.Headers.Set("Content-Type", fmt.Sprintf("multipart/mixed;\r\n boundary=%s\r\n", w.Boundary()))
  99. // Write the envelope headers (including any custom headers)
  100. if err := headerToBytes(buff, e.Headers); err != nil {
  101. }
  102. // Start the multipart/mixed part
  103. fmt.Fprintf(buff, "--%s\r\n", w.Boundary())
  104. header := textproto.MIMEHeader{}
  105. // Check to see if there is a Text or HTML field
  106. if e.Text != "" || e.HTML != "" {
  107. subWriter := multipart.NewWriter(buff)
  108. // Create the multipart alternative part
  109. header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary()))
  110. // Write the header
  111. if err := headerToBytes(buff, header); err != nil {
  112. }
  113. // Create the body sections
  114. if e.Text != "" {
  115. header.Set("Content-Type", fmt.Sprintf("text/plain; charset=UTF-8"))
  116. header.Set("Content-Transfer-Encoding", "quoted-printable")
  117. if _, err := subWriter.CreatePart(header); err != nil {
  118. return nil, err
  119. }
  120. // Write the text
  121. if err := quotePrintEncode(buff, e.Text); err != nil {
  122. return nil, err
  123. }
  124. }
  125. if e.HTML != "" {
  126. header.Set("Content-Type", fmt.Sprintf("text/html; charset=UTF-8"))
  127. header.Set("Content-Transfer-Encoding", "quoted-printable")
  128. if _, err := subWriter.CreatePart(header); err != nil {
  129. return nil, err
  130. }
  131. // Write the text
  132. if err := quotePrintEncode(buff, e.HTML); err != nil {
  133. return nil, err
  134. }
  135. }
  136. if err := subWriter.Close(); err != nil {
  137. return nil, err
  138. }
  139. }
  140. // Create attachment part, if necessary
  141. if e.Attachments != nil {
  142. for _, a := range e.Attachments {
  143. ap, err := w.CreatePart(a.Header)
  144. if err != nil {
  145. return nil, err
  146. }
  147. // Write the base64Wrapped content to the part
  148. base64Wrap(ap, a.Content)
  149. }
  150. }
  151. if err := w.Close(); err != nil {
  152. return nil, err
  153. }
  154. return buff.Bytes(), nil
  155. }
  156. // Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
  157. // This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
  158. func (e *Email) Send(addr string, a smtp.Auth) error {
  159. // Check to make sure there is at least one recipient and one "From" address
  160. if e.From == "" || (len(e.To) == 0 && len(e.Cc) == 0 && len(e.Bcc) == 0) {
  161. return errors.New("Must specify at least one From address and one To address")
  162. }
  163. // Merge the To, Cc, and Bcc fields
  164. to := append(append(e.To, e.Cc...), e.Bcc...)
  165. from, err := mail.ParseAddress(e.From)
  166. if err != nil {
  167. return err
  168. }
  169. raw, err := e.Bytes()
  170. if err != nil {
  171. return err
  172. }
  173. return smtp.SendMail(addr, a, from.Address, to, raw)
  174. }
  175. // Attachment is a struct representing an email attachment.
  176. // Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
  177. type Attachment struct {
  178. Filename string
  179. Header textproto.MIMEHeader
  180. Content []byte
  181. }
  182. // quotePrintEncode writes the quoted-printable text to the IO Writer (according to RFC 2045)
  183. func quotePrintEncode(w io.Writer, s string) error {
  184. mc := 0
  185. for _, c := range s {
  186. // Handle the soft break for the EOL, if needed
  187. if mc == MaxLineLength-1 || (!isPrintable(c) && mc+len(fmt.Sprintf("%s%X", "=", c)) > MaxLineLength-1) {
  188. if _, err := fmt.Fprintf(w, "%s", "=\r\n"); err != nil {
  189. return err
  190. }
  191. mc = 0
  192. }
  193. // append the appropriate character
  194. if isPrintable(c) {
  195. // Printable character
  196. if _, err := fmt.Fprintf(w, "%s", string(c)); err != nil {
  197. return err
  198. }
  199. // Reset the counter if we wrote a newline
  200. if c == '\n' {
  201. mc = 0
  202. }
  203. mc++
  204. continue
  205. } else {
  206. // non-printable.. encode it (TODO)
  207. es := fmt.Sprintf("%s%X", "=", c)
  208. if _, err := fmt.Fprintf(w, "%s", es); err != nil {
  209. return err
  210. }
  211. // todo - increment correctly
  212. mc += len(es)
  213. }
  214. }
  215. return nil
  216. }
  217. // isPrintable returns true if the rune given is "printable" according to RFC 2045, false otherwise
  218. func isPrintable(c rune) bool {
  219. return (c >= '!' && c <= '<') || (c >= '>' && c <= '~') || (c == ' ' || c == '\n' || c == '\t')
  220. }
  221. // base64Wrap encodeds the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
  222. // The output is then written to the specified io.Writer
  223. func base64Wrap(w io.Writer, b []byte) {
  224. encoded := base64.StdEncoding.EncodeToString(b)
  225. for i := 0; i < len(encoded); i += MaxLineLength {
  226. // Do we need to print 76 characters, or the rest of the string?
  227. if len(encoded)-i < MaxLineLength {
  228. fmt.Fprintf(w, "%s\r\n", encoded[i:])
  229. } else {
  230. fmt.Fprintf(w, "%s\r\n", encoded[i:i+MaxLineLength])
  231. }
  232. }
  233. }
  234. // headerToBytes enumerates the key and values in the header, and writes the results to the IO Writer
  235. func headerToBytes(w io.Writer, t textproto.MIMEHeader) error {
  236. for k, v := range t {
  237. // Write the header key
  238. _, err := fmt.Fprintf(w, "%s:", k)
  239. if err != nil {
  240. return err
  241. }
  242. // Write each value in the header
  243. for _, c := range v {
  244. _, err := fmt.Fprintf(w, " %s\r\n", c)
  245. if err != nil {
  246. return err
  247. }
  248. }
  249. }
  250. return nil
  251. }