【发布时间】:2020-10-22 20:44:45
【问题描述】:
我有下面的 main.go 代码来解析 HTML 模板并通过电子邮件发送:
package main
import (
"bytes"
"fmt"
"net/smtp"
"text/template"
)
func main() {
// Sender data.
from := "from@gmail.com"
password := "<Email Password>"
// Receiver email address.
to := []string{
"sender@example.com",
}
// smtp server configuration.
smtpHost := "smtp.gmail.com"
smtpPort := "587"
// Authentication.
auth := smtp.PlainAuth("", from, password, smtpHost)
t, _ := template.ParseFiles("template.html")
var body bytes.Buffer
mimeHeaders := "MIME-version: 1.0;\nContent-Type: text/html; charset=\"UTF-8\";\n\n"
body.Write([]byte(fmt.Sprintf("Subject: This is a test subject \n%s\n\n", mimeHeaders)))
t.Execute(&body, struct {
Name string
Message string
}{
Name: "Hasan yousef",
Message: "This is a test message in a HTML template",
})
// Sending email.
err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, to, body.Bytes())
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Email Sent!")
}
使用以下模板:
<!-- template.html -->
<!DOCTYPE html>
<html>
<body>
<h3>Name:</h3><span>{{.Name}}</span><br/><br/>
<h3>Email:</h3><span>{{.Message}}</span><br/>
</body>
</html>
效果很好。
我尝试对我的Office 365 电子邮件执行相同操作:
smtpHost := "smtp.office365.com"
smtpPort := "587"
但是没用,报如下错误:
504 5.7.4 Unrecognized authentication type [ZR0P278CA0020.CHEP278.PROD.OUTLOOK.COM]
在 Gmail 中,我启用了 using unsecure app 以使 smtp.PlainAuth 工作正常,在 Office 365 中我知道它的 Encryption method: TLS or STARTTLS 但不知道如何将其合并到我的代码中?
【问题讨论】:
-
如果您的问题是关于 TLS/STARTTLS,那么请删除所有与 HTML 模板解析无关的细节。
-
感谢@Marc 在您链接的帮助下,我找到了答案。赞赏。
标签: go