/
ses.go
97 lines (86 loc) · 2.69 KB
/
ses.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package mailing
import (
"context"
"errors"
"fmt"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/ses"
"github.com/aws/aws-sdk-go/service/ses/sesiface"
"github.com/gazebo-web/gz-go/v9"
)
// awsSimpleEmailService implements the Sender interface using AWS Simple Email Service API.
// This implementation uses the AWS SDK v1.
//
// References:
// - AWS SDK V1: https://github.com/aws/aws-sdk-go
// - AWS SES SDK V1: https://pkg.go.dev/github.com/aws/aws-sdk-go/service/ses
type awsSimpleEmailService struct {
API sesiface.SESAPI
}
// Send sends an email from sender to the given recipients. The email body is composed by an HTML template
// that is filled in with values provided in data.
func (e *awsSimpleEmailService) Send(ctx context.Context, sender string, recipients, cc, bcc []string, subject, template string, data any) error {
err := validateEmail(sender, recipients, cc, bcc, data)
if err != nil {
return err
}
content, err := gz.ParseHTMLTemplate(template, data)
if err != nil {
return err
}
err = e.send(ctx, sender, recipients, cc, bcc, subject, content)
if err != nil {
return err
}
return nil
}
// send attempts to send an email using the AWS SES service.
func (e *awsSimpleEmailService) send(_ context.Context, sender string, recipients []string, cc []string, bcc []string, subject string, content string) error {
input := ses.SendEmailInput{
Destination: &ses.Destination{
CcAddresses: aws.StringSlice(cc),
BccAddresses: aws.StringSlice(bcc),
ToAddresses: aws.StringSlice(recipients),
},
Message: &ses.Message{
Body: &ses.Body{
Html: &ses.Content{
Charset: aws.String(charset),
Data: aws.String(content),
},
},
Subject: &ses.Content{
Charset: aws.String(charset),
Data: aws.String(subject),
},
},
Source: aws.String(sender),
}
// Attempt to send the awsSimpleEmailService.
_, err := e.API.SendEmail(&input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
var code string
switch aerr.Code() {
case ses.ErrCodeMessageRejected:
code = ses.ErrCodeMessageRejected
case ses.ErrCodeMailFromDomainNotVerifiedException:
code = ses.ErrCodeMailFromDomainNotVerifiedException
case ses.ErrCodeConfigurationSetDoesNotExistException:
code = ses.ErrCodeConfigurationSetDoesNotExistException
default:
code = "Unknown AWS SES error"
}
return fmt.Errorf("%s %s", code, aerr.Error())
}
return errors.New(err.Error())
}
return nil
}
// NewSimpleEmailServiceSender returns a Sender implementation using AWS Simple Email Service.
func NewSimpleEmailServiceSender(api sesiface.SESAPI) Sender {
return &awsSimpleEmailService{
API: api,
}
}