Go Sending Mail (Japanese)

"Sending Mail" from golang wiki

Go公式WikiのSending Mailの日本語意訳になります。
(元記事の最終更新日: 2017/05/31 rev.7)

Eメールの送信に関する簡単なコード例が載っています。


メール送信

以下の情報も確認してみてください。

本文のストリーミング

package main

import (
	"bytes"
	"log"
	"net/smtp"
)

func main() {
	// リモートSMTPサーバーへの接続
	c, err := smtp.Dial("mail.example.com:25")
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()
	// 送信元と受信先の設定
	c.Mail("sender@example.org")
	c.Rcpt("recipient@example.net")
	// メール本文の送信
	wc, err := c.Data()
	if err != nil {
		log.Fatal(err)
	}
	defer wc.Close()
	buf := bytes.NewBufferString("メール本文です.")
	if _, err = buf.WriteTo(wc); err != nil {
		log.Fatal(err)
	}
}

SMTP認証

package main

import (
	"log"
	"net/smtp"
)

func main() {
	// 認証情報の設定
	auth := smtp.PlainAuth(
		"",
		"user@example.com",
		"password",
		"mail.example.com",
	)
	// サーバーへの接続、認証、送信先・受信先の設定、メール送信を1ステップで実行
	err := smtp.SendMail(
		"mail.example.com:25",
		auth,
		"sender@example.org",
		[]string{"recipient@example.net"},
		[]byte("メール本文です."),
	)
	if err != nil {
		log.Fatal(err)
	}
}
 
comments powered by Disqus