email.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. Domain string //E.g. arozos.com
  13. Port int //E.g. 587
  14. Username string //Username of the email account
  15. Password string //Password of the email account
  16. SenderAddr string //e.g. [email protected]
  17. }
  18. //Create a new email sender object
  19. func NewEmailSender(hostname string, domain string, port int, username string, password string, senderAddr string) *Sender {
  20. return &Sender{
  21. Hostname: hostname,
  22. Domain: domain,
  23. Port: port,
  24. Username: username,
  25. Password: password,
  26. SenderAddr: senderAddr,
  27. }
  28. }
  29. /*
  30. Send a email to a reciving addr
  31. Example Usage:
  32. SendEmail(
  33. [email protected],
  34. "Free donuts",
  35. "Come get your free donuts on this Sunday!"
  36. )
  37. */
  38. func (s *Sender) SendEmail(to string, subject string, content string) error {
  39. //Parse the email content
  40. msg := []byte("To: " + to + "\n" +
  41. "From: Zoraxy <" + s.SenderAddr + ">\n" +
  42. "Subject: " + subject + "\n" +
  43. "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n" +
  44. content + "\n\n")
  45. //Login to the SMTP server
  46. auth := smtp.PlainAuth("", s.Username+"@"+s.Domain, s.Password, s.Hostname)
  47. err := smtp.SendMail(s.Hostname+":"+strconv.Itoa(s.Port), auth, s.SenderAddr, []string{to}, msg)
  48. if err != nil {
  49. return err
  50. }
  51. return nil
  52. }