🌱🏠 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

package main
import (
"log"
"strings"
"time"
errors "git.sequentialread.com/forest/pkg-errors"
mail "github.com/xhit/go-simple-mail"
)
type EmailService struct {
Host string
Port int
Username string
Password string
Encryption string
}
func (emailService *EmailService) Initialize() error {
if emailService.Encryption == "" {
emailService.Encryption = "STARTTLS"
}
if emailService.Encryption != "STARTTLS" && emailService.Encryption != "SMTPS" {
return errors.New("EmailService.Encryption must be set to STARTTLS or SMTPS")
}
return nil
}
func (emailService *EmailService) ValidateEmailAddress(email string) string {
if len(email) == 0 {
return "email is required"
} else if len(email) < 6 || strings.Count(email, "@") != 1 || strings.Count(email, ".") < 1 || strings.LastIndex(email, ".") < strings.LastIndex(email, "@") {
return "email must be a valid email address, like user@example.com"
}
return ""
}
func (emailService *EmailService) SendEmail(subject, recipient, body string) error {
recipientError := emailService.ValidateEmailAddress(recipient)
if recipientError != "" {
return errors.New(recipientError)
}
smtpClient := mail.NewSMTPClient()
smtpClient.Host = emailService.Host
smtpClient.Port = emailService.Port
smtpClient.Username = emailService.Username
smtpClient.Password = emailService.Password
if emailService.Encryption == "STARTTLS" {
smtpClient.Encryption = mail.EncryptionTLS
} else {
smtpClient.Encryption = mail.EncryptionSSL
}
smtpClient.KeepAlive = false
smtpClient.ConnectTimeout = 10 * time.Second
smtpClient.SendTimeout = 10 * time.Second
smtpConn, err := smtpClient.Connect()
if err != nil {
log.Printf("SendEmail(): could not connect to email server: %+v", err)
return errors.New("could not connect to email server")
}
email := mail.NewMSG()
email.SetFrom(emailService.Username)
email.AddTo(recipient)
email.SetSubject(subject)
email.SetBody(mail.TextPlain, body)
err = email.Send(smtpConn)
if err != nil {
log.Printf("SendEmail(): connected to email server, but could not send mail: %+v", err)
return errors.New("connected to email server, but could not send mail")
}
return nil
}