🌱🏠 a cloud service to enable your own server (owned by you and running on your computer) to be accessible on the internet in seconds, no credit card required https://greenhouse.server.garden/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

75 lines
2.2 KiB

9 months ago
9 months ago
9 months ago
9 months ago
  1. package main
  2. import (
  3. "log"
  4. "strings"
  5. "time"
  6. errors "git.sequentialread.com/forest/pkg-errors"
  7. mail "github.com/xhit/go-simple-mail"
  8. )
  9. type EmailService struct {
  10. Host string
  11. Port int
  12. Username string
  13. Password string
  14. Encryption string
  15. }
  16. func (emailService *EmailService) Initialize() error {
  17. if emailService.Encryption == "" {
  18. emailService.Encryption = "STARTTLS"
  19. }
  20. if emailService.Encryption != "STARTTLS" && emailService.Encryption != "SMTPS" {
  21. return errors.New("EmailService.Encryption must be set to STARTTLS or SMTPS")
  22. }
  23. return nil
  24. }
  25. func (emailService *EmailService) ValidateEmailAddress(email string) string {
  26. if len(email) == 0 {
  27. return "email is required"
  28. } else if len(email) < 6 || strings.Count(email, "@") != 1 || strings.Count(email, ".") < 1 || strings.LastIndex(email, ".") < strings.LastIndex(email, "@") {
  29. return "email must be a valid email address, like user@example.com"
  30. }
  31. return ""
  32. }
  33. func (emailService *EmailService) SendEmail(subject, recipient, body string) error {
  34. recipientError := emailService.ValidateEmailAddress(recipient)
  35. if recipientError != "" {
  36. return errors.New(recipientError)
  37. }
  38. smtpClient := mail.NewSMTPClient()
  39. smtpClient.Host = emailService.Host
  40. smtpClient.Port = emailService.Port
  41. smtpClient.Username = emailService.Username
  42. smtpClient.Password = emailService.Password
  43. if emailService.Encryption == "STARTTLS" {
  44. smtpClient.Encryption = mail.EncryptionTLS
  45. } else {
  46. smtpClient.Encryption = mail.EncryptionSSL
  47. }
  48. smtpClient.KeepAlive = false
  49. smtpClient.ConnectTimeout = 10 * time.Second
  50. smtpClient.SendTimeout = 10 * time.Second
  51. smtpConn, err := smtpClient.Connect()
  52. if err != nil {
  53. log.Printf("SendEmail(): could not connect to email server: %+v", err)
  54. return errors.New("could not connect to email server")
  55. }
  56. email := mail.NewMSG()
  57. email.SetFrom(emailService.Username)
  58. email.AddTo(recipient)
  59. email.SetSubject(subject)
  60. email.SetBody(mail.TextPlain, body)
  61. err = email.Send(smtpConn)
  62. if err != nil {
  63. log.Printf("SendEmail(): connected to email server, but could not send mail: %+v", err)
  64. return errors.New("connected to email server, but could not send mail")
  65. }
  66. return nil
  67. }