email.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //Email is designed to be a package providing 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. "io/ioutil"
  6. "log"
  7. "net/mail"
  8. "net/smtp"
  9. "net/textproto"
  10. "os"
  11. )
  12. //Email is the type used for email messages
  13. type Email struct {
  14. From string
  15. To []string
  16. Bcc []string
  17. Cc []string
  18. Subject string
  19. Text string //Plaintext message (optional)
  20. Html string //Html message (optional)
  21. Headers []mail.Header
  22. Attachments map[string]*Attachment
  23. }
  24. //NewEmail creates an Email, and returns the pointer to it.
  25. func NewEmail() *Email {
  26. return &Email{Attachments: make(map[string]*Attachment)}
  27. }
  28. //Attach is used to attach a file to the email.
  29. //It attempts to open the file reference by filename and, if successful, creates an Attachment.
  30. //This Attachment is then appended to the slice of Email.Attachments.
  31. //The function will then return the Attachment for reference, as well as nil for the error if successful.
  32. func (e *Email) Attach(filename string) (a *Attachment, err error) {
  33. //Check if the file exists, return any error
  34. if _, err := os.Stat(filename); os.IsNotExist(err) {
  35. log.Fatal("%s does not exist", filename)
  36. return nil, err
  37. }
  38. buffer, _ := ioutil.ReadFile(filename)
  39. e.Attachments[filename] = &Attachment{
  40. Filename: filename,
  41. Header: textproto.MIMEHeader{},
  42. Content: buffer}
  43. return e.Attachments[filename], nil
  44. }
  45. //Bytes converts the Email object to a []byte representation of it, including all needed MIMEHeaders, boundaries, etc.
  46. func (e *Email) Bytes() []byte {
  47. return []byte{}
  48. }
  49. //Send an email using the given host and SMTP auth (optional)
  50. //This function merges the To, Cc, and Bcc fields and calls the smtp.SendMail function using the Email.Bytes() output as the message
  51. func (e *Email) Send(addr string, a smtp.Auth) error {
  52. // Merge the To, Cc, and Bcc fields
  53. to := append(append(e.To, e.Cc...), e.Bcc...)
  54. return smtp.SendMail(addr, a, e.From, to, e.Bytes())
  55. }
  56. //Attachment is a struct representing an email attachment.
  57. //Based on the mime/multipart.FileHeader struct, Attachment contains the name, MIMEHeader, and content of the attachment in question
  58. type Attachment struct {
  59. Filename string
  60. Header textproto.MIMEHeader
  61. Content []byte
  62. }