Sending Email Using Smtp in Golang
net/smtp is a built-in go package and implements SMTP protocol. It provides a simple way for sending mail through smtp servers. This package implements the Simple Mail Transfer Protocol.
Steps to send Email:
1. Get authentication from the Host server and establish a TLS connection to the host server with the PlainAuth function.
func PlainAuth(identity, username, password, host string) Auth
PlainAuth accepts four arguments of string type identity(It should be an empty string to act as username), the username(sender mail address), password (sender mail password), and port of SMTP server. PlainAuth returns an Auth, an implementation of an SMTP authentication mechanism. To authenticate to the host, the returned Auth uses the given username and password and acts as an identity.
2. Use the Auth obtained to send a mail with the SendMail function
func SendMail(addr string, a Auth, from string, to []string, msg []byte) error
SendMail function accepts five arguments. addr is of type string and contains an address and port number of the server (eg: “smtp.gmail.com:587”), a is Auth that we got from the PlainAuth function, from is of type string and contains sender mail address, to is a slice of string that contains receivers mail address and msg is a slice of the byte that contains the body of the mail.
Here we used the Gmail server to send mails. You can use a mail address with any domain, just change the host accordingly.
Go
package main
import (
"fmt"
"net/smtp"
"os"
)
func main() {
from := os.Getenv( "MAIL" )
password := os.Getenv( "PASSWD" )
toList := [] string { "example@gmail.com" }
host := "smtp.gmail.com"
port := "587"
msg := "Hello geeks!!!"
body := [] byte (msg)
auth := smtp.PlainAuth( "" , from, password, host)
err := smtp.SendMail(host+ ":" +port, auth, from, toList, body)
if err != nil {
fmt.Println(err)
os.Exit( 1 )
}
fmt.Println( "Successfully sent mail to all user in toList" )
}
|
Output:
Successfully sent mail to all user in toList
Last Updated :
08 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...