email.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. "io/ioutil"
  11. "mime"
  12. "mime/multipart"
  13. "net/mail"
  14. "net/smtp"
  15. "net/textproto"
  16. "os"
  17. "path/filepath"
  18. "strings"
  19. )
  20. const (
  21. MAX_LINE_LENGTH = 76 //The maximum line length per RFC 2045
  22. )
  23. //Email is the type used for email messages
  24. type Email struct {
  25. From string
  26. To []string
  27. Bcc []string
  28. Cc []string
  29. Subject string
  30. Text string //Plaintext message (optional)
  31. Html string //Html message (optional)
  32. Headers textproto.MIMEHeader
  33. Attachments map[string]*Attachment
  34. ReadReceipt []string
  35. }
  36. //NewEmail creates an Email, and returns the pointer to it.
  37. func NewEmail() *Email {
  38. return &Email{Attachments: make(map[string]*Attachment), Headers: textproto.MIMEHeader{}}
  39. }
  40. //Attach is used to attach a file to the email.
  41. //It attempts to open the file referenced by filename and, if successful, creates an Attachment.
  42. //This Attachment is then appended to the slice of Email.Attachments.
  43. //The function will then return the Attachment for reference, as well as nil for the error, if successful.
  44. func (e *Email) Attach(filename string) (a *Attachment, err error) {
  45. //Check if the file exists, return any error
  46. if _, err := os.Stat(filename); os.IsNotExist(err) {
  47. return nil, err
  48. }
  49. //Read the file, and set the appropriate headers
  50. buffer, _ := ioutil.ReadFile(filename)
  51. e.Attachments[filename] = &Attachment{
  52. Filename: filename,
  53. Header: textproto.MIMEHeader{},
  54. Content: buffer}
  55. at := e.Attachments[filename]
  56. //Get the Content-Type to be used in the MIMEHeader
  57. ct := mime.TypeByExtension(filepath.Ext(filename))
  58. if ct != "" {
  59. at.Header.Set("Content-Type", ct)
  60. } else {
  61. //If the Content-Type is blank, set the Content-Type to "application/octet-stream"
  62. at.Header.Set("Content-Type", "application/octet-stream")
  63. }
  64. at.Header.Set("Content-Disposition", fmt.Sprintf("attachment;\r\n filename=\"%s\"", filename))
  65. at.Header.Set("Content-Transfer-Encoding", "base64")
  66. return e.Attachments[filename], nil
  67. }
  68. //Bytes converts the Email object to a []byte representation, including all needed MIMEHeaders, boundaries, etc.
  69. func (e *Email) Bytes() ([]byte, error) {
  70. buff := &bytes.Buffer{}
  71. w := multipart.NewWriter(buff)
  72. //Set the appropriate headers (overwriting any conflicts)
  73. //Leave out Bcc (only included in envelope headers)
  74. e.Headers.Set("To", strings.Join(e.To, ","))
  75. if e.Cc != nil {
  76. e.Headers.Set("Cc", strings.Join(e.Cc, ","))
  77. }
  78. e.Headers.Set("From", e.From)
  79. e.Headers.Set("Subject", e.Subject)
  80. if len(e.ReadReceipt) != 0 {
  81. e.Headers.Set("Disposition-Notification-To", strings.Join(e.ReadReceipt, ","))
  82. }
  83. e.Headers.Set("MIME-Version", "1.0")
  84. e.Headers.Set("Content-Type", fmt.Sprintf("multipart/mixed;\r\n boundary=%s\r\n", w.Boundary()))
  85. //Write the envelope headers (including any custom headers)
  86. if err := headerToBytes(buff, e.Headers); err != nil {
  87. }
  88. //Start the multipart/mixed part
  89. fmt.Fprintf(buff, "--%s\r\n", w.Boundary())
  90. header := textproto.MIMEHeader{}
  91. //Check to see if there is a Text or HTML field
  92. if e.Text != "" || e.Html != "" {
  93. subWriter := multipart.NewWriter(buff)
  94. //Create the multipart alternative part
  95. header.Set("Content-Type", fmt.Sprintf("multipart/alternative;\r\n boundary=%s\r\n", subWriter.Boundary()))
  96. //Write the header
  97. if err := headerToBytes(buff, header); err != nil {
  98. }
  99. //Create the body sections
  100. if e.Text != "" {
  101. header.Set("Content-Type", fmt.Sprintf("text/plain; charset=UTF-8"))
  102. header.Set("Content-Transfer-Encoding", "quoted-printable")
  103. subWriter.CreatePart(header)
  104. // Write the text
  105. if err := quotePrintEncode(buff, e.Html); err != nil {
  106. return nil, err
  107. }
  108. }
  109. if e.Html != "" {
  110. header.Set("Content-Type", fmt.Sprintf("text/html; charset=UTF-8"))
  111. header.Set("Content-Transfer-Encoding", "quoted-printable")
  112. subWriter.CreatePart(header)
  113. // Write the text
  114. if err := quotePrintEncode(buff, e.Html); err != nil {
  115. return nil, err
  116. }
  117. }
  118. subWriter.Close()
  119. }
  120. //Create attachment part, if necessary
  121. if e.Attachments != nil {
  122. for _, a := range e.Attachments {
  123. ap, err := w.CreatePart(a.Header)
  124. if err != nil {
  125. return nil, err
  126. }
  127. //Write the base64Wrapped content to the part
  128. base64Wrap(ap, a.Content)
  129. }
  130. }
  131. w.Close()
  132. return buff.Bytes(), nil
  133. }
  134. //Send an email using the given host and SMTP auth (optional), returns any error thrown by smtp.SendMail
  135. //This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
  136. func (e *Email) Send(addr string, a smtp.Auth) error {
  137. //Check to make sure there is at least one recipient and one "From" address
  138. if e.From == "" || (len(e.To) == 0 && len(e.Cc) == 0 && len(e.Bcc) == 0) {
  139. return errors.New("Must specify at least one From address and one To address")
  140. }
  141. // Merge the To, Cc, and Bcc fields
  142. to := append(append(e.To, e.Cc...), e.Bcc...)
  143. from, err := mail.ParseAddress(e.From)
  144. if err != nil {
  145. return err
  146. }
  147. raw, err := e.Bytes()
  148. if err != nil {
  149. return err
  150. }
  151. return smtp.SendMail(addr, a, from.Address, to, raw)
  152. }
  153. //Attachment is a struct representing an email attachment.
  154. //Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
  155. type Attachment struct {
  156. Filename string
  157. Header textproto.MIMEHeader
  158. Content []byte
  159. }
  160. //quotePrintEncode writes the quoted-printable text to the IO Writer (according to RFC 2045)
  161. func quotePrintEncode(w io.Writer, s string) error {
  162. mc := 0
  163. for _, c := range s {
  164. // Handle the soft break for the EOL, if needed
  165. if mc == 75 || (!isPrintable(c) && mc+len(fmt.Sprintf("%s%X", "=", c)) > 75) {
  166. if _, err := fmt.Fprintf(w, "%s", "=\r\n"); err != nil {
  167. return err
  168. }
  169. mc = 0
  170. }
  171. //append the appropriate character
  172. if isPrintable(c) {
  173. //Printable character
  174. if _, err := fmt.Fprintf(w, "%s", string(c)); err != nil {
  175. return err
  176. }
  177. // Reset the counter if we wrote a newline
  178. if c == '\n' {
  179. mc = 0
  180. }
  181. mc++
  182. continue
  183. } else {
  184. //non-printable.. encode it (TODO)
  185. es := fmt.Sprintf("%s%X", "=", c)
  186. if _, err := fmt.Fprintf(w, "%s", es); err != nil {
  187. return err
  188. }
  189. //todo - increment correctly
  190. mc += len(es)
  191. }
  192. }
  193. return nil
  194. }
  195. //isPrintable returns true if the rune given is "printable" according to RFC 2045, false otherwise
  196. func isPrintable(c rune) bool {
  197. return (c >= '!' && c <= '<') || (c >= '>' && c <= '~') || (c == ' ' || c == '\n' || c == '\t')
  198. }
  199. //base64Wrap encodeds the attachment content, and wraps it according to RFC 2045 standards (every 76 chars)
  200. //The output is then written to the specified io.Writer
  201. func base64Wrap(w io.Writer, b []byte) {
  202. encoded := base64.StdEncoding.EncodeToString(b)
  203. for i := 0; i < len(encoded); i += 76 {
  204. //Do we need to print 76 characters, or the rest of the string?
  205. if len(encoded)-i < 76 {
  206. fmt.Fprintf(w, "%s\r\n", encoded[i:])
  207. } else {
  208. fmt.Fprintf(w, "%s\r\n", encoded[i:i+76])
  209. }
  210. }
  211. }
  212. //headerToBytes enumerates the key and values in the header, and writes the results to the IO Writer
  213. func headerToBytes(w io.Writer, t textproto.MIMEHeader) error {
  214. for k, v := range t {
  215. //Write the header key
  216. _, err := fmt.Fprintf(w, "%s:", k)
  217. if err != nil {
  218. return err
  219. }
  220. //Write each value in the header
  221. for _, c := range v {
  222. _, err := fmt.Fprintf(w, " %s\r\n", c)
  223. if err != nil {
  224. return err
  225. }
  226. }
  227. }
  228. return nil
  229. }