github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/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  	"github.com/shogo82148/std/fmt"
     9  	"github.com/shogo82148/std/log"
    10  	"github.com/shogo82148/std/net/smtp"
    11  )
    12  
    13  func Example() {
    14  	// リモートSMTPサーバーに接続する。
    15  	c, err := smtp.Dial("mail.example.com:25")
    16  	if err != nil {
    17  		log.Fatal(err)
    18  	}
    19  
    20  	// まず、送信者と受信者を設定します
    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  	// メール本文を送信する。
    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  	// QUITコマンドを送信し、接続を閉じます。
    43  	err = c.Quit()
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  }
    48  
    49  func ExamplePlainAuth() {
    50  	// hostnameはPlainAuthによってTLS証明書の検証に使用されます。
    51  	hostname := "mail.example.com"
    52  	auth := smtp.PlainAuth("", "user@example.com", "password", hostname)
    53  
    54  	err := smtp.SendMail(hostname+":25", auth, from, recipients, msg)
    55  	if err != nil {
    56  		log.Fatal(err)
    57  	}
    58  }
    59  
    60  func ExampleSendMail() {
    61  	// 認証情報を設定する。
    62  	auth := smtp.PlainAuth("", "user@example.com", "password", "mail.example.com")
    63  
    64  	// サーバーに接続し、認証し、送信元と受信者を設定し、
    65  	// メールを一括で送信します。
    66  	to := []string{"recipient@example.net"}
    67  	msg := []byte("To: recipient@example.net\r\n" +
    68  		"Subject: discount Gophers!\r\n" +
    69  		"\r\n" +
    70  		"This is the email body.\r\n")
    71  	err := smtp.SendMail("mail.example.com:25", auth, "sender@example.org", to, msg)
    72  	if err != nil {
    73  		log.Fatal(err)
    74  	}
    75  }