編輯:
這裏是一個使用tls連接設置的例子。我沒有一個測試反對,所以失敗對我的端部連接,但我懷疑這是你需要使它工作
package main
import (
"crypto/tls"
"fmt"
"log"
"net/smtp"
)
func main() {
var (
host = "smtp.google.com"
port = 587
from = "[email protected]"
password = "baz"
to = []string{"[email protected]"}
msg = []byte("This is my message")
auth = smtp.PlainAuth("", from, password, "smtp.gmail.com")
)
serverAddr := fmt.Sprintf("%s:%d", host, port)
conn, err := tls.Dial("tcp", serverAddr, nil)
if err != nil {
log.Printf("Error Dialing %s\n", err)
return
}
client, err := smtp.NewClient(conn, host)
if err != nil {
log.Printf("Error SMTP connection: %s\n", err)
return
}
if ok, _ := client.Extension("AUTH"); ok {
if err := client.Auth(auth); err != nil {
log.Printf("Error during AUTH %s\n", err)
return
}
}
if err := client.Mail(from); err != nil {
log.Printf("Error: %s\n", err)
return
}
for _, addr := range to {
if err := client.Rcpt(addr); err != nil {
log.Printf("Error: %s\n", err)
return
}
}
w, err := client.Data()
if err != nil {
log.Printf("Error: %s\n", err)
return
}
_, err = w.Write(msg)
if err != nil {
log.Printf("Error: %s\n", err)
return
}
err = w.Close()
if err != nil {
log.Printf("Error: %s\n", err)
return
}
client.Quit()
}
我覺得這樣的事情可能會奏效的。您必須對服務器,用戶/密碼等進行適當的更改。讓我知道您是否需要更多幫助。
package main
import (
"fmt"
"log"
"net/smtp"
)
func main() {
to := "[email protected]"
from := "[email protected]"
password := "myPassword"
subject := "subject line of email"
msg := "a one-line email message"
emailTemplate := `To: %s
Subject: %s
%s
`
body := fmt.Sprintf(emailTemplate, to, subject, msg)
auth := smtp.PlainAuth("", from, password, "smtp.gmail.com")
err := smtp.SendMail(
"smtp.gmail.com:587",
auth,
from,
[]string{to},
[]byte(body),
)
if err != nil {
log.Fatal(err)
}
}
謝謝。您的示例適用於Gmail,但我試圖連接到Microsoft Exchange服務器(2013)並通過它發送電子郵件。因此,它可能需要創建一個SMTP客戶端[並在其上調用啓動TLS()](https://groups.google.com/forum/#!searchin/golang-nuts/starttls/golang-nuts/W95PXq99uns/n6pcKAFhT6kJ)。仍在試圖弄清楚,部分:) – sa125
一個類似的例子:https://gist.github.com/chrisgillis/10888032 –