mirror of
https://github.com/unknwon/the-way-to-go_ZH_CN.git
synced 2025-08-12 04:48:29 +08:00
add chapter 15.12 (#689)
This commit is contained in:
30
eBook/examples/chapter_15/smtp.go
Normal file
30
eBook/examples/chapter_15/smtp.go
Normal file
@@ -0,0 +1,30 @@
|
||||
// smtp.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"log"
|
||||
"net/smtp"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Connect to the remote SMTP server.
|
||||
client, err := smtp.Dial("mail.example.com:25")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
// Set the sender and recipient.
|
||||
client.Mail("sender@example.org")
|
||||
client.Rcpt("recipient@example.net")
|
||||
// Send the email body.
|
||||
wc, err := client.Data()
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer wc.Close()
|
||||
buf := bytes.NewBufferString("This is the email body.")
|
||||
if _, err = buf.WriteTo(wc); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
29
eBook/examples/chapter_15/smtp_auth.go
Normal file
29
eBook/examples/chapter_15/smtp_auth.go
Normal file
@@ -0,0 +1,29 @@
|
||||
// smtp_auth.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/smtp"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Set up authentication information.
|
||||
auth := smtp.PlainAuth(
|
||||
"",
|
||||
"user@example.com",
|
||||
"password",
|
||||
"mail.example.com",
|
||||
)
|
||||
// Connect to the server, authenticate, set the sender and recipient,
|
||||
// and send the email all in one step.
|
||||
err := smtp.SendMail(
|
||||
"mail.example.com:25",
|
||||
auth,
|
||||
"sender@example.org",
|
||||
[]string{"recipient@example.net"},
|
||||
[]byte("This is the email body."),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user