Techieindoor

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.

Introduction:

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

Parameters:

Return value:

Example

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

package main

import (
	"fmt"
	"net/smtp"
)

func main() {

	from := "sender@example.com"

	to := []string{"recipient@example.com"}

	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.example.com:587",
		smtp.PlainAuth("", "user@example.com", "password", "smtp.example.com"),
		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., “smtp.example.com”, “user@example.com“, and “password”) with your actual SMTP server credentials.

Conclusion

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:

https://www.techieindoor.com/category/golang/

https://pkg.go.dev/net/smtp

Exit mobile version