Golang Mail Tutorial: Sending and Receiving Emails

Author

Reads 1.2K

Computer Program Language Text
Credit: pexels.com, Computer Program Language Text

Golang has a built-in net/smtp package that makes sending emails a breeze.

This package allows you to send emails using a simple and intuitive API.

To send an email, you'll need to create a new SMTP client and set the host, port, and authentication details.

The net/smtp package provides a Dial function that takes these details as arguments.

The Dial function returns an SMTP client that you can use to send emails.

You can then use the SendMail function to send an email to a recipient.

Receiving emails in Golang is a bit more complex, but it's still relatively straightforward.

You'll need to use the net/smtp package to connect to an SMTP server and retrieve emails.

Related reading: Email Addresses to Use

Using Net/Smtp Package

The net/smtp package is a native way to send emails in Golang, but it's been frozen by the Go language team due to its lack of basic features like TLS support and MIME attachments.

You can use net/smtp to send super simple, plain-text notifications, but it's quite bare bones. The main function of the package is SendMail, and the syntax is quite simple.

The net/smtp package doesn't require installation, you can simply copy/paste the code snippet into your main application file.

For more insights, see: Simple Http Server Golang Github

Prerequisites

Credit: youtube.com, Sending mails with Go(package "net/smtp") and Gmail SMTP server. No third party libraries.

To get started with using the Net/Smtp package, there are a few prerequisites you'll need to meet.

First and foremost, you'll need to have Go installed on your machine. This is a no-brainer, but it's essential to make sure you have the latest version.

You'll also need to have basic programming knowledge. This is a broad requirement, but it's assumed that you have a solid understanding of programming concepts.

To send emails using Net/Smtp, you'll need to have SMTP credentials. You can use any provider you like, but I'll be using SendLayer for this tutorial.

If you're using SendLayer, you'll need to authorize your sending domain. This step is crucial to improve your site's email deliverability, so don't skip it.

Recommended read: Set up Html Mail Using Word

SMTP Method

The net/smtp package in Go has its limitations, but it can still be used to send simple, plain-text notifications. You can use it to connect directly to an SMTP server and send emails without any third-party SDKs.

Credit: youtube.com, Golang send mail | Net/SMTP

The main function of the package is SendMail, and its syntax is quite simple. This function allows you to send emails without needing to install any additional packages.

The net/smtp package lacks basic features such as TLS support, MIME attachments, DKIM signing, email templates, authentication mechanisms, and email queueing. You can use it to send emails, but you'll need to consider these limitations when choosing a solution.

To use the net/smtp package, you'll need to provide your username and password, which are encoded with the basic base64 method. This is done using the PlainAuth function, which comes in the following shape:

  • PlainAuth function
  • Username and password
  • Basic base64 method

The net/smtp package is a native way to send emails in Golang, but it's been frozen by the Go language team due to its limitations. Despite this, you can still use it to send simple emails.

Here are some of the features that the net/smtp package lacks:

Comprehensive Mail Library

The go-mail library is a comprehensive mail library for Go that's easy to use yet powerful. It was initially created to provide a simple interface for sending mails to a JS-Mailer project, but it quickly evolved into a full-fledged mail library.

Here's an interesting read: Golang vs Go

Credit: youtube.com, Sending Email with Go (net/smtp, gomail, and sendgrid)

One of the key features of go-mail is that it follows idiomatic Go style and best practice. This means it's designed to work seamlessly with the Go ecosystem.

Go-mail has a small dependency footprint, mainly relying on the Go Standard Library and the Go extended packages. This makes it lightweight and easy to integrate into your projects.

The smtp package of go-mail has been forked from the original Go stdlib's net/smtp package. The go-mail team then extended it to fit their needs, adding features like more SMTP Auth methods, logging, concurrency-safety, and more.

Consider reading: Golang Go

You might like: GMX Mail

Sending Mail

Sending mail with Go is made easy with the go-mail library, which provides a simple interface for sending mails.

go-mail follows idiomatic Go style and best practice, ensuring that your mail sending code is clean and efficient.

The library has a small dependency footprint, mainly relying on the Go Standard Library and the Go extended packages.

go-mail's smtp package has been forked from the original Go stdlib's net/smtp package and has been extended to fit the package's needs, including more SMTP Auth methods and logging.

This extension makes go-mail a full-fledged mail library, capable of handling complex mail tasks with ease.

go-mail's focus on concurrency-safety ensures that your mail sending code can handle multiple connections simultaneously without issues.

Explore further: Install Golang Package

Receiving Mail

Three young people working on computers in a creative office with vibrant graffiti walls.
Credit: pexels.com, Three young people working on computers in a creative office with vibrant graffiti walls.

Reading mail in Go is as straightforward as it gets. The func ReadMessage reads a message from a connection.

This is where the magic happens. The headers are parsed, and the body of the message will be available for reading from msg.Body.

You'll need to use the ReadMessage function to access the message body, which can then be read line by line.

Suggestion: Golang Line

Sending to Multiple Recipients

Sending to Multiple Recipients is a breeze in Golang mail. Simply add the recipient email addresses to the "To" field under the SetHeader method, separating them with commas.

You can also append the recipient email address(es) to the recipient header to send emails to multiple recipients.

Goroutines can be used to send bulk email asynchronously with just one call. This is a game-changer for large-scale email sending.

API Integration

