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
+11.2k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+10k Golang : Use regular expression to get all upper case or lower case characters example
+5.6k Unix/Linux : Get reboot history or check when was the last reboot date
+22k Golang : Repeat a character by multiple of x factor
+7.2k Golang : File system scanning
+14.2k Android Studio : Use image as AlertDialog title with custom layout example
+17.8k Golang : Get all upper case or lower case characters from string example
+23.2k Golang : Get ASCII code from a key press(cross-platform) example
+6.4k Golang : Map within a map example
+13.5k Golang : Set image canvas or background to transparent
+6.3k Golang : Break string into a slice of characters example
+12.1k Golang : calculate elapsed run time