### Install Mailjet Go Package Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Use the go get command to add the Mailjet library to your project. ```bash go get github.com/mailjet/mailjet-apiv3-go/v4 ``` -------------------------------- ### List Resources with Filters and Sorting Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Retrieve resources from the Mailjet API with applied filters and sorting. This example demonstrates how to filter contacts by exclusion status and creation date, and campaigns by star status. Use `mailjet.Filter` for filtering and `mailjet.Sort` for ordering. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // List contacts with filters var contacts []resources.Contact count, total, err := mj.List("contact", &contacts, mailjet.Filter("IsExcludedFromCampaigns", "false"), mailjet.Filter("Limit", "50"), mailjet.Filter("Offset", "0"), mailjet.Sort("CreatedAt", mailjet.SortDesc), ) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Active contacts: %d/%d\n", count, total) for _, contact := range contacts { fmt.Printf("Contact: %s, Created: %v\n", contact.Email, contact.CreatedAt) } // List campaigns with status filter var campaigns []resources.Campaign count, total, err = mj.List("campaign", &campaigns, mailjet.Filter("FromTS", "1609459200"), // Unix timestamp mailjet.Filter("IsStarred", "true"), ) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("\nStarred campaigns: %d\n", count) } ``` -------------------------------- ### Get DNS Configuration and Trigger Checks with Mailjet Go Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Retrieves DNS configuration for a domain and triggers DNS checks or sender validation. Ensure API keys are set as environment variables. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Get DNS configuration for a domain var dns []resources.Dns mr := &mailjet.Request{ Resource: "dns", AltID: "example.com", } err := mj.Get(mr, &dns) if err != nil { fmt.Println("Error:", err) return } if len(dns) > 0 { d := dns[0] fmt.Println("DNS Configuration for", d.Domain) fmt.Println("\nDKIM Setup:") fmt.Printf(" Record Name: %s\n", d.DKIMRecordName) fmt.Printf(" Record Value: %s\n", d.DKIMRecordValue) fmt.Printf(" Status: %s\n", d.DKIMStatus) fmt.Println("\nSPF Setup:") fmt.Printf(" Record Value: %s\n", d.SPFRecordValue) fmt.Printf(" Status: %s\n", d.SPFStatus) fmt.Println("\nOwnership Token:") fmt.Printf(" Token: %s\n", d.OwnerShipToken) fmt.Printf(" Record Name: %s\n", d.OwnerShipTokenRecordName) } // Trigger DNS check for a sender var checkResult []resources.DnsCheck mr = &mailjet.Request{ Resource: "dns", ID: 12345, // DNS ID Action: "check", } err = mj.Get(mr, &checkResult) if err != nil { fmt.Println("Error checking DNS:", err) return } // Validate a sender var validateResult []resources.SenderValidate mr = &mailjet.Request{ Resource: "sender", ID: 67890, // Sender ID Action: "validate", } fmr := &mailjet.FullRequest{Info: mr} err = mj.Post(fmr, &validateResult) if err != nil { fmt.Println("Error validating sender:", err) return } fmt.Println("\nSender validation initiated!") // Output: // DNS Configuration for example.com // DKIM Setup: // Record Name: mailjet._domainkey.example.com // Status: OK // SPF Setup: // Status: OK } ``` -------------------------------- ### Initialize Mailjet Client Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Create a new Mailjet client instance using credentials retrieved from environment variables. ```go // Get your environment Mailjet keys and connect publicKey := os.Getenv("MJ_APIKEY_PUBLIC") secretKey := os.Getenv("MJ_APIKEY_PRIVATE") mj := mailjet.NewMailjetClient(publicKey, secretKey) ``` -------------------------------- ### Initialize Mailjet Client Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Create a new client instance using public and secret API keys. Optionally specify a custom base URL for US-based accounts. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" ) func main() { // Standard client initialization publicKey := os.Getenv("MJ_APIKEY_PUBLIC") secretKey := os.Getenv("MJ_APIKEY_PRIVATE") mj := mailjet.NewMailjetClient(publicKey, secretKey) // For US-based accounts, specify the US API endpoint mjUS := mailjet.NewMailjetClient(publicKey, secretKey, "https://api.us.mailjet.com") fmt.Printf("Client initialized with public key: %s\n", mj.APIKeyPublic()) // Output: Client initialized with public key: your_public_key } ``` -------------------------------- ### Import Mailjet Wrapper Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Include the necessary packages in your Go source files. ```go import ( "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) ``` -------------------------------- ### Run Functional Tests Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Execute the provided test program to verify your API keys are active. ```bash go run main.go ``` -------------------------------- ### Create Resources with Mailjet Go SDK Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Creates new entities like contacts, contact lists, and senders by providing a payload to the Post method. Ensure the FullRequest struct is correctly initialized with the resource type and data. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Create a new contact var contacts []resources.Contact fmr := &mailjet.FullRequest{ Info: &mailjet.Request{Resource: "contact"}, Payload: &resources.Contact{ Email: "newuser@example.com", Name: "New User", IsExcludedFromCampaigns: false, }, } err := mj.Post(fmr, &contacts) if err != nil { fmt.Println("Error creating contact:", err) return } fmt.Printf("Created contact ID: %d\n", contacts[0].ID) // Create a new contact list var lists []resources.Contactslist fmr = &mailjet.FullRequest{ Info: &mailjet.Request{Resource: "contactslist"}, Payload: &resources.Contactslist{ Name: "Newsletter Subscribers", }, } err = mj.Post(fmr, &lists) if err != nil { fmt.Println("Error creating list:", err) return } fmt.Printf("Created list ID: %d, Address: %s\n", lists[0].ID, lists[0].Address) // Create a new sender var senders []resources.Sender fmr = &mailjet.FullRequest{ Info: &mailjet.Request{Resource: "sender"}, Payload: &resources.Sender{ Email: "newsender@example.com", Name: "Marketing Team", }, } err = mj.Post(fmr, &senders) if err != nil { fmt.Println("Error creating sender:", err) return } fmt.Printf("Created sender ID: %d, Status: %s\n", senders[0].ID, senders[0].Status) // Output: // Created contact ID: 123456789 // Created list ID: 987654 // Created sender ID: 456789 } ``` -------------------------------- ### Request Context Support with Mailjet Go Client Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Enhances API requests with `context.Context` for managing timeouts and cancellations. This is crucial for production environments to control request lifecycles. Use `context.WithTimeout` and `defer cancel()` for proper resource management. ```go package main import ( "context" "fmt" "os" "time" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Create a context with timeout ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // List contacts with context var contacts []resources.Contact count, total, err := mj.List("contact", &contacts, mailjet.WithContext(ctx), mailjet.Filter("Limit", "10"), ) if err != nil { if ctx.Err() == context.DeadlineExceeded { fmt.Println("Request timed out!") } else { fmt.Println("Error:", err) } return } fmt.Printf("Retrieved %d/%d contacts\n", count, total) // Send email with context ctx2, cancel2 := context.WithTimeout(context.Background(), 30*time.Second) defer cancel2() messagesInfo := []mailjet.InfoMessagesV31{ { From: &mailjet.RecipientV31{ Email: "sender@example.com", Name: "Sender", }, To: &mailjet.RecipientsV31{ mailjet.RecipientV31{Email: "recipient@example.com"}, }, Subject: "Test with Context", TextPart: "This email was sent with context timeout support.", }, } messages := mailjet.MessagesV31{Info: messagesInfo} res, err := mj.SendMailV31(&messages, mailjet.WithContext(ctx2)) if err != nil { fmt.Println("Error sending email:", err) return } fmt.Printf("Email sent with status: %s\n", res.ResultsV31[0].Status) } ``` -------------------------------- ### Delete Resources using Mailjet Go Client Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Demonstrates how to delete various resources such as templates, senders, and contact lists from the Mailjet system using the `Delete` method. Ensure the correct resource type and identifier (ID or AltID) are provided. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Delete a template by ID mr := &mailjet.Request{ Resource: "template", ID: 12345, } err := mj.Delete(mr) if err != nil { fmt.Println("Error deleting template:", err) return } fmt.Println("Template deleted successfully!") // Delete a sender by email mr = &mailjet.Request{ Resource: "sender", AltID: "old-sender@example.com", } err = mj.Delete(mr) if err != nil { fmt.Println("Error deleting sender:", err) return } fmt.Println("Sender deleted successfully!") // Delete a contact list mr = &mailjet.Request{ Resource: "contactslist", ID: 999999, } err = mj.Delete(mr) if err != nil { fmt.Println("Error deleting contact list:", err) return } fmt.Println("Contact list deleted successfully!") } ``` -------------------------------- ### Manage Webhook Event Callbacks with Go Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Configures and lists webhook URLs for receiving real-time email event notifications (open, click, bounce) using the Mailjet Go SDK. Ensure API keys are set as environment variables. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Create webhook for open events var callbacks []resources.Eventcallbackurl fmr := &mailjet.FullRequest{ Info: &mailjet.Request{Resource: "eventcallbackurl"}, Payload: &resources.Eventcallbackurl{ EventType: "open", URL: "https://your-server.com/webhooks/mailjet/open", Status: "alive", Version: 2, // API version for callback payload }, } err := mj.Post(fmr, &callbacks) if err != nil { fmt.Println("Error creating webhook:", err) return } fmt.Printf("Created open webhook ID: %d\n", callbacks[0].ID) // Create webhook for click events fmr = &mailjet.FullRequest{ Info: &mailjet.Request{Resource: "eventcallbackurl"}, Payload: &resources.Eventcallbackurl{ EventType: "click", URL: "https://your-server.com/webhooks/mailjet/click", Status: "alive", Version: 2, }, } err = mj.Post(fmr, &callbacks) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Created click webhook ID: %d\n", callbacks[0].ID) // Create webhook for bounce events fmr = &mailjet.FullRequest{ Info: &mailjet.Request{Resource: "eventcallbackurl"}, Payload: &resources.Eventcallbackurl{ EventType: "bounce", URL: "https://your-server.com/webhooks/mailjet/bounce", Status: "alive", Version: 2, }, } err = mj.Post(fmr, &callbacks) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Created bounce webhook ID: %d\n", callbacks[0].ID) // List all webhooks var allCallbacks []resources.Eventcallbackurl _, _, err = mj.List("eventcallbackurl", &allCallbacks) if err != nil { fmt.Println("Error:", err) return } fmt.Println("\nRegistered Webhooks:") for _, cb := range allCallbacks { fmt.Printf(" ID: %d, Event: %s, URL: %s, Status: %s\n", cb.ID, cb.EventType, cb.URL, cb.Status) } // Output: // Created open webhook ID: 111 // Created click webhook ID: 222 // Created bounce webhook ID: 333 } ``` -------------------------------- ### Configure Custom Base URL Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Override the default API base URL, which is required for accounts on the US architecture. ```go mailjetClient := NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE"), "https://api.us.mailjet.com") ``` -------------------------------- ### Set Authentication Environment Variables Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Export your Mailjet API credentials as environment variables for the client to access. ```bash export MJ_APIKEY_PUBLIC='your API key' export MJ_APIKEY_PRIVATE='your API secret' ``` -------------------------------- ### Create Contact Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Create a new contact in Mailjet. Requires MJ_APIKEY_PUBLIC and MJ_APIKEY_PRIVATE environment variables. ```go // Create a new contact. package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mailjetClient := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) var data []resources.Contact mr := &mailjet.Request{ Resource: "contact", } fmr := &mailjet.FullRequest{ Info: mr, Payload: &resources.Contact{ Email: "passenger@mailjet.com", IsExcludedFromCampaigns: true, Name: "New Contact", }, } err := mailjetClient.Post(fmr, &data) if err != nil { fmt.Println(err) } fmt.Printf("Data array: %+v\n", data) } ``` -------------------------------- ### Retrieve Single Resource with Mailjet Go SDK Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Fetches specific resources such as contacts or senders using ID or AltID. Requires a configured Mailjet client and appropriate resource structs. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Get contact by ID var contacts []resources.Contact mr := &mailjet.Request{ Resource: "contact", ID: 123456789, // Contact ID } err := mj.Get(mr, &contacts) if err != nil { fmt.Println("Error:", err) return } if len(contacts) > 0 { contact := contacts[0] fmt.Printf("Contact: %s\n", contact.Email) fmt.Printf("Name: %s\n", contact.Name) fmt.Printf("Created: %v\n", contact.CreatedAt) fmt.Printf("Delivered Count: %d\n", contact.DeliveredCount) } // Get sender by email (using AltID) var senders []resources.Sender mr = &mailjet.Request{ Resource: "sender", AltID: "sender@example.com", } err = mj.Get(mr, &senders) if err != nil { fmt.Println("Error:", err) return } if len(senders) > 0 { sender := senders[0] fmt.Printf("\nSender: %s (%s)\n", sender.Name, sender.Email) fmt.Printf("Status: %s\n", sender.Status) } // Output: // Contact: user@example.com // Name: John Doe // Created: 2024-01-15 10:30:00 // Delivered Count: 42 } ``` -------------------------------- ### Manage Contact List Subscriptions with API Actions Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Use API actions to manage contact subscriptions to lists. Supports adding, removing, and updating contact list memberships. Ensure MJ_APIKEY_PUBLIC and MJ_APIKEY_PRIVATE environment variables are set. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Manage a contact's subscription to multiple lists var result []resources.ContactManagecontactslists mr := &mailjet.Request{ Resource: "contact", ID: 123456789, // Contact ID Action: "managecontactslists", } fmr := &mailjet.FullRequest{ Info: mr, Payload: &resources.ContactManagecontactslists{ ContactsLists: []resources.ContactsListAction{ { ListID: 111111, // Newsletter list Action: "addnoforce", // Add if not present }, { ListID: 222222, // Promotions list Action: "addforce", // Add or reactivate }, { ListID: 333333, // Old list Action: "remove", // Remove from list }, }, }, } err := mj.Post(fmr, &result) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Contact list memberships updated successfully!") // Add a contact to a list with properties var contactResult []resources.ContactslistManageContact mr = &mailjet.Request{ Resource: "contactslist", ID: 111111, // List ID Action: "managecontact", } fmr = &mailjet.FullRequest{ Info: mr, Payload: &resources.ContactslistManageContact{ Email: "subscriber@example.com", Name: "New Subscriber", Action: "addnoforce", Properties: map[string]interface{}{ "country": "USA", "interests": "technology", }, }, } err = mj.Post(fmr, &contactResult) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Contact added to list with properties!") } ``` -------------------------------- ### Custom HTTP Client with Proxy Support in Go Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Configures the Mailjet client to use a custom `http.Client` for advanced settings like proxy support and request timeouts. This is useful for network environments requiring specific HTTP configurations. ```go package main import ( "fmt" "log" "net/http" "net/url" "os" "time" "github.com/mailjet/mailjet-apiv3-go/v4" ) func main() { publicKey := os.Getenv("MJ_APIKEY_PUBLIC") secretKey := os.Getenv("MJ_APIKEY_PRIVATE") proxyURL := os.Getenv("HTTP_PROXY") mj := mailjet.NewMailjetClient(publicKey, secretKey) // Configure proxy proxyParsed, err := url.Parse(proxyURL) if err != nil { log.Fatal("Invalid proxy URL:", err) } // Create custom HTTP client with proxy and timeout settings customClient := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyURL(proxyParsed), MaxIdleConns: 100, MaxIdleConnsPerHost: 10, IdleConnTimeout: 90 * time.Second, }, Timeout: 30 * time.Second, } // Inject custom client mj.SetClient(customClient) // Send email through proxy messagesInfo := []mailjet.InfoMessagesV31{ { From: &mailjet.RecipientV31{ Email: "sender@example.com", Name: "Sender", }, To: &mailjet.RecipientsV31{ mailjet.RecipientV31{Email: "recipient@example.com"}, }, Subject: "Email via Proxy", TextPart: "This email was sent through a proxy server.", }, } messages := &mailjet.MessagesV31{Info: messagesInfo} res, err := mj.SendMailV31(messages) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("Email sent via proxy: %s\n", res.ResultsV31[0].Status) } ``` -------------------------------- ### Send Emails Through Proxy Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Configure an HTTP client with a proxy to send emails using the Mailjet API. Ensure the HTTP_PROXY environment variable is set. ```go package main import ( "fmt" "log" "net/http" "net/url" "os" "github.com/mailjet/mailjet-apiv3-go/v4" ) // Set the http client with the given proxy url func setupProxy(proxyURLStr string) *http.Client { proxyURL, err := url.Parse(proxyURLStr) if err != nil { log.Fatal(err) } tr := &http.Transport{Proxy: http.ProxyURL(proxyURL)} client := &http.Client{} client.Transport = tr return client } func main() { publicKey := os.Getenv("MJ_APIKEY_PUBLIC") secretKey := os.Getenv("MJ_APIKEY_PRIVATE") proxyURL := os.Getenv("HTTP_PROXY") mj := mailjet.NewMailjetClient(publicKey, secretKey) // Here we inject our http client configured with our proxy client := setupProxy(proxyURL) mj.SetClient(client) messagesInfo := []mailjet.InfoMessagesV31{ { From: &mailjet.RecipientV31{ Email: "qwe@qwe.com", Name: "Bob Patrick", }, To: &mailjet.RecipientsV31{ mailjet.RecipientV31{ Email: "qwe@qwe.com", }, }, Subject: "Hello World!", TextPart: "Hi there !", }, } messages := &mailjet.MessagesV31{Info: messagesInfo} res, err := mj.SendMailV31(messages) if err != nil { fmt.Println(err) } else { fmt.Println("Success") fmt.Println(res) } } ``` -------------------------------- ### Update Resources with PUT Request Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Updates existing resources with new values, similar to a PATCH request. Only specified fields are modified, preserving others. Ensure MJ_APIKEY_PUBLIC and MJ_APIKEY_PRIVATE environment variables are set. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Update contact properties mr := &mailjet.Request{ Resource: "contactdata", ID: 123456789, // Contact ID } fmr := &mailjet.FullRequest{ Info: mr, Payload: &resources.Contactdata{ Data: resources.KeyValueList{ {"Name": "firstname", "Value": "John"}, {"Name": "lastname", "Value": "Smith"}, {"Name": "country", "Value": "USA"}, {"Name": "age", "Value": "30"}, }, }, } err := mj.Put(fmr, nil) if err != nil { fmt.Println("Error updating contact data:", err) return } fmt.Println("Contact data updated successfully!") // Update sender information (only specified fields) mr = &mailjet.Request{ Resource: "sender", AltID: "sender@example.com", } fmr = &mailjet.FullRequest{ Info: mr, Payload: &resources.Sender{ Name: "Updated Sender Name", IsDefaultSender: true, }, } // Specify which fields to update err = mj.Put(fmr, []string{"Name", "IsDefaultSender"}) if err != nil { fmt.Println("Error updating sender:", err) return } fmt.Println("Sender updated successfully!") // Update contact list name mr = &mailjet.Request{ Resource: "contactslist", ID: 987654, } fmr = &mailjet.FullRequest{ Info: mr, Payload: &resources.Contactslist{ Name: "Premium Newsletter Subscribers", }, } err = mj.Put(fmr, []string{"Name"}) if err != nil { fmt.Println("Error updating list:", err) return } fmt.Println("Contact list updated successfully!") } ``` -------------------------------- ### Manage Contact Subscription to a List Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Manage a contact's subscription status to one or more lists. Replace placeholder IDs with actual values. Requires API keys. ```go // Create : Manage a contact subscription to a list package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mailjetClient := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) var data []resources.ContactManagecontactslists mr := &mailjet.Request{ Resource: "contact", ID: 423, // replace with your contact ID here Action: "managecontactslists", } fmr := &mailjet.FullRequest{ Info: mr, Payload: &resources.ContactManagecontactslists{ ContactsLists: []resources.ContactsListAction{ // replace with your contact lists here { ListID: 432, Action: "addnoforce", }, { ListID: 553, Action: "addforce", }, }, }, } err := mailjetClient.Post(fmr, &data) if err != nil { fmt.Println(err) } fmt.Printf("Data array: %+v\n", data) } ``` -------------------------------- ### Enable Debug Logging with Mailjet Go Client Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Enables debug logging for API requests and responses, with options for different verbosity levels and custom output destinations. Remember to disable debug mode when finished. ```go package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" "github.com/mailjet/mailjet-apiv3-go/v4/resources" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Enable debug mode (without body) mailjet.DebugLevel = mailjet.LevelDebug // For full debug with request/response body: // mailjet.DebugLevel = mailjet.LevelDebugFull // Set custom debug output destination mailjet.SetDebugOutput(os.Stdout) // Make an API call - debug info will be printed var contacts []resources.Contact count, _, err := mj.List("contact", &contacts, mailjet.Filter("Limit", "5")) if err != nil { fmt.Println("Error:", err) return } fmt.Printf("\nRetrieved %d contacts\n", count) // Disable debug mode when done mailjet.DebugLevel = mailjet.LevelNone // Debug output shows: // Method used is: GET // Final URL is: https://api.mailjet.com/v3/REST/contact?Limit=5 // Header is: map[Accept:[application/json] User-Agent:[mailjet-api-v3-go/4.0.1;go1.21]] // Status is: 200 OK // Output: // Retrieved 5 contacts } ``` -------------------------------- ### Send Emails via API v3.1 Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Send transactional emails using the Send API v3.1, supporting multiple recipients, attachments, and templates. ```go package main import ( "fmt" "log" "os" "github.com/mailjet/mailjet-apiv3-go/v4" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) messagesInfo := []mailjet.InfoMessagesV31{ { From: &mailjet.RecipientV31{ Email: "pilot@mailjet.com", Name: "Mailjet Pilot", }, To: &mailjet.RecipientsV31{ mailjet.RecipientV31{ Email: "passenger1@mailjet.com", Name: "Passenger 1", }, }, Cc: &mailjet.RecipientsV31{ mailjet.RecipientV31{ Email: "cc@mailjet.com", Name: "CC Recipient", }, }, Subject: "Your email flight plan!", TextPart: "Dear passenger 1, welcome to Mailjet!", HTMLPart: "
This is an HTML message.
", MjCampaign: "my-campaign", MjCustomID: "custom-id-123", MjDeduplicateCampaign: true, Headers: map[string]string{ "X-Custom-Header": "custom-value", }, } res, err := mj.SendMail(param) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Email sent successfully!") for _, sent := range res.Sent { fmt.Printf("Sent to: %s, MessageID: %d\n", sent.Email, sent.MessageID) } // Output: // Email sent successfully! // Sent to: recipient@example.com, MessageID: 576460752303423489 } ``` -------------------------------- ### Delete a resource with DELETE Source: https://github.com/mailjet/mailjet-apiv3-go/blob/master/README.md Removes a resource by its ID. Successful operations return a 204 No Content status code. ```go // Delete an email template: package main import ( "fmt" "os" "github.com/mailjet/mailjet-apiv3-go/v4" ) func main() { mailjetClient := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) mr := &mailjet.Request{ Resource: "template", ID: 423, // replace with your template ID here } err := mailjetClient.Delete(mr) if err != nil { fmt.Println(err) } } ``` -------------------------------- ### Send Email with Attachments using SendMailV31 Source: https://context7.com/mailjet/mailjet-apiv3-go/llms.txt Use this method to send emails that include file attachments. Ensure the file content is base64-encoded. Supports both regular and inline attachments for embedding images. ```go package main import ( "encoding/base64" "fmt" "log" "os" "github.com/mailjet/mailjet-apiv3-go/v4" ) func main() { mj := mailjet.NewMailjetClient(os.Getenv("MJ_APIKEY_PUBLIC"), os.Getenv("MJ_APIKEY_PRIVATE")) // Sample file content (in production, read from actual file) fileContent := []byte("Hello, this is a text file content.") encodedContent := base64.StdEncoding.EncodeToString(fileContent) messagesInfo := []mailjet.InfoMessagesV31{ { From: &mailjet.RecipientV31{ Email: "sender@example.com", Name: "Sender Name", }, To: &mailjet.RecipientsV31{ mailjet.RecipientV31{ Email: "recipient@example.com", Name: "Recipient Name", }, }, Subject: "Email with Attachment", TextPart: "Please find the attachment.", HTMLPart: "