Product
Docs
Resources
Log In

3 Different Ways to Send Emails Using Golang

Introduction

There is just no avoiding sending emails for customer-driven applications. Because of this, a variety of packages have been built to help send emails programmatically. Each package comes with its own programming language like Go, an open-source language supported by Google.

Notifications sent inside an application can be limiting, especially in the case of web applications. It can take time for users to actually see these notifications, or they might never if they don’t log into the app. Email notifications solve that problem, helping you communicate with customers quickly and programatically.

In this tutorial, you'll take a look at three different methods of sending emails with Golang using the package SMTP and gomail. In addition you’ll learn about third-party API services like Amazon SES and Mailgun to send emails using a multi-channel notification service like Courier.

Email Sending Fundamentals in Golang

Before you begin setting up your server or third-party API server to send emails, let’s discuss a few fundamentals that will help you out as you begin exploring Golang.

Sanitizing email user inputs

As you receive information from users on your platform (like contact information), it’s important to sanitize the data before using it. Prevent malicious users from inputting text that can harm your application by sanitizing the form input and removing the HTML entities, slashes, and tags.

Sending Plain Text Emails vs HTML Formatted Emails

If you want to add structure and styling to your email content for consistent branding, send your emails using HTML. That’s often how newsletters are sent.

However if your content is simple and includes only text and links, a plain text email is sufficient.

Knowing the type of content you wish to send can help you choose which format fits your content better.

Sending Email Attachments in Golang

When you want to share images or documents (or anything external), you’ll need to attach it to your email using a third-party package like Gomail:

1 2 msg := gomail.NewMessage() msg.Attach("/home/User/cat.jpg")

You’ll look at Gomail in more detail later on in this article.

Send Transactional v/s Marketing Email with Golang - What You Need To Know

Transactional and marketing emails have two different purposes, and both can help you understand the motivation behind the content you’re sending.

Transactional emails are sent to one user at a time as part of the user's transaction within the application. A good example of this is a receipt for payment or resetting a password.

A marketing email is usually sent to a large number of recipients to convince them to make a purchase, notify them of a current sale, or communicate about a new product launch. Keep in mind that these types of transactions are subject to local laws.

3 options to send email using Golang

1. SMTP

SMTP is a network protocol for sending email over the internet. When you send and receive emails, the server most likely uses SMTP to deliver it.

In Golang, there is a package called SMTP. It comes through the backend to Go and is readily available for you upon installation.

Package smtp

Using the Golang SMTP package, you can configure it to send emails using any SMTP server you want.

In this demonstration, you'll be utilizing the Google Gmail SMTP server.

Before you begin, you'll need a Google account. You’ll have to enable access to less secure applications. If you have two-step verification turned on, you’ll also need a password.

In the code below, the PlainAuth function takes in four arguments: identity, username, password, and host. The identity should be left to an empty string, to serve the purpose of a username.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 package main import "net/smtp" func main() { from := "<paste your gmail account here>" password := "<paste Google password or app password here>" toEmailAddress := "<paste the email address you want to send to>" to := []string{toEmailAddress} host := "smtp.gmail.com" port := "587" address := host + ":" + port subject := "Subject: This is the subject of the mail\n" body := "This is the body of the mail" message := []byte(subject + body) auth := smtp.PlainAuth("", from, password, host) err := smtp.SendMail(address, auth, from, to, message) if err != nil { panic(err) } }

In order to authenticate to the host, smtp.gmail.com, paste your Gmail username and password or app password. The SendMail function will return an error if there is one, and the email will not be sent.

The first parameter, address, is used to connect to the server and the auth is used to authenticate. The remaining parameters provide the context for the message itself.

The SMTP package is ideal for when you need to send very basic emails that don’t require a lot of configuration.

Package Gomail

However, the default package SMTP can be limiting. For example, you can’t add an attachment to your email. Gomail is a more efficient package, offering a wider range of functions like HTML templates, embedded images, and automatic encoding. To use Gomail, you'll need version 1.2 of Go or newer.

