Golang : Send email and SMTP configuration example
Golang has a SMTP(Simple Mail Transfer Protocol) package that allows developers to send out email in quick and painless way. This tutorial will cover the basic stuff and will use Gmail as an example to send out email.
NOTE : You will have to replace the configuration below such as password and gmail address with yours to test out the code
package main
import (
"fmt"
"net/smtp"
"strconv"
)
type EmailConfig struct {
Username string
Password string
Host string
Port int
}
func main() {
// authentication configuration
smtpHost := "smtp.****" // change to your SMTP provider address
smtpPort := *** // change to your SMTP provider port number
smtpPass := "yourpassword" // change here
smtpUser := "yourusername@gmail.com" // change here
emailConf := &EmailConfig{smtpUser, smtpPass, smtpHost, smtpPort}
emailauth := smtp.PlainAuth("", emailConf.Username, emailConf.Password, emailConf.Host)
sender := "fromwho@gmail.com" // change here
receivers := []string{
"someone@somedomain.com",
"someone@somedomain.com"
} // change here
message := []byte("Hello from Go SMTP package!") // your message
// send out the email
err := smtp.SendMail(smtpHost+":"+strconv.Itoa(emailConf.Port), //convert port number from int to string
emailauth,
sender,
receivers,
message,
)
if err != nil {
fmt.Println(err)
}
}
If not output or error message, check your target email address inbox to see if the generated email is there or not. Hope this tutorial can be useful to you.
Reference :
See also : Golang : Send email with attachment
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.3k Python : Print unicode escape characters and string
+4.9k Golang : Convert lines of string into list for delete and insert operation
+12.3k Android Studio : Highlight ImageButton when pressed on example
+4.7k Nginx and PageSpeed build from source CentOS example
+7.5k Golang : Generate human readable password
+13.8k Javascript : Prompt confirmation before exit
+9.1k Golang : Terminate-stay-resident or daemonize your program?
+5.1k Unix/Linux : How to archive and compress entire directory ?
+35.6k Golang : Save image to PNG, JPEG or GIF format.
+16.8k Golang : How to save log messages to file?
+15.7k Golang : How to reverse elements order in map ?
+19.1k Golang : Fix cannot download, $GOPATH not set error