...

Source file src/net/smtp/example_test.go

Documentation: net/smtp

		 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("[email protected]"); err != nil {
		22  		log.Fatal(err)
		23  	}
		24  	if err := c.Rcpt("[email protected]"); 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			 = "[email protected]"
		53  	msg				= []byte("dummy message")
		54  	recipients = []string{"[email protected]"}
		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("", "[email protected]", "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("", "[email protected]", "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{"[email protected]"}
		75  	msg := []byte("To: [email protected]\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, "[email protected]", to, msg)
		80  	if err != nil {
		81  		log.Fatal(err)
		82  	}
		83  }
		84  

View as plain text