In the code below, NewMessage creates a new message, and the headers are set by the SetHeader function. The SetBody function is used for the message itself.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 package main import ( gomail "gopkg.in/gomail.v2" ) func main() { msg := gomail.NewMessage() msg.SetHeader("From", "<paste your gmail account here>") msg.SetHeader("To", "<paste the email address you want to send to>") msg.SetHeader("Subject", "<paste the subject of the mail>") msg.SetBody("text/html", "<b>This is the body of the mail</b>") msg.Attach("/home/User/cat.jpg") n := gomail.NewDialer("smtp.gmail.com", 587, "<paste your gmail account here>", "<paste Google password or app password here>") // Send the email if err := n.DialAndSend(msg); err != nil { panic(err) } }

Don't forget to import gomail from the online repo:

1 $ go get gopkg.in/gomail.v2

Because you’re using a third-party package, the Attach function attaches external files to the email. The NewDialer function and DialAndSend open up an SMTP server connection and send the email.

2. Third-Party Email API Services

Third-party email API services like SendGrid, Mailgun, and Amazon Simple Email Service are dedicated platforms that allow you to send mass emails easily.

Using an SMTP server, you can send emails programmatically, but third-party API servers allow you to send tens of thousands of emails a day that are scalable, powerful, and offer backend analytics. In most cases, after signing up for an account, you'll have the choice of using a web API or SMTP.

Amazon - Simple Email Service (SES)

Amazon SES helps you send emails inexpensively and fast. Bonus, it has a great reputation, so your emails won’t be treated as spam.

With Amazon SES, you can send up to 50,000 emails per day with analytics on the backend, like open and click-through rate.

To get started with Amazon SES and integrate with Go, simply sign up, add, and verify your domain and emails. Then retrieve your SMTP credentials and replace them in Gomail in your Golang application if you want to use SMTP.

You also have the option to use the Amazon SES console or [Amazon SES API](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/examples-send-using-sdk.html0. Consider using Amazon SES if you want an inexpensive platform or if you’re hosting your web application on AWS.

Mailgun

Mailgun is another third-party service that helps send automated emails. One of its greatest strengths, when compared with Amazon SES, is its ability to provide more in-depth analytics. It also includes an email verification service that helps you eliminate invalid email addresses and reduces your bounce rate.

Mailgun is not as inexpensive as Amazon SES, but its added benefits may be worth the cost, depending on what you’re looking for.

Note: It’s important to send a test email for any email service, so you know if your emails are landing in spam, promotions, or inbox folders.

3. Using Multi-Channel Notification Service

At times, you may wish to send a notification to a variety of channels, including email, push notifications, and SMS. A multichannel notification service is designed to do just that.

Courier is a multichannel notification service that can design and deliver notifications with ease. With one API, you can send a notification using multiple languages.

To integrate Courier with Go, create an account and complete the onboarding process which will walk you through creating and sending your first notification.

The following example uses Gmail as the email provider service.

After the onboarding process, access Courier’s homepage and click Send emails via Gmail. Link your desired Google account to allow Courier to send emails on your behalf.

On the sidebar, click Designer and Create Notification.

Choose Gmail as the email provider and publish changes.

You can view and change the template to fit your needs.

Go to your settings and click Events. Type EXAMPLE_NOTIFICATION and select the notification you just created.

The code below shows how you make a POST request to the https://api.courier.com/send endpoint in order to send an email.

The following code is provided by Courier using Go. The complete code can be found on Courier’s site.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 package main import ( "context" "log" "github.com/trycourier/courier-go/v2" ) func main() { client := courier.CreateClient("YOUR_AUTH_TOKEN_HERE", nil) messageID, err := client.Send( context.Background(), "EXAMPLE_NOTIFICATION", "8ec8c99a-c5f7-455b-9f60-8222b8a27056", courier.SendBody{ Profile: Profile{ Email: "test@gmail.com", }, }, ) if err != nil { log.Fatalln(err) } log.Println(messageID) }

The payload variable is important—it allows you to configure the event you want to be triggered using the default event EXAMPLE_NOTIFICATION above.

Make sure you update the test@gmail.com to the email you want this notification to be sent to, and the Authorization header to your bearer token.

To run the script, run go run main.go in the terminal. This should successfully deliver the email to the recipient inbox.

To get your auth tokens, navigate to API_KEYS under your settings, as shown in the screenshot below:

If you like, you can also use Amazon SES, Mailgun, SendGrid, or other providers to send emails programmatically with Courier. For a full reference of email integrations that Courier supports, you can visit their website.

Conclusion

This guide covered three ways of sending emails with Golang using the package smtp and Gomail.

To quickly get you started with an SMTP server, use the Golang application to send up to 500 free emails a day.

If you want to send mass emails, try Amazon SES or Mailgun. As third-party services, they can send emails for medium to large scale projects.

With Amazon SES, you can send thousands of emails a day with analytic capabilities on a trusted platform. Mailgun, while more expensive, offers additional analytic features and email verification services that may justify the price tag depending on what you’re looking for.

Using a platform like Courier, you can integrate with Amazon SES, Mailgun, or SendGrid to send emails using a simple API. To get started sending notifications with ease, visit Courier today.

Author: Samuel Torimiro

View More Guides

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Email & push notification

Build your first notification in minutes

Send up to 10,000 notifications every month, for free.

Email & push notification

Product

Pricing

Providers

Developers

Documentation

API

Libraries

Status

© 2022 Courier. All rights reserved.