authorizer/server/email/mailgun.go

90 lines
2.1 KiB
Go
Raw Normal View History

2024-01-05 10:06:43 +00:00
package email
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
// log "github.com/sirupsen/logrus"
"github.com/authorizerdev/authorizer/server/constants"
)
const apiURL = "https://api.mailgun.net/v3/%s/messages"
2024-01-05 11:09:02 +00:00
func MailgunRest(to string, data map[string]interface{}, subject string, template string) error {
2024-01-05 10:06:43 +00:00
var mailgunAPIKey = os.Getenv("MAILGUN_API_KEY")
var mailgunDomain = os.Getenv("MAILGUN_DOMAIN")
2024-01-05 10:19:46 +00:00
vars, err := json.Marshal(data)
2024-01-05 10:06:43 +00:00
if err != nil {
2024-01-05 10:19:46 +00:00
vars = nil
2024-01-05 10:06:43 +00:00
}
// Create payload
payload := map[string]interface{}{
"from": mailgunDomain + " <noreply@" + mailgunDomain + ">",
"to": to,
"subject": subject,
"template": template,
2024-01-05 10:19:46 +00:00
"h:X-Mailgun-Variables": string(vars),
2024-01-05 10:06:43 +00:00
}
// Convert payload to JSON
payloadJSON, err := json.Marshal(payload)
if err != nil {
return err
}
// Make HTTP POST request
client := &http.Client{}
req, err := http.NewRequest("POST", fmt.Sprintf(apiURL, mailgunDomain), bytes.NewBuffer(payloadJSON))
if err != nil {
return err
}
req.SetBasicAuth("api", mailgunAPIKey)
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
2024-01-05 11:17:56 +00:00
return fmt.Errorf("failed to send email, status: %d", resp.StatusCode)
2024-01-05 10:06:43 +00:00
}
return nil
}
// SendMailgun function to send
func SendMailgun(to []string, event string, data map[string]interface{}) error {
template := "email_confirmation"
switch event {
case constants.VerificationTypeBasicAuthSignup:
template = "email_confirmation"
case constants.VerificationTypeForgotPassword:
template = "reset_password"
case constants.VerificationTypeInviteMember:
template = "author_invited"
case constants.VerificationTypeMagicLinkLogin:
template = "magic_link_login"
case constants.VerificationTypeOTP:
template = "one_time_password"
case constants.VerificationTypeUpdateEmail:
template = "email_update"
}
subject := "Подтверждение почты"
// TODO: language selection logic here
2024-01-05 11:09:02 +00:00
return MailgunRest(to[0], data, subject, template)
2024-01-05 10:06:43 +00:00
}