email.go 9.8 KB

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