Semaphore/util/mail.go

68 lines
1.2 KiB
Go
Raw Normal View History

package util
import (
"bytes"
log "github.com/Sirupsen/logrus"
"io"
2021-09-22 05:43:19 +02:00
"net/smtp"
)
// SendMail dispatches a mail using smtp
2017-03-13 03:30:48 +01:00
func SendMail(emailHost, mailSender, mailRecipient string, mail bytes.Buffer) error {
c, err := smtp.Dial(emailHost)
if err != nil {
return err
}
2021-09-22 05:43:19 +02:00
defer func(c *smtp.Client) {
err = c.Close()
if err != nil {
log.Error(err)
}
}(c)
2017-04-18 16:36:09 +02:00
// Set the sender and recipient.
err = c.Mail(mailSender)
if err != nil {
return err
}
err = c.Rcpt(mailRecipient)
if err != nil {
return err
}
// Send the email body.
wc, err := c.Data()
if err != nil {
return err
}
2021-09-22 05:43:19 +02:00
defer func(wc io.WriteCloser) {
err = wc.Close()
if err != nil {
log.Error(err)
}
}(wc)
2017-04-18 16:36:09 +02:00
_, err = mail.WriteTo(wc)
return err
}
2021-09-22 05:43:19 +02:00
// SendSecureMail dispatches a mail using smtp with authentication and StartTLS
func SendSecureMail(emailHost, emailPort, mailSender, mailUsername, mailPassword, mailRecipient string, mail bytes.Buffer) error {
// Receiver email address.
to := []string{
mailRecipient,
}
// Authentication.
auth := smtp.PlainAuth("", mailUsername, mailPassword, emailHost)
// Sending email.
2021-09-22 06:01:53 +02:00
err := smtp.SendMail(emailHost+":"+emailPort, auth, mailSender, to, mail.Bytes())
2021-09-22 05:43:19 +02:00
if err != nil {
2021-09-22 06:01:53 +02:00
log.Error(err)
2021-09-22 05:43:19 +02:00
}
2021-09-22 06:01:53 +02:00
return err
2021-09-22 05:43:19 +02:00
}