golang implements the method of sending E mail via smtp

  • 2020-06-01 09:58:49
  • OfStack

This article demonstrates an example of how an golang implementation can send E-mail over smtp. I will share it with you for your reference as follows:

Today, I wrote an email sending background service of a company,php only needs to store the email into the database, then mailservice written by golang will send the email out. The code of this company will not be sent out, because it contains the business logic of the company, so I sorted out the code and released it for everyone's reference

package main
import (
    "fmt"
    "net/mail"
    "net/smtp"
    "encoding/base64"
)
func main() {
    b64 := base64.NewEncoding("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
    host := "smtp.mail.com"
    email := "mail1@mail.com"
    password := "password"
    toEmail := "mail2@mail.com"
    from := mail.Address{" The sender ", email}
    to := mail.Address{" recipient ", toEmail}
    header := make(map[string]string)
    header["From"] = from.String()
    header["To"] = to.String()
    header["Subject"] = fmt.Sprintf("=?UTF-8?B?%s?=", b64.EncodeToString([]byte(" Email title 2")))
    header["MIME-Version"] = "1.0"
    header["Content-Type"] = "text/html; charset=UTF-8"
    header["Content-Transfer-Encoding"] = "base64"
    body := " I am a 1 email !golang a .";
    message := ""
    for k, v := range header {
        message += fmt.Sprintf("%s: %s\r\n", k, v)
    }
    message += "\r\n" + b64.EncodeToString([]byte(body))
    auth := smtp.PlainAuth(
        "",
        email,
        password,
        host,
    )
    err := smtp.SendMail(
        host+":25",
        auth,
        email,
        []string{to.Address},
        []byte(message),
    )
    if err != nil {
        panic(err)
    }
}

I hope this article has been helpful to you in the programming of Go language.


Related articles: