### Run SendGrid Go Event Webhook Example Source: https://github.com/sendgrid/sendgrid-go/blob/main/helpers/eventwebhook/README.md Executes the Go example for the SendGrid Event Webhook helper. This command requires the `SENDGRID_API_KEY` environment variable to be set for successful execution. ```bash go run examples/eventwebhook/eventwebhook.go ``` -------------------------------- ### Run SendGrid-Go Mail Helper Example Source: https://github.com/sendgrid/sendgrid-go/blob/main/helpers/mail/README.md Executes the example Go program for the SendGrid Mail helper, demonstrating its usage. This command is typically run from the project root and requires the `SENDGRID_API_KEY` environment variable to be set for successful execution. ```bash go run examples/helpers/mail/example.go ``` -------------------------------- ### Install SendGrid Go Library Package Source: https://github.com/sendgrid/sendgrid-go/blob/main/README.md This command installs the `sendgrid-go` library using Go's package management tool. It fetches the library from GitHub, making it available for use in Go projects. ```bash go get github.com/sendgrid/sendgrid-go ``` -------------------------------- ### General SendGrid v3 Web API Usage in Go Source: https://github.com/sendgrid/sendgrid-go/blob/main/README.md This Go example illustrates how to make a general GET request to the SendGrid v3 Web API, specifically to the `/v3/api_keys` endpoint. It shows the basic structure for initializing a SendGrid request with an API key, method, and endpoint, then handling the API response and any potential errors. ```Go package main import ( "fmt" "github.com/sendgrid/sendgrid-go" "log" os" ) func main() { request := sendgrid.GetRequest(os.Getenv("SENDGRID_API_KEY"), "/v3/api_keys", "https://api.sendgrid.com") request.Method = "GET" response, err := sendgrid.API(request) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### Execute SendGrid-Go Integration Tests with Docker Source: https://github.com/sendgrid/sendgrid-go/blob/main/CONTRIBUTING.md Command to run all integration tests for the SendGrid-Go library using Docker. This requires Docker Desktop and `make` to be installed, simplifying the setup of the mock API environment necessary for tests. ```Bash make test-docker ``` -------------------------------- ### SendGrid Go: Send Email with Transactional Template Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor.md This Go example illustrates how to send an email using a SendGrid transactional template. It sets up a message with recipients and sender, then specifies a template ID and provides substitutions for dynamic content within the template, such as name, city, and subject, before sending the email. The example also includes the structure of the template content used for testing. ```text 13b8f94f-bcae-4ec6-b752-70d6cb59f932 ``` ```text <%subject%> ``` ```html Hello -name-,

I'm glad you are trying out the template feature!

<%body%>

I hope you are having a great day in -city- :)

