1
0

email.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package email
  2. import (
  3. "net/smtp"
  4. "strconv"
  5. )
  6. /*
  7. Email.go
  8. This script handle mailing services using SMTP protocol
  9. */
  10. type Sender struct {
  11. Hostname string //E.g. mail.gandi.net
  12. Port int //E.g. 587
  13. Username string //Username of the email account
  14. Password string //Password of the email account
  15. SenderAddr string //e.g. [email protected]
  16. }
  17. // Create a new email sender object
  18. func NewEmailSender(hostname string, port int, username string, password string, senderAddr string) *Sender {
  19. return &Sender{
  20. Hostname: hostname,
  21. Port: port,
  22. Username: username,
  23. Password: password,
  24. SenderAddr: senderAddr,
  25. }
  26. }
  27. /*
  28. Send a email to a reciving addr
  29. Example Usage:
  30. SendEmail(
  31. [email protected],
  32. "Free donuts",
  33. "Come get your free donuts on this Sunday!"
  34. )
  35. */
  36. func (s *Sender) SendEmail(to string, subject string, content string) error {
  37. // Parse the email content
  38. msg := []byte("To: " + to + "\n" +
  39. "From: Zoraxy <" + s.SenderAddr + ">\n" +
  40. "Subject: " + subject + "\n" +
  41. "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n" +
  42. content + "\n\n")
  43. // Initialize the auth variable
  44. var auth smtp.Auth
  45. if s.Password != "" {
  46. // Login to the SMTP server
  47. // Username can be username (e.g. admin) or email (e.g. [email protected]), depending on SMTP service provider
  48. auth = smtp.PlainAuth("", s.Username, s.Password, s.Hostname)
  49. }
  50. // Send the email
  51. err := smtp.SendMail(s.Hostname+":"+strconv.Itoa(s.Port), auth, s.SenderAddr, []string{to}, msg)
  52. if err != nil {
  53. return err
  54. }
  55. return nil
  56. }