LoginSignup
2
1

More than 5 years have passed since last update.

Go - beegoでgomailとテンプレートを使ってメールを送る

Posted at

irisって人気ないらしいし、フラッシュメッセージ使ったらデッドロックみたいになるし、使うのやめて、beego使うことにした。これはすごくいい気がする。中国製で中国の大きい会社も沢山つかってるし、irisと比べるとかなりいたれりつくせりだし、スターの数もフレームワーク中一番多いっぽい。軽量ならechoを使ってみようと思う。

beegoもメール機能はないっぽいので、gomailを使ってやってみる。

gomailをテンプレート使って送る例

mail.go
package mail

import (
    "gopkg.in/gomail.v2"
    "html/template"
    "bytes"
)

var contentType = "text/plain"

func Send (from string, to string, sub string,
    vars interface{}, files ...string) error {

    body, err := makeBody(vars, files...)
    if err != nil {
        return err
    }
    m := gomail.NewMessage()
    m.SetHeader("From", from)
    m.SetHeader("To", to)
    m.SetHeader("Subject", sub)
    m.SetBody(contentType, body)
    d := gomail.Dialer{Host: "localhost", Port: 25}
    err = d.DialAndSend(m)
    return err
}

func makeBody(vars interface{}, files ...string) (string, error) {
    t, err := template.ParseFiles(files...)
    if err != nil {
        return "", err
    }
    buff := &bytes.Buffer{}
    t.Execute(buff, vars)
    return buff.String(), nil
}

使い方の例

contact.go
func send_contact(contact *Contact) error {
    from := "from@example.com"
    to := "to@example.com"
    sub := "お問合せありがとうございます"
    vars := contact
    files := []string{"views/mail/contact.tpl", "views/mail/footer.tpl"}
    err := mail.Send(from, to, sub, vars, files...)
    if err != nil{
        return err
    }
    to = contact.Mail
    err = mail.Send(from, to, sub, vars, files...)
    return err
}

テンプレートファイルの例

contact.tpl
{{.Name}}様

お問合せありがとうございます!

メールアドレス: {{.Mail}}

{{.Content}}

{{template "footer"}}
footer.tpl
{{define "footer"}}

-------------
Example
http://example.com
info@example.com
{{end}}

beego特有のコードは何もないので他のフレームワークとかでも使えるのかなと思います。
もっといい方法とかあったら教えてくれるとうれしいです。

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