Source file src/net/mail/example_test.go

     1  // Copyright 2015 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 mail_test
     6  
     7  import (
     8  	"fmt"
     9  	"io"
    10  	"log"
    11  	"net/mail"
    12  	"strings"
    13  )
    14  
    15  func ExampleParseAddressList() {
    16  	const list = "Alice <alice@example.com>, Bob <bob@example.com>, Eve <eve@example.com>"
    17  	emails, err := mail.ParseAddressList(list)
    18  	if err != nil {
    19  		log.Fatal(err)
    20  	}
    21  
    22  	for _, v := range emails {
    23  		fmt.Println(v.Name, v.Address)
    24  	}
    25  
    26  	// Output:
    27  	// Alice alice@example.com
    28  	// Bob bob@example.com
    29  	// Eve eve@example.com
    30  }
    31  
    32  func ExampleParseAddress() {
    33  	e, err := mail.ParseAddress("Alice <alice@example.com>")
    34  	if err != nil {
    35  		log.Fatal(err)
    36  	}
    37  
    38  	fmt.Println(e.Name, e.Address)
    39  
    40  	// Output:
    41  	// Alice alice@example.com
    42  }
    43  
    44  func ExampleReadMessage() {
    45  	msg := `Date: Mon, 23 Jun 2015 11:40:36 -0400
    46  From: Gopher <from@example.com>
    47  To: Another Gopher <to@example.com>
    48  Subject: Gophers at Gophercon
    49  
    50  Message body
    51  `
    52  
    53  	r := strings.NewReader(msg)
    54  	m, err := mail.ReadMessage(r)
    55  	if err != nil {
    56  		log.Fatal(err)
    57  	}
    58  
    59  	header := m.Header
    60  	fmt.Println("Date:", header.Get("Date"))
    61  	fmt.Println("From:", header.Get("From"))
    62  	fmt.Println("To:", header.Get("To"))
    63  	fmt.Println("Subject:", header.Get("Subject"))
    64  
    65  	body, err := io.ReadAll(m.Body)
    66  	if err != nil {
    67  		log.Fatal(err)
    68  	}
    69  	fmt.Printf("%s", body)
    70  
    71  	// Output:
    72  	// Date: Mon, 23 Jun 2015 11:40:36 -0400
    73  	// From: Gopher <from@example.com>
    74  	// To: Another Gopher <to@example.com>
    75  	// Subject: Gophers at Gophercon
    76  	// Message body
    77  }
    78  

View as plain text