package email import ( "bytes" "encoding/json" "fmt" "io" "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() // Log the Mailgun API response responseBody, err := io.ReadAll(resp.Body) if err != nil { log.Printf("Error reading Mailgun API response: %v", err) return err } log.Printf("Mailgun API response: %s", responseBody) 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_ru" case constants.VerificationTypeForgotPassword: template = "password_reset" 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 err := MailgunRest(to[0], data, subject, template) // Log the response if err != nil { log.Printf("Error sending email: %v", err) } else { log.Println("Email sent successfully") } return err }