2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Goでメールを送信する

Posted at

メールについて色々と学んでる最中なので、勉強中のGoでメールの送信方法をまとめてみました。
そのうち受信についても記事にしてまとめていきたいと思っています。

SMTPSでメールを送信する

package main

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/mail"
	"net/smtp"
)

const (
	user     = "hoge@example.com"
	password = "hogehoge"
	rcpt     = "hoge_rcpt@rcpt.example.com"
	host     = "example.com"
)

func main() {
	server := host + ":" + "465"
	body := "This mail is TLS test."
	// TLS config
	tlsconfig := &tls.Config{
		InsecureSkipVerify: true,
		ServerName:         host,
	}

	// ログイン情報を用意する
	auth := smtp.PlainAuth("", user, password, host)

	// TLSで通信するためのコネクションを用意する
	con, err := tls.Dial("tcp", server, tlsconfig)
	if err != nil {
		log.Fatal(err)
	}
	// TLSのコネクションでSMTP接続する
	c, err := smtp.NewClient(con, host)
	if err != nil {
		log.Fatal(err)
	}
	if err = c.Auth(auth); err != nil {
		log.Fatal(err)
	}
	if err = c.Mail(user); err != nil {
		log.Fatal(err)
	}
	if err = c.Rcpt(rcpt); err != nil {
		log.Fatal(err)
	}
	w, err := c.Data()
	if err != nil {
		log.Fatal(err)
	}

	message := "From: " + user + "\r\n"
	message += "To: " + rcpt + "\r\n"
	message += "\n" + body

	_, err = w.Write([]byte(message))
	if err != nil {
		log.Fatal(err)
	}
	defer w.Close()

	c.Quit()
}

STARTTLSでメールを送信する

今回サーバのポートを25番でやっていますが、環境によってはOB25によって587番ポートでサービスを提供している場合があると思うので、ポート番号は適宜変更してください。

package main

import (
    "crypto/tls"
    "log"
    "net/smtp"
)

const (
	user     = "hoge@example.com"
	password = "hogehoge"
	rcpt     = "hoge_rcpt@rcpt.example.com"
	host     = "example.com"
)

func main() {
    server := host + ":" + "25"
    tlsconfig := &tls.Config{
        ServerName:         server,
        InsecureSkipVerify: true,
    }

    c, err := smtp.Dial(server)
    if err != nil {
        log.Fatal(err)
    }
    if err = c.StartTLS(tlsconfig); err != nil {
        log.Fatal(err)
    }
    auth := smtp.PlainAuth("", user, password, host)
    if err = c.Auth(auth); err != nil {
        log.Fatal(err)
    }
    if err = c.Mail(user); err != nil {
        log.Fatal(err)
    }
    if err = c.Rcpt(rcpt); err != nil {
        log.Fatal(err)
    }
    w, err := c.Data()
    if err != nil {
        log.Fatal(err)
    }
    defer w.Close()

    message := ""
    message += "From: " + user + "\r\n"
    message += "To: " + rcpt + "\r\n"
    message += "Subject: " + "Test Mail" + "\r\n"
    message += "\n" + "This is StartTLS test"

    w.Write([]byte(message))
    c.Quit()
} 
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?