Golang implements the method of sending e-mail through SMTP _golang

Source: Internet
Author: User
Tags auth base64 sprintf

The example in this article describes the Golang implementation method for sending e-mail messages through SMTP. Share to everyone for your reference, specific as follows:

Today wrote a company's mail to send a background service, PHP only need to put the mail into the database, and then Golang write the mailservice will mail sent out. The company's code does not send out, thinking with the business logic of the company, I sorted out the code for your reference. hehe

Copy Code code as follows:
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{"sender", email}
To: = Mail. address{"Receiver", 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 ("Mail Heading 2"))
header["mime-version"] = "1.0"
header["Content-type"] = "text/html; Charset=utf-8 "
header["content-transfer-encoding"] = "base64"
Body: = "I am an email!golang issued.";
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 will help you with your go language program.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.