email.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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"
  17. "path/filepath"
  18. "strings"
  19. )
  20. const (
  21. // MaxLineLength is the maximum line length per RFC 2045
  22. MaxLineLength = 76
  23. )
  24. // Email is the type used for email messages
  25. type Email struct {
  26. From string
  27. To []string
  28. Bcc []string
  29. Cc []string
  30. Subject string
  31. Text []byte // Plaintext message (optional)
  32. HTML []byte // Html message (optional)
  33. Headers textproto.MIMEHeader
  34. Attachments []*Attachment
  35. ReadReceipt []string
  36. }
  37. // NewEmail creates an Email, and returns the pointer to it.
  38. func NewEmail() *Email {
  39. return &Email{Headers: textproto.MIMEHeader{}}
  40. }
  41. // Attach is used to attach content from an io.Reader to the email.
  42. // Required parameters include an io.Reader, the desired filename for the attachment, and the Content-Type
  43. // The function will return the created Attachment for reference, as well as nil for the error, if successful.
  44. func (e *Email) Attach(r io.Reader, filename string, c string) (a *Attachment, err error) {
  45. var buffer bytes.Buffer
  46. if _, err = io.Copy(&buffer, r); err != nil {
  47. return
  48. }
  49. at := &Attachment{
  50. Filename: filename,
  51. Header: textproto.MIMEHeader{},
  52. Content: buffer.Bytes(),
  53. }
  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. e.Attachments = append(e.Attachments, at)
  64. return at, nil
  65. }
  66. // AttachFile is used to attach content to the email.
  67. // It attempts to open the file referenced by filename and, if successful, creates an Attachment.
  68. // This Attachment is then appended to the slice of Email.Attachments.
  69. // The function will then return the Attachment for reference, as well as nil for the error, if successful.
  70. func (e *Email) AttachFile(filename string) (a *Attachment, err error) {
  71. f, err := os.Open(filename)
  72. if err != nil {
  73. return
  74. }
  75. ct := mime.TypeByExtension(filepath.Ext(filename))
  76. basename := path.Base(filename)
  77. return e.Attach(f, basename, ct)
  78. }
  79. // msgHeaders merges the Email's various fields and custom headers together in a
  80. // standards complient way to create a MIMEHeader to be used in the resulting
  81. // message. It does not alter e.Headers.
  82. //
  83. // "e"'s fields To, Cc, From, and Subject will be used unless they are present
  84. // in e.Headers.
  85. func (e *Email) msgHeaders() textproto.MIMEHeader {
  86. res := make(textproto.MIMEHeader, len(e.Headers)+4)
  87. if e.Headers != nil {
  88. for _, h := range []string{"To", "Cc", "From", "Subject"} {
  89. if v, ok := e.Headers[h]; ok {
  90. res[h] = v
  91. }
  92. }
  93. }
  94. if _, ok := res["To"]; !ok && len(e.To) > 0 {
  95. res.Set("To", strings.Join(e.To, ", "))
  96. }
  97. if _, ok := res["Cc"]; !ok && len(e.Cc) > 0 {
  98. res.Set("Cc", strings.Join(e.Cc, ", "))
  99. }
  100. if _, ok := res["From"]; !ok {
  101. res.Set("From", e.From)
  102. }
  103. if _, ok := res["Subject"]; !ok && e.Subject != "" {
  104. res.Set("Subject", e.Subject)
  105. }
  106. for field, vals := range e.Headers {
  107. if _, ok := res[field]; !ok {
  108. res[field] = vals
  109. }
  110. }
  111. return res
  112. }
  113. // Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
  114. func (e *Email) Bytes() ([]byte, error) {
  115. // TODO: better guess buffer size
  116. buff := bytes.NewBuffer(make([]byte, 0, 4096))
  117. headers := e.msgHeaders()
  118. w := multipart.NewWriter(buff)
  119. // TODO: determine the content type based on message/attachement mix.
  120. headers.Set("Content-Type", "multipart/mixed;\r\n boundary="+w.Boundary())
  121. headerToBytes(buff, headers)
  122. io.WriteString(buff, "\r\n")
  123. // Start the multipart/mixed part
  124. fmt.Fprintf(buff, "--%s\r\n", w.Boundary())
  125. header := textproto.MIMEHeader{}
  126. // Check to see if there is a Text or HTML field
  127. if len(e.Text) > 0 || len(e.HTML) > 0 {
  128. subWriter := multipart.NewWriter(buff)
  129. // Create the multipart alternative part
  130. header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary()))
  131. // Write the header
  132. headerToBytes(buff, header)
  133. // Create the body sections
  134. if len(e.Text) > 0 {
  135. header.Set("Content-Type", fmt.Sprintf("text/plain; charset=UTF-8"))
  136. header.Set("Content-Transfer-Encoding", "quoted-printable")
  137. if _, err := subWriter.CreatePart(header); err != nil {
  138. return nil, err
  139. }
  140. // Write the text
  141. if err := quotePrintEncode(buff, e.Text); err != nil {
  142. return nil, err
  143. }
  144. }
  145. if len(e.HTML) > 0 {
  146. header.Set("Content-Type", fmt.Sprintf("text/html; charset=UTF-8"))
  147. header.Set("Content-Transfer-Encoding", "quoted-printable")
  148. if _, err := subWriter.CreatePart(header); err != nil {
  149. return nil, err
  150. }
  151. // Write the text
  152. if err := quotePrintEncode(buff, e.HTML); err != nil {
  153. return nil, err
  154. }
  155. }
  156. if err := subWriter.Close(); err != nil {
  157. return nil, err
  158. }
  159. }
  160. // Create attachment part, if necessary
  161. for _, a := range e.Attachments {
  162. ap, err := w.CreatePart(a.Header)
  163. if err != nil {
  164. return nil, err
  165. }
  166. // Write the base64Wrapped content to the part
  167. base64Wrap(ap, a.Content)
  168. }
  169. if err := w.Close(); err != nil {
  170. return nil, err
  171. }
  172. return buff.Bytes(), nil
  173. }
  174. // Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
  175. // This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
  176. func (e *Email) Send(addr string, a smtp.Auth) error {
  177. // Merge the To, Cc, and Bcc fields
  178. to := make([]string, 0, len(e.To)+len(e.Cc)+len(e.Bcc))
  179. to = append(append(append(to, e.To...), e.Cc...), e.Bcc...)
  180. // Check to make sure there is at least one recipient and one "From" address
  181. if e.From == "" || len(to) == 0 {
  182. return errors.New("Must specify at least one From address and one To address")
  183. }
  184. from, err := mail.ParseAddress(e.From)
  185. if err != nil {
  186. return err
  187. }
  188. raw, err := e.Bytes()
  189. if err != nil {
  190. return err
  191. }
  192. return smtp.SendMail(addr, a, from.Address, to, raw)
  193. }
  194. // Attachment is a struct representing an email attachment.
  195. // Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
  196. type Attachment struct {
  197. Filename string
  198. Header textproto.MIMEHeader
  199. Content []byte
  200. }
  201. // quotePrintEncode writes the quoted-printable text to the IO Writer (according to RFC 2045)
  202. func quotePrintEncode(w io.Writer, body []byte) error {
  203. var buf [3]byte
  204. mc := 0
  205. for _, c := range body {
  206. // We're assuming Unix style text formats as input (LF line break), and
  207. // quoted-printble uses CRLF line breaks. (Literal CRs will become
  208. // "=0D", but probably shouldn't be there to begin with!)
  209. if c == '\n' {
  210. io.WriteString(w, "\r\n")
  211. mc = 0
  212. continue
  213. }
  214. var nextOut []byte
  215. if isPrintable[c] {
  216. buf[0] = c
  217. nextOut = buf[:1]
  218. } else {
  219. nextOut = buf[:]
  220. qpEscape(nextOut, c)
  221. }
  222. // Add a soft line break if the next (encoded) byte would push this line
  223. // to or past the limit.
  224. if mc+len(nextOut) >= MaxLineLength {
  225. if _, err := io.WriteString(w, "=\r\n"); err != nil {
  226. return err
  227. }
  228. mc = 0
  229. }
  230. if _, err := w.Write(nextOut); err != nil {
  231. return err
  232. }
  233. mc += len(nextOut)
  234. }
  235. // No trailing end-of-line?? Soft line break, then. TODO: is this sane?
  236. if mc > 0 {
  237. io.WriteString(w, "=\r\n")
  238. }
  239. return nil
  240. }
  241. // isPrintable holds true if the byte given is "printable" according to RFC 2045, false otherwise
  242. var isPrintable [256]bool
  243. func init() {
  244. for c := '!'; c <= '<'; c++ {
  245. isPrintable[c] = true
  246. }
  247. for c := '>'; c <= '~'; c++ {
  248. isPrintable[c] = true
  249. }
  250. isPrintable[' '] = true
  251. isPrintable['\n'] = true
  252. isPrintable['\t'] = true
  253. }
  254. // qpEscape is a helper function for quotePrintEncode which escapes a
  255. // non-printable byte. Expects len(dest) == 3.
  256. func qpEscape(dest []byte, c byte) {
  257. const nums = "0123456789ABCDEF"
  258. dest[0] = '='
  259. dest[1] = nums[(c&0xf0)>>4]
  260. dest[2] = nums[(c & 0xf)]
  261. }
  262. // base64Wrap encodeds the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
  263. // The output is then written to the specified io.Writer
  264. func base64Wrap(w io.Writer, b []byte) {
  265. // 57 raw bytes per 76-byte base64 line.
  266. const maxRaw = 57
  267. // Buffer for each line, including trailing CRLF.
  268. var buffer [MaxLineLength + len("\r\n")]byte
  269. copy(buffer[MaxLineLength:], "\r\n")
  270. // Process raw chunks until there's no longer enough to fill a line.
  271. for len(b) >= maxRaw {
  272. base64.StdEncoding.Encode(buffer[:], b[:maxRaw])
  273. w.Write(buffer[:])
  274. b = b[maxRaw:]
  275. }
  276. // Handle the last chunk of bytes.
  277. if len(b) > 0 {
  278. out := buffer[:base64.StdEncoding.EncodedLen(len(b))]
  279. base64.StdEncoding.Encode(out, b)
  280. out = append(out, "\r\n"...)
  281. w.Write(out)
  282. }
  283. }
  284. // headerToBytes renders "header" to "buff". If there are multiple values for a
  285. // field, multiple "Field: value\r\n" lines will be emitted.
  286. func headerToBytes(buff *bytes.Buffer, header textproto.MIMEHeader) {
  287. for field, vals := range header {
  288. for _, subval := range vals {
  289. // bytes.Buffer.Write() never returns an error.
  290. io.WriteString(buff, field)
  291. io.WriteString(buff, ": ")
  292. io.WriteString(buff, subval)
  293. io.WriteString(buff, "\r\n")
  294. }
  295. }
  296. }