-
Notifications
You must be signed in to change notification settings - Fork 218
/
amazon_ses.go
90 lines (78 loc) · 2.55 KB
/
amazon_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
package amazonses
import (
"context"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/ses"
"github.com/aws/aws-sdk-go-v2/service/ses/types"
)
//go:generate mockery --name=sesClient --output=. --case=underscore --inpackage
type sesClient interface {
SendEmail(
ctx context.Context,
params *ses.SendEmailInput,
optFns ...func(options *ses.Options),
) (*ses.SendEmailOutput, error)
}
// Compile-time check to ensure that ses.Client implements the sesClient interface.
var _ sesClient = new(ses.Client)
// AmazonSES struct holds necessary data to communicate with the Amazon Simple Email Service API.
type AmazonSES struct {
client sesClient
senderAddress *string
receiverAddresses []string
}
// New returns a new instance of a AmazonSES notification service.
// You will need an Amazon Simple Email Service API access key and secret.
// See https://aws.github.io/aws-sdk-go-v2/docs/getting-started/
func New(accessKeyID, secretKey, region, senderAddress string) (*AmazonSES, error) {
credProvider := credentials.NewStaticCredentialsProvider(accessKeyID, secretKey, "")
cfg, err := config.LoadDefaultConfig(
context.Background(),
config.WithCredentialsProvider(credProvider),
config.WithRegion(region),
)
if err != nil {
return nil, err
}
return &AmazonSES{
client: ses.NewFromConfig(cfg),
senderAddress: aws.String(senderAddress),
receiverAddresses: []string{},
}, nil
}
// AddReceivers takes email addresses and adds them to the internal address list. The Send method will send
// a given message to all those addresses.
func (a *AmazonSES) AddReceivers(addresses ...string) {
a.receiverAddresses = append(a.receiverAddresses, addresses...)
}
// Send takes a message subject and a message body and sends them to all previously set chats. Message body supports
// html as markup language.
func (a AmazonSES) Send(ctx context.Context, subject, message string) error {
input := &ses.SendEmailInput{
Source: a.senderAddress,
Destination: &types.Destination{
ToAddresses: a.receiverAddresses,
},
Message: &types.Message{
Body: &types.Body{
Html: &types.Content{
Data: aws.String(message),
},
// Text: &types.Content{
// Data: aws.String(message),
// },
},
Subject: &types.Content{
Data: aws.String(subject),
},
},
}
_, err := a.client.SendEmail(ctx, input)
if err != nil {
return fmt.Errorf("send mail using Amazon SES service: %w", err)
}
return nil
}