-
Notifications
You must be signed in to change notification settings - Fork 0
/
sendgrid.go
74 lines (63 loc) · 1.8 KB
/
sendgrid.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
package mail
import (
"encoding/base64"
"fmt"
"github.com/sendgrid/sendgrid-go"
"github.com/sendgrid/sendgrid-go/helpers/mail"
"os"
)
func (s *SendGridSender) SendMail(
subject string,
content string,
to []string,
cc []string,
bcc []string,
attachFiles []string,
) error {
from := mail.NewEmail(s.AppName, s.AppEmail)
// Build recipients
toRecipients := []*mail.Email{}
for _, recipient := range to {
toRecipients = append(toRecipients, mail.NewEmail("", recipient))
}
// Create email message
message := mail.NewV3Mail()
message.SetFrom(from)
message.Subject = subject
// Add content
message.AddContent(mail.NewContent("text/html", content))
// Add recipients
personalization := mail.NewPersonalization()
for _, recipient := range toRecipients {
personalization.AddTos(recipient)
}
for _, ccRecipient := range cc {
personalization.AddCCs(mail.NewEmail("", ccRecipient))
}
for _, bccRecipient := range bcc {
personalization.AddBCCs(mail.NewEmail("", bccRecipient))
}
message.AddPersonalizations(personalization)
for _, filePath := range attachFiles {
fileContent, err := os.ReadFile(filePath)
if err != nil {
return fmt.Errorf("failed to read attachment: %w", err)
}
encodedContent := base64.StdEncoding.EncodeToString(fileContent)
attachment := mail.NewAttachment()
attachment.SetContent(encodedContent)
attachment.SetFilename(filePath)
attachment.SetType("application/octet-stream")
attachment.SetDisposition("attachment")
message.AddAttachment(attachment)
}
client := sendgrid.NewSendClient(s.APIKey)
response, err := client.Send(message)
if err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
if response.StatusCode >= 400 {
return fmt.Errorf("email sending failed with status: %d, body: %s", response.StatusCode, response.Body)
}
return nil
}