smtp
stands for Simple Mail Transfer Protocol. It is used to send emails, and it works by moving messages between email clients and servers.
The Go language provides a library that adds email functionality to a Go app and thus makes this package easy to use.
This package uses the syntax below to send emails.
func SendMail(addr server: port, a Auth, from email_address, to []email_address, msg []content_here) error
The address attribute addr
allows the user to connect to a server and must include:
port
numberHTML
) that will be included in the message
error
for clarification purposes.Follow the steps below to send an email using smtp
.
PlainAuth
function to provide an authentication mechanismPlain authentication is a method of authorizing an email client to send an email to its recipient.
This function accepts four arguments which are of the string
type.
They include:
username
- the sender’s email address.
password
- the sender’s email password.
port
- the SMTP
port server.
identity
- an empty string that acts as username
.
func PlainAuth(identity, username, password, host string) Auth
The syntax above represents the PlainAuth
function which returns an Auth
. The returned Auth
uses the given username
, password
and acts as an identity
to authenticate the host.
Auth
obtained to send an email with the SendMail
functionThis function sends the email. It connects to the mail server using the authentication (Auth
) earlier created from the PlainAuth
function.
Below is a sample code snippet that uses smtp
to send an email.
package main import ( "log" "net/smtp" ) func main() { // Configuration from := "samplemail@gmail.com" password := "12345samplemail" to := []string{"recipient@email.com"} smtpHost := "smtp.gmail.com" smtpPort := "587" message := []byte("Hello! I'm trying out smtp to send emails to recipients.") // Create authentication auth := smtp.PlainAuth("", from, password, smtpHost) // Send actual message err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, message) if err != nil { log.Fatal(err) }
Sensitive data like passwords should not be used directly in the code.
The best practice is to use environment (env
) variables for configuration.
RELATED TAGS
CONTRIBUTOR
View all Courses