email.go 9.9 KB

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