github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/src/net/smtp/example_test.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package smtp_test 6 7 import ( 8 "fmt" 9 "log" 10 "net/smtp" 11 ) 12 13 func Example() { 14 // Connect to the remote SMTP server. 15 c, err := smtp.Dial("mail.example.com:25") 16 if err != nil { 17 log.Fatal(err) 18 } 19 20 // Set the sender and recipient first 21 if err := c.Mail("sender@example.org"); err != nil { 22 log.Fatal(err) 23 } 24 if err := c.Rcpt("recipient@example.net"); err != nil { 25 log.Fatal(err) 26 } 27 28 // Send the email body. 29 wc, err := c.Data() 30 if err != nil { 31 log.Fatal(err) 32 } 33 _, err = fmt.Fprintf(wc, "This is the email body") 34 if err != nil { 35 log.Fatal(err) 36 } 37 err = wc.Close() 38 if err != nil { 39 log.Fatal(err) 40 } 41 42 // Send the QUIT command and close the connection. 43 err = c.Quit() 44 if err != nil { 45 log.Fatal(err) 46 } 47 } 48 49 // variables to make ExamplePlainAuth compile, without adding 50 // unnecessary noise there. 51 var ( 52 from = "gopher@example.net" 53 msg = []byte("dummy message") 54 recipients = []string{"foo@example.com"} 55 ) 56 57 func ExamplePlainAuth() { 58 // hostname is used by PlainAuth to validate the TLS certificate. 59 hostname := "mail.example.com" 60 auth := smtp.PlainAuth("", "user@example.com", "password", hostname) 61 62 err := smtp.SendMail(hostname+":25", auth, from, recipients, msg) 63 if err != nil { 64 log.Fatal(err) 65 } 66 } 67 68 func ExampleSendMail() { 69 // Set up authentication information. 70 auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com") 71 72 // Connect to the server, authenticate, set the sender and recipient, 73 // and send the email all in one step. 74 to := []string{"recipient@example.net"} 75 msg := []byte("To: recipient@example.net\r\n" + 76 "Subject: discount Gophers!\r\n" + 77 "\r\n" + 78 "This is the email body.\r\n") 79 err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg) 80 if err != nil { 81 log.Fatal(err) 82 } 83 }