Menu Close

Go – SendMail Function in net/smtp package in Go

In this article, we will explore the SendMail Function in net/smtp package in Go in detail, along with examples.


The Simple Mail Transfer Protocol (SMTP) is an Internet standard for electronic mail (email) transmission. Go, a popular programming language created by Google, provides an ‘smtp’ package that allows developers to send emails using the SMTP protocol. In this article, we will explore the SendMail function in Go’s smtp package, understand its usage, and look at a working example.

What is SendMail Function ?

The SendMail function is part of the ‘net/smtp’ package in Go. It provides a simple and convenient way to send emails through an SMTP server.

Function Signature

The function signature for SendMail is as follows:

func SendMail(addr string, a Auth, from string, to []string, msg []byte) error


  • addr: The address of the SMTP server, including the port number (e.g., “”).
  • a: The authentication (smtp.Auth) to use when connecting to the server. If no authentication is needed, set it to nil.
  • from: The sender’s email address.
  • to: A slice of recipient email addresses.
  • msg: The email message, including headers and body, as a byte slice.

Return value:

  • error: The function returns an error if there is a problem sending the email. Otherwise, it returns nil.


Here’s an example that demonstrates how to send an email using the SendMail function in Go:

package main

import (

func main() {

	from := "[email protected]"

	to := []string{"[email protected]"}

	subject := "Subject: Test email from Go\n"

	body := "Hello, this is a test email sent using Go's smtp package."

	msg := []byte(subject + "MIME-version: 1.0;\nContent-Type: text/plain; charset=\"UTF-8\";\n\n" + body)

	err := smtp.SendMail(
		smtp.PlainAuth("", "[email protected]", "password", ""),
		from, to, msg)

	if err != nil {
		fmt.Println("Error sending email:", err)
	} else {
		fmt.Println("Email sent successfully!")

In this example, we first set up the sender, recipient, subject, and body of the email. We then create the email message with headers and the body. Finally, we use the SendMail function to send the email through an SMTP server.

Note that you will need to replace the placeholders (e.g., “”, “[email protected]“, and “password”) with your actual SMTP server credentials.


In this article, we covered the basics of the SendMail function in Go’s smtp package. With its simplicity and ease of use, the SendMail function is an excellent choice for sending emails using the SMTP protocol in your Go applications. Remember to replace the placeholders with your actual SMTP server details, and you’ll be sending emails in no time!

To check more Go related articles. Pls click given below link:

Posted in golang, net, packages

Leave a Reply

Your email address will not be published. Required fields are marked *