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" 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") vars, err := json.Marshal(data) if err != nil { vars = nil } // Create payload payload := map[string]interface{}{ "from": mailgunDomain + " ", "to": to, "subject": subject, "template": template, "h:X-Mailgun-Variables": string(vars), } // 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 { return fmt.Errorf("failed to send email, status: %d", resp.StatusCode) } 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 return MailgunRest(to[0], data, subject, template) }