``` ```go package main import ( "fmt" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { message := &mail.Message{ To: []mail.To{mail.To{ "Email": "test@example.com", "Name": "Example Recipient", "Substitutions": map[string]string{ "-name-", "Example User", }, }}, From: mail.Email{"from@example.com", "Example Sender"}, } message.SetTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932") message.AddSubstitution("-city-", "Orange") message.AddSubstitution("%subject%", "A message with Template") client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY")) response, err := client.Send(message) if err != nil { fmt.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### Construct and Send Email with SendGrid Go Library Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor_2.md This Go code demonstrates how to build a complex email message using the SendGrid Go library. It covers setting up 'from', 'to', 'subject', and content, along with advanced features like adding multiple recipients (To, CC, BCC), custom headers, substitutions, custom arguments, and personalizations. The example illustrates both global settings and settings applied to specific personalizations. ```Go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { from := mail.NewFrom("test@example.com", "Example User") to := mail.NewTo("test@example.com", "Example User") subject := mail.NewSubject("Sending with Twilio SendGrid is Fun") plainTextContent := mail.NewPlainTextContent("and easy to do anywhere, even with Go") htmlContent := mail.NewHtmlContent("and easy to do anywhere, even with Go") email := mail.NewMessage(from, to, subject, plainTextContent, htmlContent) // For a detailed description of each of these settings, please see the [documentation](https://sendgrid.com/docs/API_Reference/api_v3.html). email.AddTo("test1@example.com", "Example User1") to = []*mail.Tos{ mail.NewTo("test2@example.com", "Example User2"), mail.NewTo("test3@example.com", "Example User3"), } email.AddTos(to...) email.AddCcs("test1@example4.com", "Example User4") cc := []*mail.Ccs{ mail.NewCcs("test5@example.com", "Example User5"), mail.NewCcs("test6@example.com", "Example User6"), } email.AddCcs(cc...) email.AddBcc("test1@example7.com", "Example User7") bcc := []*mail.Bccs{ mail.NewBcc("test8@example.com", "Example User8"), mail.NewBcc("test9@example.com", "Example User9"), } email.AddBccs(bcc...) email.AddHeader("X-Test1", "Test1") email.AddHeader("X-Test2", "Test2") headers := []*mail.Headers{ mail.NewHeader("X-Test3", "Test3"), mail.NewHeader("X-Test4", "Test4"), } email.AddHeaders(headers) email.AddSubstitution("%name1%", "Example Name 1") email.AddSubstitution("%city1%", "Denver") substitutions := []*mail.Substitutions{ mail.NewSubstitution("%name2%", "Example Name 2"), mail.NewSubstitution("%city2%", "Orange"), } email.AddSubstitutions(substitutions) email.AddCustomArg("marketing1", "false") email.AddCustomArg("transactional1", "true") customArgs := []*mail.CustomArgs{ mail.NewCustomArg("marketing2", "true"), mail.NewCustomArg("transactional2", "false"), } email.AddCustomArgs(customArgs) email.SetSendAt(1461775051) // If you need to add more [Personalizations](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html), here is an example of adding another Personalization by passing in a personalization index email.AddTo("test10@example.com", "Example User10", 1) to = []*mail.Tos{ mail.NewTo("test11@example.com", "Example User11"), mail.NewTo("test12@example.com", "Example User12"), } email.AddTos(to..., 1) email.AddCcs("test13@example.com", "Example User13", 1) cc = []*mail.Ccs{ mail.NewCcs("test14@example.com", "Example User14"), mail.NewCcs("test15@example.com", "Example User15"), } email.AddCcs(cc..., 1) email.AddBcc("test16@example.com", "Example User16", 1) bcc = []*mail.Bccs{ mail.NewBcc("test17@example.com", "Example User17"), mail.NewBcc("test18@example.com", "Example User18"), } email.AddBccs(bcc..., 1) email.AddHeader("X-Test5", "Test5", 1) email.AddHeader("X-Test6", "Test6", 1) headers1 := []*mail.Headers{ mail.NewHeader("X-Test7", "Test7"), mail.NewHeader("X-Test8", "Test8"), } email.AddHeaders(headers1, 1) email.AddSubstitution("%name3%", "Example Name 3", 1) email.AddSubstitution("%city3%", "Redwood City", 1) substitutions1 := []*mail.Substitutions{ mail.NewSubstitution("%name4%", "Example Name 4"), mail.NewSubstitution("%city4%", "London"), } email.AddSubstitutions(substitutions1, 1) email.AddCustomArg("marketing3", "true", 1) email.AddCustomArg("transactional3", "false", 1) customArgs1 := []*mail.CustomArgs{ mail.NewCustomArg("marketing4", "false"), "transactional4": "true", } email.AddCustomArgs(customArgs1, 1) email.SetSendAt(1461775051, 1) email.SetSubject("this subject overrides the Global Subject", 1) // The values below this comment are global to entire message email.SetFrom("test@example.com", "Example User 0") email.SetGlobalSubject("Sending with Twilio SendGrid is Fun") email.AddContent(sendgrid.MimeType.Text, "and easy to do anywhere, even with Go") email.AddContent(sendgrid.MimeType.Html, "and easy to do anywhere, even with Go") contents := []*mail.Contents{ mail.NewContent("text/calendar", "Party Time!!"), ``` -------------------------------- ### Send a Single Email to a Single Recipient (Go) Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor_2.md This Go code demonstrates the minimum setup required to send a single email to one recipient using the SendGrid API. It initializes a SendGrid client with an API key from an environment variable, constructs an email message with sender, recipient, subject, and content, and then sends it, logging the response or any errors. ```go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { from := mail.NewFrom("test@example.com", "Example User") to := mail.NewTo("test@example.com", "Example User") subject := mail.NewSubject("Sending with Twilio SendGrid is Fun") plainTextContent := mail.NewPlainTextContent("and easy to do anywhere, even with Go") htmlContent := mail.NewHtmlContent("and easy to do anywhere, even with Go") email := mail.NewMessage(from, to, subject, plainTextContent, htmlContent) sendgrid := sendgrid.NewClient(os.Getenv("SENDGRID_API_KEY")) response, err := sendgrid.Send(email) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### SendGrid Legacy Template HTML Body Example Source: https://github.com/sendgrid/sendgrid-go/blob/main/use-cases/legacy-templates.md An example HTML structure for a SendGrid legacy transactional template body. It demonstrates the use of dynamic placeholders like '-name-', '-city-', and '<%body%>' which are replaced with actual data when the email is sent, enabling personalized content. ```html Hello -name-,

I'm glad you are trying out the template feature!

<%body%>

I hope you are having a great day in -city- :)

