Sending emails with Golang
golang send email
golang
To send an email directly from Golang you can use the package smtp
which implements the Simple Mail Transfer
Protocol (SMTP) as defined in RFC 5321. You also need a mail server, for this tutorial will use the Gmail mail server.
Configuration
For this application to work, Gmail need to allow access to less secure applications in Gmail, you can do it from this link and activating the switch.
If you have active a signing in with 2-Step Verification then this option is disabled and this Golang application will not work at all.
If you still want to try this application you will need first to disable the 2-Step Verification and then to allow less secure application to access your Gmail account.
Golang send email code
package main
import (
"fmt"
"net/smtp"
)
func main() {
// 'from' data
from := "sender.email@gmail.com"
password := "MyComplicatedPassw0rd"
// 'to' email addresses
to := []string{
"receipient.email@gmail.com",
//You can add more than one 'to' email addresses
}
// smtp host server configuration
smtpHost := "smtp.gmail.com"
smtpPort := "587"
// Authentication.
auth := smtp.PlainAuth("", from, password, smtpHost)
// Message.
message := "To: receipient.email@gmail.com\r\n" +
"Subject: Test email using Gmail!\r\n" +
"\r\n" +
"This is the email body.\r\n"
// Sending email.
err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, []byte(message))
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Email Sent!")
}
Output
Email Sent!
For this tutorial I used a Gmail address as recipient.
Errors
There are three main possible errors that you might run into.
If you entered the wrong credentials.
535 5.7.8 Username and Password not accepted. Learn more at
5.7.8 https://support.google.com/mail/?p=BadCredentials c12sm1308020wml.39 - gsmtp
If you didn't turn OFF the Less Secure App access yet.
534 5.7.9 Application-specific password required. Learn more at
5.7.9 https://support.google.com/mail/?p=InvalidSecondFactor 1sm4251935wmf.0 - gsmtp
If you have entered wrong recipient email Address.
553 5.1.2 The recipient address <recipient-email> is not a valid RFC-5321
5.1.2 address. 63sm9682176wra.86 - gsmtp
Compile&Run
To compile the code navigate to the file location and run the following command.
$ go build example.go
Assuming that example.go
is the name of your file.
Then depending on if you are on Linux or Windows the binary file is created.
To run the application, execute the command.
Linux
$ ./example
Windows
c:\Users\adm\go\tutorials> example.exe
If you want to compile and run the application in one single step, run the following command:
go run example.go