2021-01-25 01:14:21 +02:00
|
|
|
package mail
|
|
|
|
|
|
|
|
import (
|
2021-01-25 06:05:28 +02:00
|
|
|
"net/smtp"
|
|
|
|
"net/textproto"
|
2021-01-25 01:14:21 +02:00
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
"github.com/jordan-wright/email"
|
|
|
|
"github.com/pkg/errors"
|
2021-01-25 01:14:21 +02:00
|
|
|
)
|
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// Mail struct holds necessary data to send emails.
|
2021-01-25 01:14:21 +02:00
|
|
|
type Mail struct {
|
2021-01-25 06:05:28 +02:00
|
|
|
senderAddress string
|
|
|
|
smtpHostAddr string
|
|
|
|
smtpAuth smtp.Auth
|
2021-01-25 01:14:21 +02:00
|
|
|
receiverAddresses []string
|
|
|
|
}
|
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// New returns a new instance of a Mail notification service.
|
|
|
|
func New(senderAddress, smtpHostAddress string) *Mail {
|
|
|
|
return &Mail{
|
|
|
|
senderAddress: senderAddress,
|
|
|
|
smtpHostAddr: smtpHostAddress,
|
2021-01-25 01:14:21 +02:00
|
|
|
receiverAddresses: []string{},
|
|
|
|
}
|
2021-01-25 06:05:28 +02:00
|
|
|
}
|
2021-01-25 01:14:21 +02:00
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// AuthenticateSMTP authenticates you to send emails via smtp.
|
|
|
|
// Example values: "", "test@gmail.com", "password123", "smtp.gmail.com"
|
2021-01-26 12:31:33 +02:00
|
|
|
// For more information about smtp authentication, see here:
|
|
|
|
// -> https://pkg.go.dev/net/smtp#PlainAuth
|
2021-01-25 06:05:28 +02:00
|
|
|
func (m *Mail) AuthenticateSMTP(identity, userName, password, host string) {
|
|
|
|
m.smtpAuth = smtp.PlainAuth(identity, userName, password, host)
|
2021-01-25 01:14:21 +02:00
|
|
|
}
|
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// AddReceivers takes email addresses and adds them to the internal address list. The Send method will send
|
|
|
|
// a given message to all those addresses.
|
2021-01-25 01:14:21 +02:00
|
|
|
func (m *Mail) AddReceivers(addresses ...string) {
|
|
|
|
m.receiverAddresses = append(m.receiverAddresses, addresses...)
|
|
|
|
}
|
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
// Send takes a message subject and a message body and sends them to all previously set chats. Message body supports
|
|
|
|
// html as markup language.
|
2021-01-25 01:14:21 +02:00
|
|
|
func (m Mail) Send(subject, message string) error {
|
2021-01-25 06:05:28 +02:00
|
|
|
msg := &email.Email{
|
|
|
|
To: m.receiverAddresses,
|
|
|
|
From: m.senderAddress,
|
|
|
|
Subject: subject,
|
|
|
|
// Text: []byte("Text Body is, of course, supported!"),
|
|
|
|
HTML: []byte(message),
|
|
|
|
Headers: textproto.MIMEHeader{},
|
|
|
|
}
|
2021-01-25 01:14:21 +02:00
|
|
|
|
2021-01-25 06:05:28 +02:00
|
|
|
err := msg.Send(m.smtpHostAddr, m.smtpAuth)
|
2021-01-25 01:14:21 +02:00
|
|
|
if err != nil {
|
2021-01-25 06:05:28 +02:00
|
|
|
err = errors.Wrap(err, "failed to send mail")
|
2021-01-25 01:14:21 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
return err
|
|
|
|
}
|