1
0

email.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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. //Login to the SMTP server
  44. //Username can be username (e.g. admin) or email (e.g. [email protected]), depending on SMTP service provider
  45. auth := smtp.PlainAuth("", s.Username, s.Password, s.Hostname)
  46. err := smtp.SendMail(s.Hostname+":"+strconv.Itoa(s.Port), auth, s.SenderAddr, []string{to}, msg)
  47. if err != nil {
  48. return err
  49. }
  50. return nil
  51. }