LoginSignup
1
2

More than 5 years have passed since last update.

Go - irisとgomailでテンプレート使ってメール送信する

Posted at

irisでテンプレート使ってメール送信するサンプルコードがここにありました。
自分はgomailというのを今使っているので、gomail用にちょっと修正しました。

mailパッケージというのを作って一応汎用的にしてみました。

mail.go
package mail

import (
    "github.com/kataras/iris"
    "github.com/kataras/iris/context"
    "gopkg.in/gomail.v2"
    "bytes"
)

func Send (app *iris.Application, from string, to string,
    sub string, view string, layout string, vars context.Map) error {

    m := gomail.NewMessage()
    m.SetHeader("From", from)
    m.SetHeader("To", to)
    m.SetHeader("Subject", sub)
    buff := &bytes.Buffer{}
    app.View(buff, view, layout, vars)
    m.SetBody("text/plain", buff.String())
    d := gomail.Dialer{Host: "localhost", Port: 25}
    err := d.DialAndSend(m)
    return err
}

上記をインポートして下記のように使います。

send.go
func send() error {
    err := mail.Send(
        app,
        "from@example.com",
        "to@example.com",
        "お問合せありがとうございます",
        "mail/contact.html",
        "mail/layout.html",
        context.Map{
            "Company": "会社名",
            "Name":  "ご担当者様",
            "Mail": "to@example.com",
            "Content": "お問い合わせ内容",
        },
    )
    return err
}

text/plainをtext/htmlに変えればHTMLメールが送れます。

1
2
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
1
2