66 lines
1.3 KiB
Go
66 lines
1.3 KiB
Go
package mail
|
|
|
|
import (
|
|
"fmt"
|
|
"net/smtp"
|
|
|
|
"github.com/jordan-wright/email"
|
|
)
|
|
|
|
const (
|
|
smtpAuthAddress = "smtp.gmail.com"
|
|
smtpServerAddress = "smtp.gmail.com:587"
|
|
)
|
|
|
|
type EmailSender interface {
|
|
SendEmail(
|
|
subject string,
|
|
content string,
|
|
to []string,
|
|
cc []string,
|
|
bcc []string,
|
|
attachFiles []string,
|
|
) error
|
|
}
|
|
|
|
type GmailSender struct {
|
|
displayName string
|
|
fromEmailAddress string
|
|
fromEmailPassword string
|
|
}
|
|
|
|
func NewGmailSender(displayName string, fromEmailAddress string, fromEmailPassword string) EmailSender {
|
|
return &GmailSender{
|
|
displayName: displayName,
|
|
fromEmailAddress: fromEmailAddress,
|
|
fromEmailPassword: fromEmailPassword,
|
|
}
|
|
}
|
|
|
|
func (sender *GmailSender) SendEmail(
|
|
subject string,
|
|
content string,
|
|
to []string,
|
|
cc []string,
|
|
bcc []string,
|
|
attachFiles []string,
|
|
) error {
|
|
e := email.NewEmail()
|
|
e.From = fmt.Sprintf("%s <%s>", sender.displayName, sender.fromEmailAddress)
|
|
e.Subject = subject
|
|
e.HTML = []byte(content)
|
|
e.To = to
|
|
e.Cc = cc
|
|
e.Bcc = bcc
|
|
|
|
for _, f := range attachFiles {
|
|
_, err := e.AttachFile(f)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to attach file %s: %w", f, err)
|
|
}
|
|
}
|
|
|
|
smtpAuth := smtp.PlainAuth("", sender.fromEmailAddress, sender.fromEmailPassword, smtpAuthAddress)
|
|
return e.Send(smtpServerAddress, smtpAuth)
|
|
}
|