-
Notifications
You must be signed in to change notification settings - Fork 0
/
mail_service.go
86 lines (74 loc) · 2.33 KB
/
mail_service.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
package main
import (
"bytes"
"context"
"fmt"
"guestbook/constants"
"log"
"github.com/emersion/go-sasl"
"github.com/emersion/go-smtp"
"github.com/spf13/viper"
"github.com/karim-w/go-azure-communication-services/emails"
)
func SendMail(recepients []string, subject, body string) error {
mailerToUse := viper.GetString("mailer.mailer_name")
if mailerToUse == "azure_communication_service" {
from := viper.GetString("mailer.azure_communication_service.from_email")
host := viper.GetString("mailer.azure_communication_service.host")
key := viper.GetString("mailer.azure_communication_service.key")
client := emails.NewClient(host, key, nil)
var err error
for _, recipient := range recepients {
payload := emails.Payload{
SenderAddress: from,
Content: emails.Content{
Subject: subject,
PlainText: body,
},
Recipients: emails.Recipients{
To: []emails.ReplyTo{
{
Address: recipient,
},
},
},
}
_, err = client.SendEmail(context.Background(), payload)
if err != nil {
log.Printf("WARN: Failed to send email: %v\n", err)
}
}
return err
} else if mailerToUse == "smtp" {
from := viper.GetString("mailer.smtp.from_email")
host := viper.GetString("mailer.smtp.host")
port := viper.GetString("mailer.smtp.port")
username := viper.GetString("mailer.smtp.username")
password := viper.GetString("mailer.smtp.password")
auth := sasl.NewLoginClient(username, password)
var err error
for _, recipient := range recepients {
message := "From: " + from + "\n" +
"To: " + recipient + "\n" +
"Subject: " + subject + "\n\n" +
body
to := []string{recipient}
msg := []byte(message)
reader := bytes.NewReader(msg)
err = smtp.SendMail(host+":"+port, auth, from, to, reader)
if err != nil {
log.Printf("WARN: Failed to send email: %v\n", err)
}
}
return err
} else {
log.Fatalf("Unknown mailer config: %s\n", mailerToUse)
panic("unknown mailer config")
}
}
func SendVerificationEmail(recipient, token string) error {
subject := "[Guestbooks] Please verify your email address"
verificationLink := fmt.Sprintf(constants.PUBLIC_URL+"/verify-email?token=%s", token)
body := fmt.Sprintf("Please click on the following link to verify your email address: %s", verificationLink)
return SendMail([]string{recipient}, subject, body)
}