email.go 9.7 KB

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