75 lines
1.8 KiB
Go
75 lines
1.8 KiB
Go
package email
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
"github.com/aws/aws-sdk-go/service/ses"
|
|
"github.com/pkg/errors"
|
|
gomail "gopkg.in/gomail.v2"
|
|
)
|
|
|
|
// Send sends email without attachments.
|
|
func (c *EmailClient) Send(ctx context.Context, sender string, mailList []*string, title string, body string) error {
|
|
if err := check(sender, mailList); err != nil {
|
|
return err
|
|
}
|
|
sesEmailInput := &ses.SendEmailInput{
|
|
Destination: &ses.Destination{
|
|
ToAddresses: mailList,
|
|
},
|
|
Message: &ses.Message{
|
|
Body: &ses.Body{
|
|
Html: &ses.Content{
|
|
Data: aws.String(body)},
|
|
},
|
|
Subject: &ses.Content{
|
|
Data: aws.String(title),
|
|
},
|
|
},
|
|
Source: aws.String(sender),
|
|
}
|
|
if _, err := c.ses.SendEmail(sesEmailInput); err != nil {
|
|
return errors.Wrap(err, "send email failed")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// SendRaw send email that supports attachments.
|
|
func (c *EmailClient) SendRaw(ctx context.Context, sender string, mailList []*string, title string, body string, attachments []string) error {
|
|
if err := check(sender, mailList); err != nil {
|
|
return err
|
|
}
|
|
msg := gomail.NewMessage(gomail.SetCharset("UTF-8"))
|
|
msg.SetHeader("From", sender)
|
|
toList := make([]string, len(mailList))
|
|
for i, l := range mailList {
|
|
toList[i] = *l
|
|
}
|
|
msg.SetHeader("To", toList...)
|
|
msg.SetHeader("Subject", title)
|
|
msg.SetBody("text/html", body)
|
|
for _, a := range attachments {
|
|
msg.Attach(a)
|
|
}
|
|
var emailRaw bytes.Buffer
|
|
_, _ = msg.WriteTo(&emailRaw)
|
|
if _, err := c.ses.SendRawEmail(&ses.SendRawEmailInput{
|
|
RawMessage: &ses.RawMessage{Data: emailRaw.Bytes()},
|
|
}); err != nil {
|
|
return errors.Wrap(err, "send raw email failed")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func check(sender string, mailList []*string) error {
|
|
if sender == "" {
|
|
return errors.New("no sender")
|
|
}
|
|
if len(mailList) == 0 {
|
|
return errors.New("no recipient")
|
|
}
|
|
return nil
|
|
}
|