Skip to content

Instantly share code, notes, and snippets.

Last active September 20, 2023 15:13
Show Gist options
  • Save andelf/5004821 to your computer and use it in GitHub Desktop.
Save andelf/5004821 to your computer and use it in GitHub Desktop.
golang send mail net/smtp SMTP
package main
import (
func encodeRFC2047(String string) string{
// use mail's rfc2047 to encode any string
addr := mail.Address{String, ""}
return strings.Trim(addr.String(), " <>")
func main() {
// Set up authentication information.
smtpServer := ""
auth := smtp.PlainAuth(
from := mail.Address{"监控中心", ""}
to := mail.Address{"收件人", ""}
title := "当前时段统计报表"
body := "报表内容一切正常";
header := make(map[string]string)
header["From"] = from.String()
header["To"] = to.String()
header["Subject"] = encodeRFC2047(title)
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/plain; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"
message := ""
for k, v := range header {
message += fmt.Sprintf("%s: %s\r\n", k, v)
message += "\r\n" + base64.StdEncoding.EncodeToString([]byte(body))
// Connect to the server, authenticate, set the sender and recipient,
// and send the email all in one step.
err := smtp.SendMail(
smtpServer + ":25",
//[]byte("This is the email body."),
if err != nil {
Copy link

ritoon commented Oct 2, 2014

Thank's !

Copy link

Nice work. Thanks!.

Copy link

is working, thank you!

Copy link

Not working for me. I am getting error like:
2015/05/19 17:38:49 x509: certificate has expired or is not yet valid
exit status 1

Copy link

Thank you!

Copy link

I got this error for using gmail 2015/11/26 14:56:43 x509: certificate signed by unknown authority

Copy link

Like a charm 👍

Copy link

Than you !

Copy link


Copy link

thank you

Copy link

hatuan commented Jan 19, 2018

Thank you

Copy link

lanzay commented Feb 3, 2018

Thank you
Little bit correct it: return strings.Trim(addr.String(), " <@>")

Copy link

in3166 commented May 28, 2020

Thank you :)

Copy link

Thank, Bro. U saved my weekend.

Copy link

I'd prefer to use the official package mime to encode title(subject) in RFC 2047:

import (

// ...
// header["Subject"] = encodeRFC2047(title)
header["Subject"] = mime.QEncoding.Encode("UTF-8", title)
// ...

Copy link

id6827 commented Jun 9, 2022

@andelf thank you 😀
@goldenmean58 👍

Copy link

Thanks!!! I am struggling for hours. My old code worked with G-Mail and Yahoo but not with smaller mail services. THANKS AGAIN

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment