-
-
Save jim3ma/b5c9edeac77ac92157f8f8affa290f45 to your computer and use it in GitHub Desktop.
Golang StartTLS SMTP Example
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 ( | |
"fmt" | |
"log" | |
"net" | |
"net/mail" | |
"net/smtp" | |
"crypto/tls" | |
) | |
// StartTLS Email Example | |
func main() { | |
from := mail.Address{"", "[email protected]"} | |
to := mail.Address{"", "[email protected]"} | |
subj := "This is the email subject" | |
body := "This is an example body.\n With two lines." | |
// Setup headers | |
headers := make(map[string]string) | |
headers["From"] = from.String() | |
headers["To"] = to.String() | |
headers["Subject"] = subj | |
// Setup message | |
message := "" | |
for k,v := range headers { | |
message += fmt.Sprintf("%s: %s\r\n", k, v) | |
} | |
message += "\r\n" + body | |
// Connect to the SMTP Server | |
servername := "smtp.example.tld:465" | |
host, _, _ := net.SplitHostPort(servername) | |
auth := smtp.PlainAuth("","[email protected]", "password", host) | |
// TLS config | |
tlsconfig := &tls.Config { | |
InsecureSkipVerify: true, | |
ServerName: host, | |
} | |
c, err := smtp.Dial(servername) | |
if err != nil { | |
log.Panic(err) | |
} | |
c.StartTLS(tlsconfig) | |
// Auth | |
if err = c.Auth(auth); err != nil { | |
log.Panic(err) | |
} | |
// To && From | |
if err = c.Mail(from.Address); err != nil { | |
log.Panic(err) | |
} | |
if err = c.Rcpt(to.Address); err != nil { | |
log.Panic(err) | |
} | |
// Data | |
w, err := c.Data() | |
if err != nil { | |
log.Panic(err) | |
} | |
_, err = w.Write([]byte(message)) | |
if err != nil { | |
log.Panic(err) | |
} | |
err = w.Close() | |
if err != nil { | |
log.Panic(err) | |
} | |
c.Quit() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I have try this example to send a mail via
smtp.office365.com:587
and got error afterc.Auth()
, there is error message:2024/12/02 15:50:16 504 5.7.4 Unrecognized authentication type [TPYP295CA0020.TWNP295.PROD.OUTLOOK.COM 2024-12-02T07:50:11.227Z 08DD11A71FE694FB]
panic: 504 5.7.4 Unrecognized authentication type [TPYP295CA0020.TWNP295.PROD.OUTLOOK.COM 2024-12-02T07:50:11.227Z 08DD11A71FE694FB]
does any one can give some suggestion?