Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
language
email
communitycreator

How to send email using smtp in Golang

Wale Moshood

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.

Syntax

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

Parameters

The address attribute addr allows the user to connect to a server and must include:

  • A port number
  • An authentication method
  • The sender and recipient’s email addresses
  • The markup language (HTML) that will be included in the message
  • An error for clarification purposes.

Steps to send an email

Follow the steps below to send an email using smtp.

1. Use the PlainAuth function to provide an authentication mechanism

Plain authentication is a method of authorizing an email client to send an email to its recipient.

Parameters

This function accepts four arguments which are of the string type.

They include:

  1. username - the sender’s email address.

  2. password - the sender’s email password.

  3. port - the SMTP port server.

  4. identity - an empty string that acts as username.

Syntax

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.

2. Use the Auth obtained to send an email with the SendMail function

This 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

golang
go
language
email
communitycreator
RELATED COURSES

View all Courses

Keep Exploring