How To Send An Email in Go Lang Using An SMTP (Step-By-Step)
Do you want to send an Email to your users in Go Lang? Learn how to do so by first setting up an SMTP using Brevo SMTP and then sending the first email in this step-by-step guide! Brevo offers a free tier with up to 300 free emails per day, which is enough for most small projects!
Set up Brevo SMTP
Before we can send an Email we have to set up an SMTP service. For this guide, I am using Brevo because I have a good experience with them, and the 300 free emails per day are enough for my projects. You can use whatever SMTP server you have access to, though.
- Create an account for Brevo here (affiliate link).
- Log in to your account
- Click on your Profile and go to “SMTP & API”
- Click on “Generate a new SMTP key”
- Enter a name for the key, for example, “go-mail”
- Copy the key. You will need it in the next step
Send an Email in Go Lang
Now that we have set up Brevo, you need the following details from the last steps to be able to send an email using the SMTP:
- SMTP Server: smtp-relay.sendinblue.com
- Port: 587
- Login: <your-email>
- Key: <your-key>
For this guide, I will create a new project, install the gomail package and then send an email using it. Follow these steps:
go mod init github.com/<username>/send-mail-go
go get gopkg.in/gomail.v2
- Create a file called
main.go
- Enter the following code:
package main
import (
gomail "gopkg.in/gomail.v2"
)
func main() {
from := "<your-login>"
to := "<your-receiver>"
host := "smtp-relay.sendinblue.com"
port := 587
msg := gomail.NewMessage()
msg.SetHeader("From", from)
msg.SetHeader("To", to)
msg.SetHeader("Subject", "Your subject")
// text/html for a html email
msg.SetBody("text/plain", "Your body")
n := gomail.NewDialer(host, port, from, "<your-key>")
// Send the email
if err := n.DialAndSend(msg); err != nil {
panic(err)
}
}
With this, you are able to send emails using Go Lang and Brevo SMTP. Try it out now, and let me know what you think!
Conclusion
In this guide, we learned how to set up Brevo SMTP and use it to send an email in Go Lang. I hope the guide was helpful to you, and if you have any questions, feel free to ask.
Need help or want to share feedback? Join my discord community!
Don’t miss out on any updates or future guides by subscribing to my monthly newsletter.
[convertkit form=2303042]
If this guide is helpful to you and you like what I do, please support me with a coffee!