``` -------------------------------- ### SendGrid Go Email Sending with All Settings Example Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor.md This Go code demonstrates how to construct a comprehensive email message using the SendGrid Go library, utilizing almost all available personalization, content, attachment, and tracking settings. It covers adding multiple recipients (To, CC, BCC), custom headers, substitutions, custom arguments, scheduled sending, multiple content types (plain and HTML), attachments, template IDs, sections, categories, ASM settings, IP pool, and various mail and tracking settings. Finally, it sends the constructed message using the SendGrid API client. ```go package main import ( "fmt" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { message := &mail.Message{} to1 := &mail.To{mail.To{"Email": "test1@example.com", "Name": "Test Recipient 1"}} to2 := &mail.To{mail.To{"Email": "test2@example.com", "Name": "Test Recipient 2"}} to1.AddCC(&mail.Email{"cc1@example.com", "Test Recipient"}) ccs := []mail.Email{ mail.Email{"cc2@example.com", "Test Recipient"}, mail.Email{"cc3@example.com", "Test Recipient"}, } to2.AddCCs(ccs) to1.AddBCC(&mail.Email{"bcc1@example.com", "Test Recipient"}) bccs := []mail.Email{ mail.Email{"bcc2@example.com", "Test Recipient"}, mail.Email{"bcc3@example.com", "Test Recipient"}, } to2.AddBCCs(bccs) to1.AddHeader("X-Hdr1", "Test1") hdrs := map[string]string{ "X-Hdr2": "Test2", "X-Hdr3": "Test3" } to2.AddHeaders(hdrs) to1.AddSubstitution("%City1%", "Denver") to1.AddSubstitution("%name1%", "Name 1") substitutions := map[string]string{ "%City2%": "Orange", "%name2%": "Name 2" } to2.AddSubstitutions(substitutions) to1.AddCustomArg("Message-Category", "Marketing") customArgs := map[string]string{ "Campaign-ID": "Mkt-123", "Location": "US-West" } to2.AddCustomArgs(customArgs) to1.SetSendAt(1461775051) to1.SetSubject("Override subject for Rcpt 1") message.AddTo(to1) message.AddTo(to2) // If you need to add more [Personalizations](https://sendgrid.com/docs/Classroom/Send/v3_Mail_Send/personalizations.html), // Here is an example of adding another Personalization by passing in a personalization index // Global message level methods message.SetFrom(&mail.Email{"from@example.com", "Example Sender"}) message.SetReplyTo(&mail.Email{"replyto@example.com", "Reply To"}) message.SetSubject("Sending Email is fun!") message.AddContent(&mail.Content{ "Type": "text/plain", "Value": "Text content" }) message.AddContent(&mail.Content{ "Type": "text/html", "Value": " HTML content" }) message.AddAttachment(&mail.Attachment{ "filename": "balance_001.pdf", "content": "base64 encoded string", "type": "application/pdf", "disposition": "attachment" }) message.SetTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932") message.AddSection("%section1", "Substitution for Section 1 Tag") sections := map[string]string{ "%section2%": "Substitution for Section 2 Tag", "%section3%": "Substitution for Section 3 Tag" } message.AddSections(sections) message.AddCategory("customer") categories := []string{"new_account", "aws"} message.AddCategories(categories) message.AddCustomArg("campaign", "welcome") globalCustomArgs := map[string]string{ "sequence2": "2", "sequence3": "3" } message.AddCustomArgs(globalCustomArgs) asmGroupIds := []int{1, 4, 5} message.SetAsm(3, asmGroupIds) message.SetSendAt(1461775051) message.SetIpPoolName("23") // mail settings message.SetBccSetting(true, "test@example.com") message.SetBypassListManagement(true) message.SetFooterSetting(true, "Some Footer HTML", "Some Footer Text") message.SetSandBoxMode(true) message.SetSpamCheck(true, 1, "https://gotchya.example.com") // tracking settings message.SetClickTracking(true, false) message.SetOpenTracking(true, "Optional tag to replace with the open image in the body of the message") message.SetSubscriptionTracking(true, "HTML to insert into the text / html portion of the message", "text to insert into the text/plain portion of the message", "substitution tag") message.SetGoogleAnalytics(true, "some campaign", "some content", "some medium", "some source", "some term") client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY")) response, err := client.Send(message) if err != nil { fmt.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) } } ``` -------------------------------- ### SendGrid Email with Basic Content and Single Attachment in Go Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor_2.md This example illustrates how to create a basic email message with 'from', 'to', 'subject', plain text, and HTML content using the SendGrid Go library. It then demonstrates how to add a single file attachment to the email. The snippet concludes by showing how to send the constructed email and print the API response details. ```go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { from := mail.NewFrom("test@example.com", "Example User") to := mail.NewTo("test@example.com", "Example User") subject := mail.NewSubject("Sending with Twilio SendGrid is Fun") plainTextContent := mail.NewPlainTextContent("and easy to do anywhere, even with Go") htmlContent := mail.NewHtmlContent("and easy to do anywhere, even with Go") email := mail.NewMessage(from, to, subject, plainTextContent, htmlContent) email.AddAttachment("balance_001.pdf", "base64 encoded string", "application/pdf", "attachment", "Balance Sheet") sendgrid := sendgrid.NewClient(os.Getenv("SENDGRID_API_KEY")) response, err := sendgrid.Send(email) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### Create SendGrid Domain Authentication via Go API Source: https://github.com/sendgrid/sendgrid-go/blob/main/use-cases/setup-domain-authentication.md This Go program demonstrates how to create a domain authentication using the SendGrid Go library. It constructs a POST request to the `/v3/whitelabel/domains` endpoint with a JSON body containing domain details, IP addresses, and subuser information. The program then prints the API response status, body, and headers. ```Go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" ) func main() { apiKey := os.Getenv("SENDGRID_API_KEY") host := "https://api.sendgrid.com" request := sendgrid.GetRequest(apiKey, "/v3/whitelabel/domains", host) request.Method = "POST" request.Body = []byte(` { "automatic_security": false, "custom_spf": true, "default": true, "domain": "example.com", "ips": [ "192.168.1.1", "192.168.1.2" ], "subdomain": "SUBDOMAIN", "username": "YOUR_SENDGRID_SUBUSER_NAME" }`) response, err := sendgrid.API(request) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### SendGrid Go SDK: Send Email with Transactional Template Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor_2.md This Go program demonstrates how to send an email using the SendGrid Go SDK, leveraging a transactional template with dynamic substitutions. It initializes a SendGrid client using an API key from environment variables, constructs an email message, sets the template ID, adds custom substitutions, and sends the email, logging the response. ```go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { from := mail.NewFrom("test@example.com", "Example User") to := mail.NewTo("test@example.com", "Example User") subject := mail.NewSubject("Sending with Twilio SendGrid is Fun") plainTextContent := mail.NewPlainTextContent("and easy to do anywhere, even with Go") htmlContent := mail.NewHtmlContent("and easy to do anywhere, even with Go") email := mail.NewMessage(from, to, subject, plainTextContent, htmlContent) // See `Send Multiple Emails to Multiple Recipients` for additional methods for adding substitutions email.AddSubstitution("-name-", "Example User") email.AddSubstitution("-city-", "Denver") email.SetTemplateId("13b8f94f-bcae-4ec6-b752-70d6cb59f932") sendgrid := sendgrid.NewClient(os.Getenv("SENDGRID_API_KEY")) response, err := sendgrid.Send(email) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### SendGrid Go: Send Email with Attachments Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor.md This Go example demonstrates how to construct and send an email using the SendGrid API, including adding multiple file attachments. It initializes a message with recipients, sender, subject, and content, then adds attachments using both `AddAttachment` and `AddAttachments` methods before sending the email via the SendGrid client. The API key is assumed to be stored in an environment variable. ```go package main import ( "fmt" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { message := &mail.Message{ To: []mail.To{ mail.To{"Email": "test@example.com", "Name": "Example Recipient"}, }, From: mail.Email{"from@example.com", "Example Sender"}, Subject: "Test Email Subject", TextContent: "Text Email Content", HTMLContent: "HTML Email Content", } message.AddAttachment(&mail.Attachment{ "filename": "yosemite.jpg", "content": "base64 encoded string", "type": "image/jpg", "disposition": "inline", "content_id": "image_1", }) attachments := []mail.Attachment{ mail.Attachment{ "filename": "el_capitan.jpg", "content": "base64 encoded string 2", "type": "image/jpg", "disposition": "inline", "content_id": "image_2", }, mail.Attachment{ "filename": "sierra.jpg", "content": "base64 encoded string 3", "type": "image/jpg", "disposition": "inline", "content_id": "image_3", }, } message.AddAttachments(attachments) client := sendgrid.NewSendClient(os.Getenv("SENDGRID_API_KEY")) response, err := client.Send(message) if err != nil { fmt.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### SendGrid Go Mail API Reference Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor.md Comprehensive API reference for the `sendgrid-go/helpers/mail` package and `sendgrid` client, detailing methods for constructing email messages, managing personalizations, adding content, attachments, and configuring various mail and tracking settings. ```APIDOC mail.Email: mail.Email{Email string, Name string} - Represents an email address with an optional name. - Parameters: - Email: The email address (e.g., "example@example.com") - Name: The name associated with the email address (e.g., "John Doe") mail.To: mail.To{Email string, Name string} - Represents a recipient for personalization, extending mail.Email. - Parameters: - Email: The recipient's email address. - Name: The recipient's name. AddCC(email *mail.Email) - Adds a single CC recipient to the personalization. - Parameters: - email: A pointer to a mail.Email struct. AddCCs(emails []mail.Email) - Adds multiple CC recipients to the personalization. - Parameters: - emails: A slice of mail.Email structs. AddBCC(email *mail.Email) - Adds a single BCC recipient to the personalization. - Parameters: - email: A pointer to a mail.Email struct. AddBCCs(emails []mail.Email) - Adds multiple BCC recipients to the personalization. - Parameters: - emails: A slice of mail.Email structs. AddHeader(key string, value string) - Adds a custom header to the personalization. - Parameters: - key: The header name (e.g., "X-Hdr1"). - value: The header value. AddHeaders(headers map[string]string) - Adds multiple custom headers to the personalization. - Parameters: - headers: A map of header names to values. AddSubstitution(key string, value string) - Adds a substitution tag and its value for the personalization. - Parameters: - key: The substitution tag (e.g., "%City%"). - value: The value to substitute. AddSubstitutions(substitutions map[string]string) - Adds multiple substitution tags and their values for the personalization. - Parameters: - substitutions: A map of substitution tags to values. AddCustomArg(key string, value string) - Adds a custom argument (metadata) for the personalization. - Parameters: - key: The argument name. - value: The argument value. AddCustomArgs(customArgs map[string]string) - Adds multiple custom arguments for the personalization. - Parameters: - customArgs: A map of argument names to values. SetSendAt(timestamp int64) - Sets the Unix timestamp for when the email should be sent for this personalization. - Parameters: - timestamp: Unix timestamp (e.g., 1461775051). SetSubject(subject string) - Overrides the global subject for this specific personalization. - Parameters: - subject: The subject string. mail.Message: AddTo(to *mail.To) - Adds a personalization block to the message. - Parameters: - to: A pointer to a mail.To struct containing recipient and personalization details. SetFrom(from *mail.Email) - Sets the sender email address for the message. - Parameters: - from: A pointer to a mail.Email struct. SetReplyTo(replyTo *mail.Email) - Sets the reply-to email address for the message. - Parameters: - replyTo: A pointer to a mail.Email struct. SetSubject(subject string) - Sets the global subject for the message. - Parameters: - subject: The subject string. AddContent(content *mail.Content) - Adds content (e.g., plain text or HTML) to the message. - Parameters: - content: A pointer to a mail.Content struct. - mail.Content{Type string, Value string} - Type: MIME type (e.g., "text/plain", "text/html"). - Value: The content string. AddAttachment(attachment *mail.Attachment) - Adds an attachment to the message. - Parameters: - attachment: A pointer to a mail.Attachment struct. - mail.Attachment{Filename string, Content string, Type string, Disposition string} - Filename: The name of the file. - Content: Base64 encoded content of the file. - Type: MIME type of the attachment (e.g., "application/pdf"). - Disposition: "attachment" or "inline". SetTemplateId(templateID string) - Sets the ID of a SendGrid dynamic template to use. - Parameters: - templateID: The template ID string. AddSection(key string, value string) - Adds a section substitution to the message. - Parameters: - key: The section tag (e.g., "%section1"). - value: The value to substitute. AddSections(sections map[string]string) - Adds multiple section substitutions to the message. - Parameters: - sections: A map of section tags to values. AddCategory(category string) - Adds a category to the message. - Parameters: - category: The category string. AddCategories(categories []string) - Adds multiple categories to the message. - Parameters: - categories: A slice of category strings. AddCustomArg(key string, value string) - Adds a global custom argument (metadata) to the message. - Parameters: - key: The argument name. - value: The argument value. AddCustomArgs(customArgs map[string]string) - Adds multiple global custom arguments to the message. - Parameters: - customArgs: A map of argument names to values. SetAsm(groupID int, groupIDs []int) - Sets the ASM (Advanced Suppression Manager) group for the message. - Parameters: - groupID: The ID of the suppression group. - groupIDs: An optional slice of group IDs to display in the unsubscribe preferences. SetSendAt(timestamp int64) - Sets the global Unix timestamp for when the email should be sent. - Parameters: - timestamp: Unix timestamp (e.g., 1461775051). SetIpPoolName(ipPoolName string) - Sets the IP pool name to use for sending the email. - Parameters: - ipPoolName: The name of the IP pool. Mail Settings (mail.Message methods): SetBccSetting(enable bool, email string) - Enables or disables BCC functionality and sets the BCC email address. - Parameters: - enable: Boolean to enable/disable. - email: The email address to BCC. SetBypassListManagement(enable bool) - Enables or disables bypassing SendGrid's list management (unsubscribe groups). - Parameters: - enable: Boolean to enable/disable. SetFooterSetting(enable bool, html string, text string) - Enables or disables the email footer and sets its content. - Parameters: - enable: Boolean to enable/disable. - html: HTML content for the footer. - text: Plain text content for the footer. SetSandBoxMode(enable bool) - Enables or disables SendGrid's sandbox mode for testing. - Parameters: - enable: Boolean to enable/disable. SetSpamCheck(enable bool, threshold int, url string) - Enables or disables spam checking and configures its settings. - Parameters: - enable: Boolean to enable/disable. - threshold: The spam score threshold. - url: The URL to post spam check results. Tracking Settings (mail.Message methods): SetClickTracking(enable bool, enableText bool) - Enables or disables click tracking. - Parameters: - enable: Boolean to enable/disable click tracking. - enableText: Boolean to enable/disable text link tracking. SetOpenTracking(enable bool, substitutionTag string) - Enables or disables open tracking. - Parameters: - enable: Boolean to enable/disable open tracking. - substitutionTag: Optional tag to replace with the open image in the body. SetSubscriptionTracking(enable bool, html string, text string, substitutionTag string) - Enables or disables subscription tracking and configures its content. - Parameters: - enable: Boolean to enable/disable. - html: HTML content to insert for the unsubscribe link. - text: Plain text content to insert for the unsubscribe link. - substitutionTag: Substitution tag for the unsubscribe link. SetGoogleAnalytics(enable bool, campaign string, content string, medium string, source string, term string) - Enables or disables Google Analytics tracking and configures its parameters. - Parameters: - enable: Boolean to enable/disable. - campaign: Google Analytics campaign name. - content: Google Analytics content. - medium: Google Analytics medium. - source: Google Analytics source. - term: Google Analytics term. sendgrid.NewSendClient: NewSendClient(apiKey string) *sendgrid.Client - Creates a new SendGrid API client. - Parameters: - apiKey: Your SendGrid API key, typically from an environment variable. - Returns: A pointer to a sendgrid.Client instance. sendgrid.Client: Send(message *mail.Message) (*rest.Response, error) - Sends an email message using the SendGrid API. - Parameters: - message: A pointer to a mail.Message struct containing the email details. - Returns: - *rest.Response: The API response containing status code, body, and headers. - error: An error object if the API call fails. ``` -------------------------------- ### Run Go Application File Source: https://github.com/sendgrid/sendgrid-go/blob/main/CONTRIBUTING.md Command to execute a specific Go application file from the command line. Replace `` with the path to the Go source file you wish to run. This is used for testing or running examples locally. ```Bash go run ``` -------------------------------- ### SendGrid Go Email Sending without Mail Helper Class Source: https://github.com/sendgrid/sendgrid-go/blob/main/use-cases/legacy-templates-without-mailer-helper.md This Go snippet illustrates how to send an email through the SendGrid API by manually constructing the HTTP request. It demonstrates setting up the API key, endpoint, method, and the JSON request body, including personalizations, subject, content type, and a template ID. The example also shows how to handle the API response, printing the status code, body, and headers. ```go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" ) func main() { request := sendgrid.GetRequest(os.Getenv("SENDGRID_API_KEY"), "/v3/mail/send", "https://api.sendgrid.com") request.Method = "POST" request.Body = []byte(` { "personalizations": [ { "to": [ { "email": "test@example.com" } ], "subject": "I'm replacing the subject tag", "substitutions": { "-name-": "Example User", "-city-": "Denver" }, } ], "from": { "email": "test@example.com" }, "content": [ { "type": "text/html", "value": "I'm replacing the body tag" } ], "template_id": "13b8f94f-bcae-4ec6-b752-70d6cb59f932" }`) response, err := sendgrid.API(request) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### SendGrid Transactional Template HTML Body Structure Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor_2.md An example HTML structure for a SendGrid transactional template body, demonstrating the use of dynamic substitutions like -name-, -body-, and -city-. These placeholders allow for personalized content to be injected into the email at the time of sending. ```html Hello -name-,

I'm glad you are trying out the template feature!

<%body%>

I hope you are having a great day in -city- :)

``` -------------------------------- ### Load Twilio Environment Variables and Gitignore on Linux/Mac Source: https://github.com/sendgrid/sendgrid-go/blob/main/use-cases/twilio-setup.md After creating the `twilio.env` file, this snippet shows how to add it to `.gitignore` to prevent committing sensitive information and then `source` the file to load the environment variables into the current shell session. ```bash echo "twilio.env" >> .gitignore source ./twilio.env ``` -------------------------------- ### Send a Single Email to Multiple Recipients (Go) Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor_2.md This Go example illustrates how to send a single email to multiple recipients using the SendGrid API. It builds upon the basic email sending by creating a slice of `mail.Tos` objects for the recipients, allowing the same email content to be delivered to several addresses simultaneously. ```go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { from := mail.NewFrom("test@example.com", "Example User") to := []*mail.Tos{ mail.NewTo("test@example1.com", "Example User 1"), mail.NewTo("test@example2.com", "Example User 2"), } subject := mail.NewSubject("Sending with Twilio SendGrid is Fun") plainTextContent := mail.NewPlainTextContent("and easy to do anywhere, even with Go") htmlContent := mail.NewHtmlContent("and easy to do anywhere, even with Go") email := mail.NewMessage(from, to..., subject, plainTextContent, htmlContent) sendgrid := sendgrid.NewClient(os.Getenv("SENDGRID_API_KEY")) response, err := sendgrid.Send(email) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### Clone and Configure Git Remotes for sendgrid-go Source: https://github.com/sendgrid/sendgrid-go/blob/main/CONTRIBUTING.md This snippet provides the necessary Git commands to clone a forked repository, navigate into it, and add the original upstream repository as a remote. This setup is crucial for contributing to the project and keeping your fork synchronized. ```bash git clone https://github.com/sendgrid/sendgrid-go cd sendgrid-go git remote add upstream https://github.com/sendgrid/sendgrid-go ``` -------------------------------- ### Clone and Configure Git Repository Fork Source: https://github.com/sendgrid/sendgrid-go/blob/main/FIRST_TIMERS.md This snippet demonstrates how to clone a forked GitHub repository, navigate into its directory, and add the original repository as an 'upstream' remote. This setup is crucial for synchronizing changes from the main project and keeping your fork up-to-date. ```bash # Clone your fork of the repo into the current directory git clone https://github.com/your_username/sendgrid-go # Navigate to the newly cloned directory cd sendgrid-go # Assign the original repo to a remote called "upstream" git remote add upstream https://github.com/sendgrid/sendgrid-go ``` -------------------------------- ### SendGrid Go: Send Email with Dynamic Sections and Substitutions Source: https://github.com/sendgrid/sendgrid-go/blob/main/use-cases/sections-with-mailer-helper.md This Go code snippet demonstrates how to construct and send an email using the SendGrid Go helper library, specifically highlighting the 'Sections' feature. It shows how to define custom content sections (`AddSection`) and use substitutions (`SetSubstitution`) within the email body to dynamically insert personalized information and reusable content blocks before sending the email via the SendGrid API. ```go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { from := mail.NewEmail("Example User", "test@example.com") subject := "Sections can be fun" to := mail.NewEmail("Example User", "test@example.com") content := mail.NewContent("text/html", "\n\n\t\n\n\n-wel-\n

\nI'm glad you are trying out the Sections feature!\n

\n-gday-\n

\n\n") m := mail.NewV3MailInit(from, subject, to, content) m.Personalizations[0].SetSubstitution("-name-", "Example User") m.Personalizations[0].SetSubstitution("-city-", "Denver") m.Personalizations[0].SetSubstitution("-wel-", "-welcome-") m.Personalizations[0].SetSubstitution("-gday-", "-great_day-") m.AddSection("-welcome-", "Hello -name-,") m.AddSection("-great_day-", "I hope you are having a great day in -city- :)") request := sendgrid.GetRequest(os.Getenv("SENDGRID_API_KEY"), "/v3/mail/send", "https://api.sendgrid.com") request.Method = "POST" request.Body = mail.GetRequestBody(m) response, err := sendgrid.API(request) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### Send Multiple Emails with Personalization (Go) Source: https://github.com/sendgrid/sendgrid-go/blob/main/proposal/mail-helper-refactor_2.md This Go code demonstrates sending emails to multiple recipients, incorporating personalization through substitutions. It shows how to define recipients with custom data maps and apply global substitutions, allowing for dynamic content generation for each email sent via the SendGrid API. ```go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" "github.com/sendgrid/sendgrid-go/helpers/mail" ) func main() { from := mail.NewFrom("test@example.com", "Example User") tos := []*mail.Tos{ mail.NewTo("test1@example.com", "Example User 1", map[string]string{ "-name-": "Alain", "-github-": "http://github.com/ninsuo" }), mail.NewTo("test2@example.com", "Example User 2", map[string]string{ "-name-": "Elmer", "-github-": "http://github.com/thinkingserious" }) } // Alternatively, you can pass in a map of subjects OR add a subject as a parameter to the `To` object subject := mail.NewSubject("Hi -name-!") globalSubstitution := mail.NewGlobalSubstitution("-time-", "") plainTextContent := mail.NewPlainTextContent("and easy to do anywhere, even with Go") htmlContent := mail.NewHtmlContent("and easy to do anywhere, even with Go") email := mail.NewMessage(from, tos..., subject, // or subject... plainTextContent, htmlContent, globalSubstitution) // or globalSubstition... sendgrid := sendgrid.NewClient(os.Getenv("SENDGRID_API_KEY")) response, err := sendgrid.Send(email) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ``` -------------------------------- ### SendGrid Go: Send Email with Custom Arguments (Direct API) Source: https://github.com/sendgrid/sendgrid-go/blob/main/use-cases/custom-args-without-mailer-helper.md This Go example illustrates how to send an email using the SendGrid Go library by directly constructing the API request body. It specifically highlights the use of `custom_args` within both the `personalizations` array and at the top level of the email object. The code also includes `substitutions` for dynamic content and demonstrates how to handle the API response, requiring a SendGrid API key from environment variables. ```Go package main import ( "fmt" "log" "os" "github.com/sendgrid/sendgrid-go" ) func main() { request := sendgrid.GetRequest(os.Getenv("SENDGRID_API_KEY"), "/v3/mail/send", "https://api.sendgrid.com") request.Method = "POST" request.Body = []byte(` { "personalizations": [ { "to": [ { "email": "test@example.com" } ], "subject": "CustomArgs can be fun", "substitutions": { "-name-": "Example User", "-city-": "Denver" }, "custom_args": { "user_id": "343", "batch_id": "3" } } ], "from": { "email": "test@example.com" }, "content": [ { "type": "text/html", "value": "\n\n\t\n\n\nHello -name-,\n

\nI'm glad you are trying out the CustomArgs feature!\n

\nI hope you are having a great day in -city- :)\n

\n\n" } ], "custom_args": { "campaign": "welcome", "weekday": "morning" } }`) response, err := sendgrid.API(request) if err != nil { log.Println(err) } else { fmt.Println(response.StatusCode) fmt.Println(response.Body) fmt.Println(response.Headers) } } ```