Sending Emails with MailerSend and Golang

Install the MailerSend Golang SDK

First, you need to install the MailerSend Golang SDK by running the following command in your terminal:

go get github.com/mailersend/mailersend-go

Import the SDK in your Golang code

Next, import the SDK in your Golang code:

import (
	"github.com/mailersend/mailersend-go"
)

Create a new MailerSend client

Create a new MailerSend client with your MailerSend API key:

apiKey := "YOUR_API_KEY"
ms := mailersend.NewMailersend(apiKey)

Define the email content and recipient details

Define the email content and recipient details:

subject := "Test email"
text := "This is the plain text version of the email."
html := "<h1>Hello {{name}},</h1><p>This is a test email sent using the MailerSend SDK.</p>"

from := mailersend.From{
	Name:  "Sender Name",
	Email: "sender@example.com",
}

recipients := []mailersend.Recipient{
	{
		Name:  "Recipient Name",
		Email: "recipient@example.com",
	},
}

In this example, we've defined a single recipient with the email address recipient@example.com and the name Recipient Name. We've also set the email's subject line, HTML content, and plain text content.

Note that we're using the {{name}} placeholder in the HTML content. This will be replaced with the recipient's name when the email is sent.

Create the new Message

Create a new Message using the NewMessage method on the Email service:

message := ms.Email.NewMessage()

Setup the new message

Setup the message using the methods available:

message.SetFrom(from)
message.SetRecipients(recipients)
message.SetSubject(subject)
message.SetHTML(html)
message.SetText(text)

Send the message

Send the message to the API:

ctx := context.TODO()
res, err := ms.Email.Send(ctx, message)
if err != nil {
	// error 
}

The Send method will return a Response struct and an error. You can check the error to see if the email was sent successfully.

That's it! With these steps, you can easily send an email using MailerSend and the Golang SDK.

What’s next?

Last Updated: