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.
Successfully sent mail to all user in toList