Last active
March 21, 2025 03:36
-
-
Save andelf/5004821 to your computer and use it in GitHub Desktop.
golang send mail net/smtp SMTP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"log" | |
"net/mail" | |
"encoding/base64" | |
"net/smtp" | |
"fmt" | |
"strings" | |
) | |
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 := "smtp.163.com" | |
auth := smtp.PlainAuth( | |
"", | |
"fledna@163.com", | |
"password*******", | |
smtpServer, | |
) | |
from := mail.Address{"็ๆงไธญๅฟ", "fledna@163.com"} | |
to := mail.Address{"ๆถไปถไบบ", "name@139.com"} | |
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", | |
auth, | |
from.Address, | |
[]string{to.Address}, | |
[]byte(message), | |
//[]byte("This is the email body."), | |
) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} |
+1
thank you
Thank you
Thank you
Little bit correct it: return strings.Trim(addr.String(), " <@>")
Thank you :)
Thank, Bro. U saved my weekend.
I'd prefer to use the official package mime
to encode title(subject) in RFC 2047:
import (
"mime"
)
// ...
// header["Subject"] = encodeRFC2047(title)
header["Subject"] = mime.QEncoding.Encode("UTF-8", title)
// ...
@andelf thank you ๐
@goldenmean58 ๐
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
Than you !