### Code Examples Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/COMPLETION_SUMMARY.txt Over 100 working code examples are included, demonstrating real-world patterns, batch operations, and error handling, following Go best practices and tested patterns from the README. ```APIDOC ## Code Examples ### Usage Examples - Each significant function is accompanied by at least one usage example. - Examples are tested patterns derived from the README and follow Go best practices. - Real-world patterns, including batch operations and error handling, are demonstrated. ### Example Structure (Illustrative) ```go // Example for sending a single email msg := mailgun.Message{ To: []string{"recipient@example.com"}, From: "sender@example.com", Subject: "Hello from mailgun-go", Text: "This is a test email.", } // Assuming 'mg' is an initialized mailgun.Client ID, err := mg.Send(msg) if err != nil { log.Fatalf("Failed to send email: %v", err) } fmt.Printf("Email sent with ID: %s\n", ID) ``` ``` -------------------------------- ### Install Mailgun Go Library Source: https://github.com/mailgun/mailgun-go/blob/main/README.md Use this command to install the Mailgun Go library with Go Modules, ensuring you include the /v5 suffix for the correct version. ```bash go get github.com/mailgun/mailgun-go/v5 ``` -------------------------------- ### Create IP Warmup Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Starts the IP warmup process for a dedicated IP address. This operation requires a valid context and the IP address. ```go err := mg.CreateIPWarmup(ctx, "192.0.2.1") if err != nil { log.Fatal(err) } fmt.Println("IP warmup started") ``` -------------------------------- ### Configure Event Listing with Filters Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Example of configuring event list options with a limit, time range, and event filter. This allows for precise retrieval of event logs. ```go opts := &mailgun.ListEventOptions{ Limit: 100, Begin: time.Now().Add(-24 * time.Hour), Filter: map[string]string{ "event": "delivered OR failed", }, } it := mg.ListEvents("mg.example.com", opts) ``` -------------------------------- ### Configure Domain Listing with Filters Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Example of configuring domain list options with a specific limit, state, and search term. This is useful for targeted domain retrieval. ```go opts := &mailgun.ListDomainsOptions{ Limit: 50, State: mailgun.DomainStatePtr(mtypes.DomainStateActive), Search: mailgun.StringPtr("mail"), } it := mg.ListDomains(opts) ``` -------------------------------- ### Mailgun Route Expression Examples Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Provides examples of common route expression syntax for filtering incoming messages. ```text match_all() // Match all messages match_recipient("user@example.com") // Match specific recipient match_header("subject", "test") // Match header value match_header("from", ".*@example.com") // Regex match on header ``` -------------------------------- ### CreateIPWarmup Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Starts the IP warmup process for a dedicated IP address. This action initiates the gradual increase of sending volume to establish the IP's reputation. ```APIDOC ## CreateIPWarmup ### Description Starts IP warmup for a dedicated IP. ### Method `CreateIPWarmup(ctx context.Context, ip string)` ### Parameters #### Path Parameters - **ip** (string) - Required - IP address to warmup #### Query Parameters - **ctx** (context.Context) - Required - Context for timeout ### Returns error if warmup cannot start ### Example ```go err := mg.CreateIPWarmup(ctx, "192.0.2.1") if err != nil { log.Fatal(err) } fmt.Println("IP warmup started") ``` ``` -------------------------------- ### Client Creation from Environment Variables Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/COMPLETION_SUMMARY.txt Creates a new Mailgun client instance using API key and domain from environment variables. Useful for quick setup in various environments. ```go // NewMailgunFromEnv() - Environment-based creation ``` -------------------------------- ### Handle Mailgun Webhooks with Go Source: https://github.com/mailgun/mailgun-go/blob/main/README.md This example demonstrates how to securely handle incoming Mailgun webhooks in a Go application. It verifies the webhook signature before processing the event. ```go package main import ( "encoding/json" "fmt" "net/http" "os" "github.com/mailgun/mailgun-go/v5" "github.com/mailgun/mailgun-go/v5/events" "github.com/mailgun/mailgun-go/v5/mtypes" ) func main() { // You can find Mailgun API keys in your Account Menu, under "API Security": // (https://app.mailgun.com/settings/api_security) mg := mailgun.NewMailgun("MAILGUN_API_KEY") mg.SetWebhookSigningKey("WEBHOOK_SIGNING_KEY") http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { var payload mtypes.WebhookPayload if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { fmt.Printf("decode JSON error: %s", err) w.WriteHeader(http.StatusNotAcceptable) return } verified, err := mg.VerifyWebhookSignature(payload.Signature) if err != nil { fmt.Printf("verify error: %s\n", err) w.WriteHeader(http.StatusNotAcceptable) return } if !verified { w.WriteHeader(http.StatusNotAcceptable) fmt.Printf("failed verification %+v\n", payload.Signature) return } fmt.Printf("Verified Signature\n") // Parse the event provided by the webhook payload e, err := events.ParseEvent(payload.EventData) if err != nil { fmt.Printf("parse event error: %s\n", err) return } switch event := e.(type) { case *events.Accepted: fmt.Printf("Accepted: auth: %t\n", event.Flags.IsAuthenticated) case *events.Delivered: fmt.Printf("Delivered transport: %s\n", event.Envelope.Transport) } }) fmt.Println("Serve on :9090...") if err := http.ListenAndServe(":9090", nil); err != nil { fmt.Printf("serve error: %s\n", err) os.Exit(1) } } ``` -------------------------------- ### GetDomain Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Retrieves detailed information about a specific domain, including DNS records needed for setup. ```APIDOC ## GetDomain ### Description Retrieves detailed information about a specific domain, including DNS records needed for setup. ### Method `GetDomain` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters #### Path Parameters - **domain** (string) - Required - Domain name (e.g., `mg.example.com`) #### Query Parameters - **opts** (*GetDomainOptions) - Optional - Options (e.g., Verify: true) ### Returns - `mtypes.GetDomainResponse`: Domain details and DNS records. ### Throws - `UnexpectedResponseError`: If domain not found or API error. ### Example ```go resp, err := mg.GetDomain(ctx, "mg.example.com", nil) if err != nil { log.Fatal(err) } fmt.Printf("Domain: %s\n", resp.Domain.Name) fmt.Printf("State: %s\n", resp.Domain.State) // Display sending DNS records for _, record := range resp.SendingDNSRecords { fmt.Printf("Record: %s = %s\n", record.Name, record.Value) } ``` ``` -------------------------------- ### Get Domain Details Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Retrieves detailed information and DNS records for a specific domain. Pass a context for cancellation and an optional options struct. ```go resp, err := mg.GetDomain(ctx, "mg.example.com", nil) if err != nil { log.Fatal(err) } fmt.Printf("Domain: %s\n", resp.Domain.Name) fmt.Printf("State: %s\n", resp.Domain.State) // Display sending DNS records for _, record := range resp.SendingDNSRecords { fmt.Printf("Record: %s = %s\n", record.Name, record.Value) } ``` -------------------------------- ### Get Export Download Link Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Gets the download link for a specific data export by its ID. Requires a context and the export ID. ```go func (mg *Client) GetExportLink(ctx context.Context, id string) (string, error) ``` -------------------------------- ### Send HTML Email with Mailgun Go SDK Source: https://github.com/mailgun/mailgun-go/blob/main/README.md This example shows how to send an HTML formatted email using the Mailgun Go SDK. Ensure you have your domain and API key configured. ```go package main import ( "context" "fmt" "log" "time" "github.com/mailgun/mailgun-go/v5" ) // Your available domain names can be found here: // (https://app.mailgun.com/app/domains) var yourDomain = "your-domain-name" // e.g. mg.yourcompany.com // You can find Mailgun API keys in your Account Menu, under "API Security": // (https://app.mailgun.com/settings/api_security) var apiKey = "MAILGUN_API_KEY" func main() { // Create an instance of the Mailgun Client mg := mailgun.NewMailgun(apiKey) sender := "sender@example.com" subject := "HTML email!" recipient := "recipient@example.com" message := mailgun.NewMessage(yourDomain, sender, subject, "", recipient) body := `
Hello world
More examples can be found here
` message.SetHTML(body) ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() // Send the message with a 10-second timeout resp, err := mg.Send(ctx, message) if err != nil { log.Fatal(err) } fmt.Printf("ID: %s Resp: %s\n", resp.ID, resp.Message) } ``` -------------------------------- ### Get Webhook Signing Key Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/client.md Retrieves the configured webhook signing key for verifying webhook signatures. ```go key := mg.WebhookSigningKey() ``` -------------------------------- ### Verify Domain Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/COMPLETION_SUMMARY.txt Initiates the verification process for a domain with Mailgun. This typically involves DNS record setup. ```go // VerifyDomain() - Domain verification ``` -------------------------------- ### Get Domain Connection (Deprecated) Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Retrieves domain connection settings. This method is deprecated and `GetDomain` should be used instead. ```go func (mg *Client) GetDomainConnection(ctx context.Context, domain string) (mtypes.DomainConnection, error) ``` -------------------------------- ### Create a New Domain Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Creates a new domain in your Mailgun account with specified options like spam action and web scheme. Returns domain details and DNS setup instructions. ```go resp, err := mg.CreateDomain(ctx, "mail.mycompany.com", &mailgun.CreateDomainOptions{ SpamAction: mtypes.SpamActionTag, WebScheme: "https", }) if err != nil { log.Fatal(err) } fmt.Printf("Domain %s created\n", resp.Domain.Name) fmt.Printf("Please configure these DNS records:\n") for _, record := range resp.SendingDNSRecords { fmt.Printf(" %s: %s\n", record.RecordType, record.Value) } ``` -------------------------------- ### ParseEvent Example Usage Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/events.md Demonstrates how to parse a single event from webhook data and handle different event types using a type switch. Ensure the webhook data is correctly unmarshalled into `mtypes.WebhookPayload` first. ```go var payload mtypes.WebhookPayload if err := json.Unmarshal(webhookData, &payload); err != nil { log.Fatal(err) } event, err := events.ParseEvent(payload.EventData) if err != nil { log.Fatal(err) } switch e := event.(type) { case *events.Delivered: fmt.Printf("Delivered to %s\n", e.Recipient) case *events.Failed: fmt.Printf("Failed: %s\n", e.Reason) } ``` -------------------------------- ### Get Domain Tracking Settings Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Retrieves the current tracking settings for a specified domain. Use this to check the status of open, click, and unsubscribe tracking. ```go tracking, err := mg.GetDomainTracking(ctx, "mail.mycompany.com") if err != nil { log.Fatal(err) } fmt.Printf("Open tracking: %v\n", tracking.OpenTrackingActive) fmt.Printf("Click tracking: %v\n", tracking.ClickTrackingActive) ``` -------------------------------- ### Get Specific IP Information Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Retrieves detailed information about a specific IP address. Requires the IP address string and context for timeouts. ```go ipInfo, err := mg.GetIP(ctx, "192.0.2.1") if err != nil { log.Fatal(err) } fmt.Printf("IP: %s\n", ipInfo.IP) fmt.Printf("Warmup: %v\n", ipInfo.Warmup) ``` -------------------------------- ### Send Email with Mailgun Go Source: https://github.com/mailgun/mailgun-go/blob/main/README.md This Go code snippet demonstrates how to send an email using the Mailgun API. Ensure you have your Mailgun API key and domain configured. The example includes setting a timeout for the API request. ```go package main import ( "context" "fmt" "log" "time" "github.com/mailgun/mailgun-go/v5" ) // Your available domain names can be found here: // (https://app.mailgun.com/app/domains) var yourDomain = "your-domain-name" // e.g. mg.yourcompany.com // You can find Mailgun API keys in your Account Menu, under "API Security": // (https://app.mailgun.com/settings/api_security) var apiKey = "MAILGUN_API_KEY" func main() { // Create an instance of the Mailgun Client mg := mailgun.NewMailgun(apiKey) // When you have an EU domain, you must specify the endpoint: // err := mg.SetAPIBase(mailgun.APIBaseEU) sender := "sender@example.com" subject := "Fancy subject!" body := "Hello from Mailgun Go!" recipient := "recipient@example.com" // The message object allows you to add attachments and Bcc recipients message := mailgun.NewMessage(yourDomain, sender, subject, body, recipient) ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() // Send the message with a 10-second timeout resp, err := mg.Send(ctx, message) if err != nil { log.Fatal(err) } fmt.Printf("ID: %s Resp: %s\n", resp.ID, resp.Message) } ``` -------------------------------- ### Create Domain with Options Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Creates a new domain with specified options, including spam action, web scheme, and message TTL. Use this for custom domain configurations. ```go opts := &mailgun.CreateDomainOptions{ SpamAction: mtypes.SpamActionTag, WebScheme: "https", MessageTTL: 86400, // 1 day } resp, err := mg.CreateDomain(ctx, "mail.example.com", opts) ``` -------------------------------- ### Create Mailgun Client from Environment Variables Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/client.md Create a Mailgun client by reading configuration from environment variables (MG_API_KEY, MG_URL, MG_WEBHOOK_SIGNING_KEY). An error is returned if MG_API_KEY is not set. ```go // Set environment variables: // MG_API_KEY=your-api-key // MG_URL=https://api.eu.mailgun.net (optional, defaults to US) // MG_WEBHOOK_SIGNING_KEY=your-webhook-key (optional) mg, err := mailgun.NewMailgunFromEnv() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Unsubscribe Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/bounces-complaints.md Retrieves unsubscribe information for a specific address. ```APIDOC ## GetUnsubscribe ### Description Retrieves unsubscribe information for a specific address. ### Method GET (Implied) ### Endpoint `/domains/{domain}/unsubscribes/{address}` (Implied) ### Parameters #### Path Parameters - **domain** (string) - Required - The domain name. - **address** (string) - Required - The email address to retrieve unsubscribe information for. ### Response #### Success Response (200) - **Unsubscribe** (mtypes.Unsubscribe) - Information about the specified unsubscribe record. - **error** (error) - An error if the retrieval fails. ``` -------------------------------- ### Initialize Mailgun Client from Environment Variables Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Use this when you want to configure the Mailgun client using environment variables. Ensure MG_API_KEY is set. ```bash export MG_API_KEY="key-abc123..." export MG_URL="https://api.eu.mailgun.net" # For EU region export MG_WEBHOOK_SIGNING_KEY="pubkey-xyz..." ``` ```go mg, err := mailgun.NewMailgunFromEnv() ``` -------------------------------- ### GetExportLink Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Gets the download link for a specific data export by its ID. ```APIDOC ## GetExportLink ### Description Gets download link for an export. ### Method GET ### Endpoint /v3/YOUR_DOMAIN/exports/{id}/download ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the export. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **string** - The download URL for the export. #### Response Example None ``` -------------------------------- ### Get API Key Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/client.md Retrieves the configured API key for the Mailgun client. ```go key := mg.APIKey() ``` -------------------------------- ### Get API Base URL Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/client.md Retrieves the configured API base URL for the Mailgun client. ```go base := mg.APIBase() // "https://api.mailgun.net" ``` -------------------------------- ### Get Export by ID Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Retrieves a specific data export by its ID. Requires a context and the export ID. ```go func (mg *Client) GetExport(ctx context.Context, id string) (mtypes.Export, error) ``` -------------------------------- ### Configure HTTP Client with Proxy Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Set up an HTTP client to use a proxy server. This is useful for network environments that require a proxy. ```go // With proxy proxyURL, _ := url.Parse("http://proxy.example.com:8080") transport := &http.Transport{ Proxy: http.ProxyURL(proxyURL), } client = &http.Client{ Transport: transport, Timeout: 30 * time.Second, } mg.SetHTTPClient(client) ``` -------------------------------- ### List Domains with Custom Page Size Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Demonstrates how to list domains using custom pagination settings. Use this when you need to control the number of items returned per request. ```go // List domains with custom page size it := mg.ListDomains(&mailgun.ListDomainsOptions{Limit: 25}) ``` ```go // List with default page size it := mg.ListBounces("mg.example.com", nil) ``` -------------------------------- ### List IP Warmups Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Use this method to create an iterator for paginating through IP addresses currently in warmup. ```go it := mg.ListIPWarmups() ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() var warmups []mtypes.IPWarmupDetails for it.Next(ctx, &warmups) { for _, warmup := range warmups { fmt.Printf("IP: %s (Warmup: %d%%)\n", warmup.IP, warmup.WarmupPercentage) } } ``` -------------------------------- ### Get HTTP Client Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/client.md Retrieves the HTTP client instance used by the Mailgun client for making API requests. ```go client := mg.HTTPClient() ``` -------------------------------- ### Get Stored Attachment Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Retrieves an attachment from a stored message using its storage URL. Requires a context and the URL. ```go func (mg *Client) GetStoredAttachment(ctx context.Context, url string) ([]byte, error) ``` -------------------------------- ### Client Initialization and Configuration Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/COMPLETION_SUMMARY.txt Details on how to initialize the Mailgun client, configure API base URLs (US/EU/custom), customize the HTTP client, manage webhook signing keys, and enable debug mode. ```APIDOC ## Client Initialization and Configuration ### Description Provides methods for initializing the Mailgun client, setting API base URLs for different regions (US, EU, custom), customizing the underlying HTTP client, managing webhook signing keys, and enabling debug mode for the SDK. ### API Surface - Client initialization - Configuration methods - API base URL selection (US/EU/custom) - HTTP client customization - Webhook signing key management - Subaccount support - Debug mode ``` -------------------------------- ### Get Stored Message Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Retrieves a message stored in Mailgun using its storage URL. Requires a context and the URL. ```go func (mg *Client) GetStoredMessage(ctx context.Context, url string) (mtypes.StoredMessage, error) ``` -------------------------------- ### List API Keys Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Lists all API keys in your account. Use this to retrieve a collection of existing API keys. ```go keys, err := mg.ListAPIKeys(ctx, nil) if err != nil { log.Fatal(err) } for _, key := range keys { fmt.Printf("Key: %s...%s (Role: %s)\n", key.Begin, key.End, key.Role) } ``` -------------------------------- ### Get Specific Mailgun Route Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Retrieves a specific route by its ID. Ensure you have the correct route ID before calling this method. ```go route, err := mg.GetRoute(ctx, "route-id-123") if err != nil { log.Fatal(err) } fmt.Printf("Route: %s\n", route.Description) ``` -------------------------------- ### List All IPs Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Lists IP addresses in your account, with options to filter by dedicated and enabled status. Requires context for timeouts. ```go // List all dedicated, enabled IPs ips, err := mg.ListIPs(ctx, true, true) if err != nil { log.Fatal(err) } for _, ip := range ips { fmt.Printf("IP: %s (Dedicated: %v, Enabled: %v)\n", ip.IP, ip.Dedicated, ip.Enabled) } ``` -------------------------------- ### Get IP Warmup Status Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Retrieves the warmup status for a specific IP address. Ensure you provide a valid context and IP. ```go warmup, err := mg.GetIPWarmup(ctx, "192.0.2.1") if err != nil { log.Fatal(err) } fmt.Printf("IP: %s\n", warmup.IP) fmt.Printf("Warmup percentage: %d%%\n", warmup.WarmupPercentage) ``` -------------------------------- ### GetDomainOptions Struct Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Options for retrieving domain details, including an option to verify the domain. ```go type GetDomainOptions struct { Verify bool // Whether to verify domain } ``` -------------------------------- ### Get Domain Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Retrieves details for a specific domain, including its DNS records for receiving and sending. Optionally verifies the domain during retrieval. ```APIDOC ## GET /domains/{name} ### Description Retrieves details for a specific domain, including its DNS records for receiving and sending. Optionally verifies the domain during retrieval. ### Method GET ### Endpoint /domains/{name} ### Parameters #### Path Parameters - **name** (string) - Required - The name of the domain #### Query Parameters - **Verify** (bool) - Optional - Whether to verify domain ``` -------------------------------- ### Create Mailgun Client with API Key Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/client.md Instantiate a new Mailgun client using your API key. This uses the default API base URL. ```go mg := mailgun.NewMailgun("MAILGUN_API_KEY") ``` -------------------------------- ### Get Bounce Information Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/bounces-complaints.md Retrieves bounce details for a specific email address within a domain. Requires a context for potential timeouts. ```go bounce, err := mg.GetBounce(ctx, "mg.example.com", "user@example.com") if err != nil { log.Fatal(err) } fmt.Printf("Address: %s\n", bounce.Address) fmt.Printf("Code: %s\n", bounce.Code) fmt.Printf("Error: %s\n", bounce.Error) ``` -------------------------------- ### Get Stored Message Raw Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Retrieves the raw MIME content of a stored message using its ID. Requires a context and the message ID. ```go func (mg *Client) GetStoredMessageRaw(ctx context.Context, id string) (mtypes.StoredMessageRaw, error) ``` -------------------------------- ### CreateDomainOptions Struct Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Configuration options for creating a new Mailgun domain. ```go type CreateDomainOptions struct { IsSensitivePhishingDomain bool // Mark as sensitive phishing domain Wildcard bool // Create wildcard domain SMTPPassword string // SMTP password SpamAction SpamAction // Spam handling action WebScheme string // Web scheme (http or https) SkipVerification bool // Skip domain verification MessageTTL int // Message TTL in seconds } ``` -------------------------------- ### List Domains with Pagination Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Use this to iterate through your domains with specified paging and filtering options. Ensure context is managed for timeouts. ```go it := mg.ListDomains(&mailgun.ListDomainsOptions{Limit: 25}) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) def cancel() var domains []mtypes.Domain for it.Next(ctx, &domains) { for _, domain := range domains { fmt.Printf("Domain: %s (State: %s)\n", domain.Name, domain.State) } } if err := it.Err(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Define Domain List Options Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Defines specific options for listing domains, allowing filtering by state, sorting, searching, and including subaccounts. Use these to refine domain queries. ```go type ListDomainsOptions struct { Limit int State *mtypes.DomainState // Filter by state Sort *string // Sort order Authority *string // Filter by authority Search *string // Search by name IncludeSubaccounts *bool // Include subaccounts } ``` -------------------------------- ### Create a New Mailing List Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/mailing-lists.md Creates a new mailing list. Ensure the `Address` field in the `mtypes.MailingList` struct is set. ```go newList := mtypes.MailingList{ Address: "newsletter@example.com", Name: "Newsletter", Description: "Company newsletter", } created, err := mg.CreateMailingList(ctx, newList) if err != nil { log.Fatal(err) } fmt.Printf("Created list: %s\n", created.Address) ``` -------------------------------- ### Get Unsubscribe Information Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/bounces-complaints.md Retrieves unsubscribe information for a specific email address within a domain. Requires context, domain, and the email address. ```go func (mg *Client) GetUnsubscribe(ctx context.Context, domain, address string) (mtypes.Unsubscribe, error) ``` -------------------------------- ### Get Specific Complaint Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/bounces-complaints.md Retrieve complaint information for a single email address within a specified domain. Requires a context for potential timeouts. ```go complaint, err := mg.GetComplaint(ctx, "mg.example.com", "complainer@example.com") if err != nil { log.Fatal(err) } fmt.Printf("Complaint recorded at: %v\n", complaint.CreatedAt) ``` -------------------------------- ### Configure Webhook Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/COMPLETION_SUMMARY.txt Sets up a webhook to receive event notifications from Mailgun. Specify the event types to subscribe to. ```go // CreateWebhook() - Webhook setup ``` -------------------------------- ### Create API Key Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Creates a new API key with a specified role. Ensure you securely store the returned key material. ```go key, err := mg.CreateAPIKey(ctx, "send", nil) if err != nil { log.Fatal(err) } fmt.Printf("New API key created (store this securely): %v\n", key) ``` -------------------------------- ### Send an Email using Mailgun Go SDK Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/README.md This Go code snippet demonstrates how to create a Mailgun client, construct a new email message with plain text and HTML content, and send it using the SDK. It includes setting a timeout for the request. ```Go package main import ( "context" "fmt" "log" "time" "github.com/mailgun/mailgun-go/v5" ) func main() { // Create client mg := mailgun.NewMailgun("your-mailgun-api-key") // Create message message := mailgun.NewMessage( "mg.example.com", "sender@example.com", "Subject", "Plain text body", "recipient@example.com", ) message.SetHTML("HTML body") // Send with timeout ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() response, err := mg.Send(ctx, message) if err != nil { log.Fatal(err) } fmt.Printf("Message sent: %s\n", response.ID) } ``` -------------------------------- ### Set Click Tracking Mode Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/messages.md Configure the click tracking mode for the message. Accepted options are "yes", "no", or "htmlonly". An error is returned for invalid options. ```go msg.SetTrackingClicks("htmlonly") ``` -------------------------------- ### Send Message with Attachments Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/README.md Attach files to your email. Provide the local file path to the attachment. ```go message := mailgun.NewMessage("mg.example.com", "sender@example.com", "Subject", "Body", "recipient@example.com") message.AddAttachment("/path/to/file.pdf") resp, err := mg.Send(ctx, message) ``` -------------------------------- ### Send Email Using Templates in Go Source: https://github.com/mailgun/mailgun-go/blob/main/README.md Demonstrates how to send an email using a pre-defined Mailgun template. Ensure your domain and API key are correctly configured. The template variables are added as a JSON stringified X-Mailgun-Variables header. ```go package main import ( "context" "fmt" "log" "time" "github.com/mailgun/mailgun-go/v5" ) // Your available domain names can be found here: // (https://app.mailgun.com/app/domains) var yourDomain = "your-domain-name" // e.g. mg.yourcompany.com // You can find Mailgun API keys in your Account Menu, under "API Security": // (https://app.mailgun.com/settings/api_security) var apiKey = "MAILGUN_API_KEY" func main() { // Create an instance of the Mailgun Client mg := mailgun.NewMailgun(apiKey) sender := "sender@example.com" subject := "Fancy subject!" body := "" recipient := "recipient@example.com" // The message object allows you to add attachments and Bcc recipients message := mailgun.NewMessage(yourDomain, sender, subject, body, recipient) message.SetTemplate("passwordReset") err := message.AddTemplateVariable("passwordResetLink", "some link to your site unique to your user") if err != nil { log.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) defer cancel() // Send the message with a 10-second timeout resp, err := mg.Send(ctx, message) if err != nil { log.Fatal(err) } fmt.Printf("ID: %s Resp: %s\n", resp.ID, resp.Message) } ``` -------------------------------- ### Get Mailing List Information Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/mailing-lists.md Retrieves details for a specific mailing list using its email address. Useful for checking list properties or member counts. ```go list, err := mg.GetMailingList(ctx, "newsletter@example.com") if err != nil { log.Fatal(err) } fmt.Printf("List: %s\n", list.Name) fmt.Printf("Members: %d\n", list.MembersCount) ``` -------------------------------- ### Update Domain with Options Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Updates an existing domain with new settings such as web scheme, skip verification, and message TTL. Use this to modify domain configurations. ```go err := mg.UpdateDomain(ctx, "mail.example.com", &mailgun.UpdateDomainOptions{ WebScheme: "https", MessageTTL: 86400, }) ``` -------------------------------- ### Get Mailing List Member Information Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/mailing-lists.md Retrieves specific information about a single mailing list member. Use this to check a member's subscription status or other details. ```go member, err := mg.GetMember(ctx, "user@example.com", "newsletter@example.com") if err != nil { log.Fatal(err) } fmt.Printf("Subscribed: %v\n", *member.Subscribed) ``` -------------------------------- ### NewMailgunFromEnv Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/client.md Creates a new Mailgun client using environment variables. ```APIDOC ## NewMailgunFromEnv ### Description Creates a new Mailgun client using environment variables. Supports `MG_API_KEY`, `MG_URL`, and `MG_WEBHOOK_SIGNING_KEY`. ### Signature ```go func NewMailgunFromEnv() (*Client, error) ``` ### Returns - `*Client` or error if `MG_API_KEY` is not defined ### Throws - `errors.New` if required `MG_API_KEY` environment variable is missing ### Example ```go // Set environment variables: // MG_API_KEY=your-api-key // MG_URL=https://api.eu.mailgun.net (optional, defaults to US) // MG_WEBHOOK_SIGNING_KEY=your-webhook-key (optional) mg, err := mailgun.NewMailgunFromEnv() if err != nil { log.Fatal(err) } ``` ``` -------------------------------- ### Retrieve Specific Webhook URLs Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/webhooks.md Fetches the list of URLs configured for a particular type of webhook event on a domain. Use this to get the endpoints for a single event notification. ```go urls, err := mg.GetWebhook(ctx, "mg.example.com", "delivered") if err != nil { log.Fatal(err) } for _, url := range urls { fmt.Printf("Webhook URL: %s\n", url) } ``` -------------------------------- ### Client Creation Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/COMPLETION_SUMMARY.txt Creates a new Mailgun client instance. This is the primary entry point for interacting with the Mailgun API. ```go // NewMailgun() - Client creation ``` -------------------------------- ### Create a new Mailgun template Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/templates.md Use this method to create a new email template. Provide the domain and a Template object with the desired name and description. ```go newTemplate := &mtypes.Template{ Name: "passwordReset", Description: "Password reset email", } err := mg.CreateTemplate(ctx, "mg.example.com", newTemplate) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Specific Tag Statistics Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Retrieves statistics for a particular tag within a domain. Requires a context, domain name, and tag name. The result includes tag statistics. ```go tag, err := mg.GetTag(ctx, "mg.example.com", "promotional") if err != nil { log.Fatal(err) } fmt.Printf("Tag: %s\n", tag.Name) ``` -------------------------------- ### Create a New Webhook Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/webhooks.md Configures a new webhook endpoint for a specified event kind on a domain. Supports setting one or multiple URLs for the webhook. ```go err := mg.CreateWebhook(ctx, "mg.example.com", "delivered", []string{"https://webhook.example.com/delivered"}) if err != nil { log.Fatal(err) } // Multiple URLs for failover err = mg.CreateWebhook(ctx, "mg.example.com", "failed", []string{ "https://primary.example.com/failed", "https://backup.example.com/failed", }) ``` -------------------------------- ### List Domains by IP Address Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Lists all domains assigned to a specific IP address. Use the IP address and optional paging options to retrieve the domains. ```go func (mg *Client) ListIPDomains(ip string, opts *ListIPDomainOptions) *IPDomainsIterator ``` -------------------------------- ### Get Template Version Go Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/templates.md Retrieve a specific version of a Mailgun template by providing the domain, template name, and version tag. This is useful for inspecting or comparing different template versions. ```go version, err := mg.GetTemplateVersion(ctx, "mg.example.com", "passwordReset", "v1") if err != nil { log.Fatal(err) } fmt.Printf("Version: %s\n", version.Tag) fmt.Printf("Active: %v\n", version.Active) ``` -------------------------------- ### VerifyAndReturnDomain Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Deprecated: Use `VerifyDomain` instead. Same functionality. ```APIDOC ## VerifyAndReturnDomain ### Description Deprecated: Use `VerifyDomain` instead. Same functionality. ### Method `VerifyAndReturnDomain` ### Parameters #### Path Parameters - **domain** (string) - Required - Domain name to verify #### Query Parameters - None #### Request Body - None ### Returns - `mtypes.GetDomainResponse`: Updated domain status. ### Throws - `UnexpectedResponseError`: If DNS records are not properly configured. ### Example ```go // First create and configure DNS records resp, err := mg.VerifyAndReturnDomain(ctx, "mail.mycompany.com") if err != nil { log.Fatal(err) } if resp.Domain.State == "active" { fmt.Println("Domain successfully verified!") } else { fmt.Printf("Domain state: %s\n", resp.Domain.State) } ``` ``` -------------------------------- ### Send Simple Message Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/README.md Use this to send a basic email message. Ensure the Mailgun client is initialized. ```go message := mailgun.NewMessage("mg.example.com", "sender@example.com", "Subject", "Body", "recipient@example.com") resp, err := mg.Send(ctx, message) ``` -------------------------------- ### Create New Mailgun Route Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Creates a new route with specified configuration. Define priority, description, expression, and actions for the new route. ```go newRoute := mtypes.Route{ Priority: 10, Description: "Forward all mail to webhook", Expression: "match_all()", Actions: []string{"forward(\"https://example.com/webhook\")"}, } created, err := mg.CreateRoute(ctx, newRoute) if err != nil { log.Fatal(err) } fmt.Printf("Route created with ID: %s\n", created.ID) ``` -------------------------------- ### Getting HTTP Status Code from Error in Go Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/errors.md Retrieve the HTTP status code from a Mailgun error using the `GetStatusFromErr` helper function. This is useful for conditional logic based on the response status. ```go func GetHTTPStatus(err error) int { return mailgun.GetStatusFromErr(err) } resp, err := mg.Send(ctx, msg) if err != nil { status := GetHTTPStatus(err) if status == 401 { fmt.Println("Invalid API key") } } ``` -------------------------------- ### Set Server-Side Template Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/messages.md Configures the message to use a server-side template for rendering. Provide the name of the template to be used. ```go msg.SetTemplate("passwordReset") ``` -------------------------------- ### Common Event Interface Methods Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/events.md Details the common methods available for all event types that implement the `events.Event` interface. ```go func (e Event) GetID() string // Unique event ID func (e Event) GetName() string // Event type name func (e Event) GetTimestamp() time.Time // Event timestamp func (e Event) GetRecipient() string // Recipient email ``` -------------------------------- ### ListDomainsOptions Struct Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Options for filtering and sorting domain listings. ```go type ListDomainsOptions struct { Limit int // Number of items per page (default: 100) State *DomainState // Filter by domain state Sort *string // Sort order (optional) Authority *string // Filter by authority (optional) Search *string // Search by domain name (optional) IncludeSubaccounts *bool // Include subaccount domains (optional) } ``` -------------------------------- ### Create New SMTP Credentials Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/credentials-ips-routes.md Creates new SMTP credentials for a given domain. Ensure you provide a context for timeouts and valid domain, login, and password. ```go err := mg.CreateCredential(ctx, "mg.example.com", "postmaster@mg.example.com", "secure_password_123") if err != nil { log.Fatal(err) } ``` -------------------------------- ### Enable Test Mode Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/messages.md Enable test mode for the message, which prevents actual delivery. Pass `true` to enable. ```go msg.SetTestMode(true) ``` -------------------------------- ### GetDomainResponse Struct Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/domains.md Contains detailed information about a domain, including its configuration and associated DNS records. ```go type GetDomainResponse struct { Domain Domain // Domain information ReceivingDNSRecords []DNSRecord // DNS records for receiving SendingDNSRecords []DNSRecord // DNS records for sending UseAutomaticSenderSecurity bool // Whether to use automatic sender security } ``` -------------------------------- ### Paginate List of Domains Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/README.md Iterate through a list of domains, handling pagination automatically. Ensure context is managed with timeouts. ```go it := mg.ListDomains(nil) ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) def cancel() var domains []mtypes.Domain for it.Next(ctx, &domains) { for _, domain := range domains { fmt.Printf("Domain: %s\n", domain.Name) } } if err := it.Err(); err != nil { log.Fatal(err) } ``` -------------------------------- ### Create a New Subaccount Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Create a new subaccount by providing a unique name. The response includes the newly created subaccount's details, such as its ID and name. ```go func (mg *Client) CreateSubaccount(ctx context.Context, subaccountName string) (mtypes.SubaccountResponse, error) ``` ```go sub, err := mg.CreateSubaccount(ctx, "customer-123") if err != nil { log.Fatal(err) } fmt.Printf("Created subaccount: %s (ID: %s)\n", sub.Name, sub.ID) ``` -------------------------------- ### Define Event List Options Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/configuration.md Defines options for listing events, including time ranges, sorting, filtering, and polling intervals. Use this to retrieve specific event data. ```go type ListEventOptions struct { Begin time.Time End time.Time ForceAscending bool ForceDescending bool Compact bool Limit int Filter map[string]string PollInterval time.Duration // For polling } ``` -------------------------------- ### Sending a Message with a Template Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/templates.md Demonstrates how to set a template name and add global variables for email personalization. ```APIDOC ## Sending a Message with a Template This example shows how to configure a message to use a specific template and provide variables that will be substituted into the template. ### Method This is demonstrated using the `Send` method of the Mailgun Go SDK, which implicitly handles template rendering when a template is set. ### Usage 1. Create a new message using `mailgun.NewMessage`. 2. Set the template name using `msg.SetTemplate("templateName")`. 3. Add global template variables using `msg.AddTemplateVariable(key, value)`. 4. Send the message using `mg.Send(ctx, msg)`. ### Code Example ```go msg := mailgun.NewMessage( "mg.example.com", "sender@example.com", "Password Reset", "", "recipient@example.com", ) // Set the template name msg.SetTemplate("passwordReset") // Add template variables for substitution msg.AddTemplateVariable("firstName", "John") msg.AddTemplateVariable("resetLink", "https://example.com/reset/abc123") ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() resp, err := mg.Send(ctx, msg) if err != nil { log.Fatal(err) } fmt.Printf("Message ID: %s\n", resp.ID) ``` ``` -------------------------------- ### Create DKIM Key for a Domain Source: https://github.com/mailgun/mailgun-go/blob/main/_autodocs/api-reference/additional-apis.md Use this method to generate a new DKIM key for a specified domain. It requires a context, domain name, and a DKIM selector. Optional settings can be provided. The response includes the public and private keys. ```go func (mg *Client) CreateDomainKey(ctx context.Context, domain, dkimSelector string, opts *CreateDomainKeyOptions) (mtypes.DomainKey, error) ``` ```go key, err := mg.CreateDomainKey(ctx, "mg.example.com", "default") if err != nil { log.Fatal(err) } fmt.Printf("Public key:\n%s\n", key.PublicKey) // Add to your DNS: default._domainkey.mg.example.com IN TXT "