SoFunction
Updated on 2025-03-05

How to send emails through SMTP in Go language

package main
import (
 "net/smtp"
 "fmt"
 "strings"
)

/*
 * user : example@ login smtp server user
 * password: xxxxx login smtp server password
 * host: :port   smtp.:25
 * to: example@;example1@;example2@;...
 *  subject:The subject of mail
 *  body: The content of mail
 *  mailtyoe: mail type html or text
 */


func SendMail(user, password, host, to, subject, body, mailtype string) error{
 hp := (host, ":")
 auth := ("", user, password, hp[0])
 var content_type string
 if mailtype == "html" {
  content_type = "Content-Type: text/"+ mailtype + "; charset=UTF-8"
 }else{
  content_type = "Content-Type: text/plain" + "; charset=UTF-8"
 }

 msg := []byte("To: " + to + "\r\nFrom: " + user + "<"+ user +">\r\nSubject: " + subject + "\r\n" + content_type + "\r\n\r\n" + body)
 send_to := (to, ";")
 err := (host, auth, user, send_to, msg)
 return err
}

func main() {
 user := "xxxx@"
 password := "xxxx"
 host := "smtp.:25"
 to := "xxxx@;ssssss@"

 subject := "Test send email by golang"

 body := `
 <html>
 <body>
 <h3>
 "Test send email by golang"
 </h3>
 </body>
 </html>
 `
 ("send email")
 err := SendMail(user, password, host, to, subject, body, "html")
 if err != nil {
  ("send mail error!")
  (err)
 }else{
  ("send mail success!")
 }
}