emailer.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Package emailer for send email messages text or html formats
  2. package emailer
  3. import (
  4. "encoding/base64"
  5. "fmt"
  6. "net/smtp"
  7. "strings"
  8. "time"
  9. )
  10. // encode header of email message
  11. func mailEncodeHeader(str string) string {
  12. return "=?UTF-8?B?" + base64.StdEncoding.EncodeToString([]byte(str)) + "?="
  13. }
  14. // encode header email field
  15. func mailEncodeEmail(email string) string {
  16. return mailEncodeHeader(email) + " <" + email + ">"
  17. }
  18. // join encoded emails (receivers) for header field "To"
  19. func mailJoinReceivers(receivers []string) string {
  20. arr := make([]string, len(receivers))
  21. for i, v := range receivers {
  22. arr[i] = mailEncodeEmail(v)
  23. }
  24. return strings.Join(arr, ",")
  25. }
  26. // SendEmail send email message with text/plain mime type
  27. func SendEmail(subject, message string, receivers []string, userName, userPassword, host, identity string, port int16) (err error) {
  28. auth := smtp.PlainAuth(identity, userName, userPassword, host)
  29. msg := []byte("To: " + mailJoinReceivers(receivers) + "\r\n" +
  30. "Date:" + time.Now().Format("Mon 2 Jan 2006 15:04:05 -0700") + "\r\n" +
  31. "From: " + mailEncodeEmail(userName) + "\r\n" +
  32. "Subject: " + mailEncodeHeader(subject) + "\r\n" +
  33. "Content-Type: text/plain; charset=utf-8\r\n" +
  34. "\r\n" + message + "\r\n")
  35. return smtp.SendMail(fmt.Sprintf("%v:%v", host, port), auth, userName, receivers, msg)
  36. }
  37. // SendEmailHTML send email message with text/html mime type
  38. func SendEmailHTML(subject, message string, receivers []string, userName, userPassword, host, identity string, port int16) (err error) {
  39. auth := smtp.PlainAuth(identity, userName, userPassword, host)
  40. msg := []byte("To: " + mailJoinReceivers(receivers) + "\r\n" +
  41. "Date:" + time.Now().Format("Mon 2 Jan 2006 15:04:05 -0700") + "\r\n" +
  42. "From: " + mailEncodeEmail(userName) + "\r\n" +
  43. "Subject: " + mailEncodeHeader(subject) + "\r\n" +
  44. "Content-Type: text/html; charset=utf-8\r\n" +
  45. "\r\n" + message + "\r\n")
  46. return smtp.SendMail(fmt.Sprintf("%v:%v", host, port), auth, userName, receivers, msg)
  47. }