sdk-fix
This commit is contained in:
@@ -1,12 +1,11 @@
|
||||
package email
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"context"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
mailgun "github.com/mailgun/mailgun-go/v4"
|
||||
|
||||
log "github.com/sirupsen/logrus"
|
||||
|
||||
@@ -18,60 +17,21 @@ const apiURL = "https://api.mailgun.net/v3/%s/messages"
|
||||
func MailgunRest(to string, data map[string]interface{}, subject string, template string) error {
|
||||
var mailgunAPIKey = os.Getenv("MAILGUN_API_KEY")
|
||||
var mailgunDomain = os.Getenv("MAILGUN_DOMAIN")
|
||||
sender := mailgunDomain + "<noreply@" + mailgunDomain + ">"
|
||||
|
||||
// Create payload
|
||||
payload := map[string]interface{}{
|
||||
"from": "noreply@" + mailgunDomain,
|
||||
"to": to,
|
||||
"subject": subject,
|
||||
"template": template,
|
||||
}
|
||||
mg := mailgun.NewMailgun(mailgunDomain, mailgunAPIKey)
|
||||
m := mg.NewMessage(sender, subject, "", to)
|
||||
m.SetTemplate(template)
|
||||
m.AddTemplateVariable("validation_url", data["validation_url"])
|
||||
|
||||
vars, err := json.Marshal(data)
|
||||
if err != nil {
|
||||
payload["h:X-Mailgun-Variables"] = string(vars)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second*30)
|
||||
defer cancel()
|
||||
|
||||
// Convert payload to JSON
|
||||
payloadJSON, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, id, err := mg.Send(ctx, m)
|
||||
|
||||
log.Printf("Mailgun API request payload: %s", payloadJSON)
|
||||
log.Printf(id)
|
||||
|
||||
// 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()
|
||||
|
||||
// Log the Mailgun API response
|
||||
responseBody, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
log.Printf("Error %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
responseString := string(responseBody)
|
||||
log.Printf("Mailgun API response: %s", responseString)
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("failed to send email, status: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
// SendMailgun function to send
|
||||
|
Reference in New Issue
Block a user