email.go 10.0 KB

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