github.com/roboticscm/goman@v0.0.0-20210203095141-87c07b4a0a55/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  func ExamplePlainAuth() {
    50  	// Set up authentication information.
    51  	auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com")
    52  
    53  	// Connect to the server, authenticate, set the sender and recipient,
    54  	// and send the email all in one step.
    55  	to := []string{"recipient@example.net"}
    56  	msg := []byte("This is the email body.")
    57  	err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
    58  	if err != nil {
    59  		log.Fatal(err)
    60  	}
    61  }