In this article, I break down my email-sending flow with Gomail, a super straightforward package for Golang. Of course, I’ve made sure to include code snippets ready for use.
I’ll also cover debugging and testing so you can make sure your code is working perfectly after following this guide.
How to install Gomail
If you haven’t already, make sure to download Go 1.2 or newer from the official website.
Then, proceed to install Gomail by running the following command in your terminal:
go get gopkg.in/mail.v2Then, you can include it in your project or application with the following code:
import gomail "gopkg.in/mail.v2"Useful links:
How to send email using Gomail and SMTP
For starters, let’s send a plain text message. Here’s a code snippet you can paste into your main configuration file (e.g., main.go):
package main
import (
"fmt"
gomail "gopkg.in/mail.v2"
)
func main() {
// Create a new message
message := gomail.NewMessage()
// Set email headers
message.SetHeader("From", "youremail@email.com")
message.SetHeader("To", "recipient1@email.com")
message.SetHeader("Subject", "Hello from the Mailtrap team")
// Set email body
` message.SetBody("text/plain", "This is the Test Body")
// Set up the SMTP dialer
dialer := gomail.NewDialer("live.smtp.mailtrap.io", 587, "api", "1a2b3c4d5e6f7g")
// Send the email
if err := dialer.DialAndSend(message); err != nil {
fmt.Println("Error:", err)
panic(err)
} else {
fmt.Println("Email sent successfully!")
}
}To run the script, simply execute go run.main.go.
Code breakdown:
NewDialer– Initiates a new SMTP connection, specifying the mail server address, port number, and credentials (username and password) to authenticate (auth) the sender.NewMessage– Creates a new email message you can customize.SetHeader– Sets specific headers such as “From”, “To”, and “Subject,” defining the sender, recipient, and subject line.SetBody– Defines the content of the email body, which is plain text in this example.DialAndSend– Establishes a connection and sends the email.
Also, as you can notice, I’m using Mailtrap SMTP, a reliable SMTP with robust sending capabilities that ensures my emails reach recipients’ inboxes. It has a high sending throughput and comes with in-depth analytics, dedicated IPs, and other features that help me optimize my email infrastructure.
Oh, and yes, there’s a free plan that lets you try all these features out, so be sure to check it out!
Send HTML email
Sending an HTML email with Gomail is super easy as all you have to do is modify the SetBody method by changing the MIME type from “text/plain” to “text/html”:
For example:
package main
import (
"fmt"
gomail "gopkg.in/mail.v2"
)
func main() {
// Create a new message
message := gomail.NewMessage()
// Set email headers
message.SetHeader("From", "youremail@email.com")
message.SetHeader("To", "recipient1@email.com")
message.SetHeader("Subject", "Hello from the Mailtrap team")
// Set email body to HTML format
message.SetBody("text/html", `
<html>
<body>
<h1>This is a Test Email</h1>
<p><b>Hello!</b> This is a test email with HTML formatting.</p>
<p>Thanks,<br>Mailtrap</p>
</body>
</html>
`)
// Set up the SMTP dialer
dialer := gomail.NewDialer("live.smtp.mailtrap.io", 587, "api", "1a2b3c4d5e6f7g")
// Send the email
if err := dialer.DialAndSend(message); err != nil {
fmt.Println("Error:", err)
panic(err)
} else {
fmt.Println("HTML Email sent successfully!")
}
}Pro tips:
- I recommend writing your HTML code within the string passed to
SetBody. - To ensure better readability for multiline HTML content, enclose the HTML in backticks (`).
- Another common practice is to attach a plain text version of your HTML message, just in case some of your recipients’ clients don’t support HTML.For this, you can use the
AddAlternativefunction:
m.SetBody( "text/html", "<p>Hello!</p>")
m.AddAlternative("text/plain", "Hello!")Send Emails with Mailtrap for Free
Send email to multiple recipients
If you have multiple recipients, simply add their addresses in the “To” field under the SetHeader method. Of course, don’t forget to separate them with commas.
Check it out:
package main
import (
"fmt"
gomail "gopkg.in/mail.v2"
)
func main() {
// Create a new message
message := gomail.NewMessage()
// Set email headers with multiple recipients
message.SetHeader("From", "youremail@email.com")
message.SetHeader("To", "abc@gmail.com", "xyz@gmail.com", "123@gmail.com") // Multiple recipients
message.SetHeader("Subject", "Test Email to Multiple Recipients")
// Set email body
message.SetBody("text/html", `
<html>
<body>
<h1>This is a Test Email</h1>
<p><b>Hello!</b> This is a test email sent to multiple recipients.</p>
<p>Thanks,<br>Mailtrap</p>
</body>
</html>
`)
// Set up the SMTP dialer
dialer := gomail.NewDialer("live.smtp.mailtrap.io", 587, "api", "1a2b3c4d5e6f7g")
// Send the email
if err := dialer.DialAndSend(message); err != nil {
fmt.Println("Error:", err)
panic(err)
} else {
fmt.Println("Email sent successfully to multiple recipients!")
}
}Additionally, you can use the Cc and Bcc to send carbon copy or blind carbon copy emails, like so:
message.SetHeader("Cc", "ccperson@example.com")
message.SetHeader("Bcc", "bccperson@example.com")We appreciate you chose this part of the article to know how to send HTML email in Gomail. To fing out how to send emails with attachments and embedded images, click here!