因為 AWS 官方文件沒有 GO 的範例,記錄一下測過的版本
main.go
1package main
2
3import "fmt"
4
5func main() {
6 subject := "這是測試信件"
7 bodyText := "這是測試信件的純文字內文"
8 bodyHtml := "<p>這是測試信件的內文</p>"
9 sender := "noreply@fall-prediction.net"
10 recipients := []string{"lizne6z0@gmail.com"}
11
12 ses := NewSes("ap-south-1")
13 messageId, err := ses.SendEmail(subject, bodyText, bodyHtml, sender, recipients)
14
15 if err != nil {
16 fmt.Println("The email was not sent. Error message: ", err)
17 } else {
18 fmt.Println("Email sent! Message ID: " + messageId)
19 }
20}
ses.go
1package main
2
3import (
4 "context"
5 "sync"
6
7 "github.com/aws/aws-sdk-go-v2/config"
8 "github.com/aws/aws-sdk-go-v2/service/sesv2"
9 "github.com/aws/aws-sdk-go-v2/service/sesv2/types"
10)
11
12var ses *Ses
13var sesOnce sync.Once
14
15type Ses struct {
16 client *sesv2.Client
17}
18
19func (s *Ses) SendEmail(subject, bodyText, bodyHtml string, sender string, recipients []string) (string, error) {
20 emailInput := s.getEmailInput(subject, bodyText, bodyHtml, sender, recipients)
21 output, err := s.client.SendEmail(context.Background(), &emailInput)
22 return *output.MessageId, err
23}
24
25func (s *Ses) getEmailInput(subject, bodyText, bodyHtml string, sender string, recipients []string) sesv2.SendEmailInput {
26 charset := "UTF-8"
27 return sesv2.SendEmailInput{
28 FromEmailAddress: &sender,
29 Content: &types.EmailContent{
30 Simple: &types.Message{
31 Body: &types.Body{
32 Html: &types.Content{
33 Data: &bodyHtml,
34 Charset: &charset,
35 },
36 Text: &types.Content{
37 Data: &bodyText,
38 Charset: &charset,
39 },
40 },
41 Subject: &types.Content{
42 Data: &subject,
43 Charset: &charset,
44 },
45 },
46 },
47 Destination: &types.Destination{
48 ToAddresses: recipients,
49 },
50 }
51}
52
53func NewSes(region string) *Ses {
54 if ses == nil {
55 sesOnce.Do(func() {
56 cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithRegion(region))
57 if err != nil {
58 panic("unable to load SDK config" + err.Error())
59 }
60 sesClient := sesv2.NewFromConfig(cfg)
61 ses = &Ses{sesClient}
62 })
63 }
64 return ses
65}
另:官方文件建議為每個收件人個別呼叫 SendEmail 一次