API integration is a breeze in Go. Mailtrap's Email API is regularly maintained and updated by a team of developers, making it a stress-free coding experience.

For your interest: Golang Rest

Credit: youtube.com, Golang & sending emails using SMTP server (Gmail, Office365 ..) : Building Microservices

To integrate the API with your project, create a free Mailtrap account, verify your domain, and update DNS records. Then, navigate to the Sending Domains → Integration and choose the Transactional Stream for now.

You can send emails to multiple recipients with just a few lines of code, as all you have to do is add email addresses to the to field. For example, with Mailtrap's API, you can send a plain-text email by copying a snippet into your main.go file.

Here are the steps to send a plain-text email with Mailtrap's API:

  • Create a free Mailtrap account.
  • Verify your domain and update DNS records.
  • Navigate to the Sending Domains → Integration and choose the Transactional Stream for now.
  • Click on API and select Go underneath Code Samples.

Sending bulk emails is also easy, thanks to Mailtrap's bulk-aware email API. With SendLayer, another email API provider, you can send marketing emails with high deliverability and no additional costs.

Middleware

Middleware is a crucial aspect of API integration, allowing developers to extend the functionality of their code without relying on external dependencies.

go-mail, a mail library, has taken this approach by adding support for middleware on the Msg object, starting from version v0.2.8.

Credit: youtube.com, How Do You Implement Middleware? - Emerging Tech Insider

This means third-party developers can now alter a given mail message to suit their needs without requiring go-mail to support their specific requirement.

A collection of useful middlewares has been created to help users get started with message middleware.

This collection can be found in a separate repository called go-mail-middleware.

Via API

Integrating APIs for email sending is a great way to simplify the process and reduce stress.

Mailtrap's Email API is a well-maintained and updated option that can be integrated with your project.

To get started, create a free Mailtrap account, verify your domain, and update DNS records.

Navigating to the Sending Domains → Integration section and choosing the Transactional Stream for now is the next step.

Then, click on API and select Go underneath Code Samples.

Sending a plain-text email is as simple as copying the provided snippet into your main.go file.

Just be sure to replace the placeholders like token and from:email with your actual Mailtrap credentials.

People Working in front of the Computer
Credit: pexels.com, People Working in front of the Computer

Sending emails to multiple recipients is also a breeze, thanks to the Mailtrap API.

All you have to do is add email addresses to the to field.

However, don't forget to properly base64-encode your file before adding it to the content field.

Using Go's encoding/base64 package can make this process easier.

The Mailtrap API is also bulk-aware, allowing you to send marketing emails on top of transactional with high deliverability and no additional costs.

Here are some key benefits of using an API-based email provider:

  • Bulk-aware and suitable for sending marketing emails
  • High deliverability
  • No additional costs

Testing and Examples

Testing your email function is crucial to ensure it's properly configured. Run the .go file you created in a terminal window to test it.

You should see a success notification in the terminal. This indicates that your email function is working correctly.

To confirm, check the email inbox of the recipient you specified.

Consider reading: Golang Func Type

Test

Testing your application is crucial to ensure everything is working as expected. Testing your email function is particularly important.

To test your email function in Go, simply run the .go file you created in a terminal window. You should see a success notification in the terminal.

Go ahead and check the email inbox of the recipient you specified. This will confirm that the email was sent successfully.

Examples

People Using Computers at Work
Credit: pexels.com, People Using Computers at Work

You can use the strings.NewReader() module to specify a JSON payload for an API request. This payload variable contains details about the email, like the sender and recipient email addresses.

Note that the From email address needs to include the domain name you authorized in SendLayer. For instance, if you verified example.com as your sending domain, the sender email should include @example.com.

You can define the request parameters using the http.NewRequest() method, which accepts three arguments: request type, URL, and payload. The request type can be specified as a string, such as "POST".

To specify the request headers, you can use the req.Header.Add() method. This method allows you to add custom headers to the request.

The http.DefaultClient.Do() function is used to run the API request, and it accepts the request object as a parameter. If the email is successfully sent, you'll see the MessageID printed in the console.

Advanced Topics

Go libraries like Go-Mail and Gomail make sending emails a breeze. They allow you to send emails using a simple API.

Credit: youtube.com, Interactive Go Code Review: mox mail server

With Go-Mail, you can send emails using the SMTP protocol, which is the standard protocol for sending emails over the internet.

Gomail, on the other hand, uses a more high-level approach, allowing you to create emails with attachments and HTML content.

Using Gomail, you can create an email with a subject, body, and attachment in just a few lines of code.

Go libraries also provide a way to handle email errors, making it easier to debug your email sending code.

For example, Go-Mail provides a way to handle SMTP errors, such as connection timeouts and authentication failures.

Gomail also provides a way to handle email parsing errors, such as malformed email headers.

Go libraries like Go-Mail and Gomail make it easy to send emails with attachments, including images, text files, and more.

You can send emails with attachments using the AttachFile function in Go-Mail.

Gomail also provides a way to send emails with attachments, using the Attach function.

Go libraries also provide a way to send emails with HTML content, making it easy to create visually appealing emails.

Gomail provides a way to send emails with HTML content using the HTMLBody function.

Margarita Champlin

Writer

Margarita Champlin is a seasoned writer with a passion for crafting informative and engaging content. With a keen eye for detail and a knack for simplifying complex topics, she has established herself as a go-to expert in the field of technology. Her writing has been featured in various publications, covering a range of topics, including Azure Monitoring.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.