Study notes - Go gomail
This blog takes 126 email as an example to introduce how to use Golanggomail
The library implements the mail sending function.
0. Preparation
- Install Golang environment
- Install
gomail
Librarygo get /gomail.v2
- Apply for SMTP service with 126 mailbox and obtain the authorization code
Open the web page of 126 mailbox, click Settings -POP3/SMTP/IMAP service, enable the POP3/SMTP service, and obtain the authorization code.
1. Configure SMTP server information in the config file
On the projectconfig
In the directory, create aand configure SMTP server information. The SMTP server address of the 126 mailbox is
smtp.
, the port is465
, the user name is your 126 email address, and the password is the authorization code you applied for.
# mail: smtp: smtp. smtp-port: 465 user: your_email@ password: your SMTP password
2. Write email sending function
Create a SendEmail function, receive the target email address, email subject, and email content as parameters, and read the SMTP server information in the configuration file. SendEmail will connect to the SMTP server based on the read configuration information, create an email object, set the email header, recipient, cc person, subject, content and other information, and then send the email.
func SendEmail(target, subject, content string) { server, port, usr, pwd := () ("SMTP Server:", server, "port:", port, "username:", usr, "password:", pwd) // Create a new mail sender d := (server, port, usr, pwd) = &{InsecureSkipVerify: true} // Try to connect and get SendCloser sendCloser, err := () if err != nil { if netErr, ok := err.(); ok && () { ("Connection timeout:", err) } else if opErr, ok := err.(*); ok { ("Operation error:", opErr) } else { ("Connection Error:", err) } return } defer () // Make sure to close the connection at the end of the function ("Successfully connected to SMTP server") // Create email m := () // Set the email header ("From", usr) // Set the recipient ("To", target) // Set up the cc person for yourself ("Cc", usr, "admin") // Set the email subject ("Subject", subject) // Set email content, support html format ("text/html", content) // Send email if err := (m); err != nil { ("Mail Send Error:", err) return } ("The email was sent successfully!") }
3. Call SendEmail function to send email
Where you need to send an email, call the SendEmail function and pass in the target email address, email subject, and email content as parameters.
func main() { email := "target_email@" SendEmail(email, "test email", "<h1>Test email content</h1>") }
This is the article about how to use Golang's gomail library to implement the email sending function. For more information about Golang's gomail library, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!