SoFunction
Updated on 2025-03-06

Sample code for sending emails in Go language

To send emails in Go, you can use third-party libraries such asgomail. The following is a usegomailSample code for sending emails:

package main
import (
	"fmt"
	"/gomail.v2"
)
func main() {
	// Create an email message	m := ()
	("From", "sender@")
	("To", "recipient@")
	("Subject", "Email Subject")
	("text/plain", "Email Content")
 	// Set up mail server information	d := ("", 587, "username", "password")
 	// Send mail	err := (m)
	if err != nil {
		("Send email failed:", err)
		return
	}
 	("Email sent successfully")
}

In the example above, we first create aObject, sets the sender, recipient, topic and body content.
Then, we created aObject, sets the address, port number of the SMTP server, and the username and password of the sender.
Finally, we useDialAndSendMethod to connect to the SMTP server and send emails. If the sending of the message fails, an error will be returned.
Please note that you need to replace the sender, recipient, SMTP server information, etc. in the sample code according to the actual situation. Also, make sure you have imported it in the projectgomailLibrary.

This is the article about the sample code for sending emails in Go language. For more related Go email content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!