This repository has been archived by the owner on Sep 22, 2023. It is now read-only.
/
ses.go
97 lines (81 loc) · 1.93 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 aws
import (
"bytes"
"context"
"log"
"os"
"github.com/aws/aws-sdk-go-v2/service/sesv2"
"github.com/aws/aws-sdk-go-v2/service/sesv2/types"
"gopkg.in/gomail.v2"
)
var (
client *sesv2.Client
from = os.Getenv("SMTP_FROM")
)
// SESEmail represents an email context
type SESEmail struct {
To string
Cc string
Bcc string
Data types.RawMessage
FileName string
}
// SESEmailClient initializes the AWS SES client.
func SESEmailClient() {
// Load assumed user role AWS configuration
cfg := AssumedRoleConfig()
// Initialize AWS Simple Email Service Client
client = sesv2.NewFromConfig(cfg)
}
// NewSESEmail returns an initialized SES email context.
func NewSESEmail() *SESEmail {
return &SESEmail{}
}
// BuildMessage builds email context.
func (e *SESEmail) BuildMessage(to, cc, bcc, subject, html, text, fileName string) {
e.To = to
e.Cc = cc
e.Bcc = bcc
e.FileName = fileName
// Initialize new email message
msg := gomail.NewMessage()
// Set email headers
msg.SetHeader("To", to)
msg.SetHeader("Subject", subject)
// Set email body
msg.SetBody("text/plain", text)
msg.SetBody("text/html", html)
// Set email attachment
msg.Attach(fileName)
// Create a new buffer to add raw email data
var emailRaw bytes.Buffer
msg.WriteTo(&emailRaw)
// Set email data
e.Data = types.RawMessage{
Data: emailRaw.Bytes(),
}
}
// Send sends an email using AWS SES.
func (e *SESEmail) Send() error {
// Input email content
input := &sesv2.SendEmailInput{
FromEmailAddress: &from,
Destination: &types.Destination{
ToAddresses: []string{e.To},
BccAddresses: []string{e.Bcc},
},
Content: &types.EmailContent{
Raw: &e.Data,
},
}
// Send email
output, err := client.SendEmail(context.Background(), input)
if err != nil {
log.Println("Send email error: ", err.Error())
return err
}
log.Println("Email sent: ", *output.MessageId)
// Delete attachment
os.Remove(e.FileName)
return nil
}