github.com/jacobsoderblom/buffalo@v0.11.0/generators/mail/mail.go (about)

     1  package mail
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  
     7  	"github.com/gobuffalo/buffalo/generators"
     8  	"github.com/gobuffalo/buffalo/meta"
     9  	"github.com/gobuffalo/makr"
    10  	"github.com/gobuffalo/packr"
    11  	"github.com/markbates/inflect"
    12  	"github.com/pkg/errors"
    13  )
    14  
    15  // Generator for creating new mailers
    16  type Generator struct {
    17  	App      meta.App     `json:"app"`
    18  	Name     inflect.Name `json:"name"`
    19  	SkipInit bool         `json:"skip_init"`
    20  }
    21  
    22  // Run the new mailer generator. It will init the mailers directory
    23  // if it doesn't already exist
    24  func (d Generator) Run(root string, data makr.Data) error {
    25  	g := makr.New()
    26  	defer g.Fmt(root)
    27  	data["opts"] = d
    28  
    29  	if err := d.initGenerator(data); err != nil {
    30  		return errors.WithStack(err)
    31  	}
    32  
    33  	fn := d.Name.File()
    34  	g.Add(makr.NewFile(filepath.Join("mailers", fn+".go"), mailerTmpl))
    35  	g.Add(makr.NewFile(filepath.Join("templates", "mail", fn+".html"), mailTmpl))
    36  	return g.Run(root, data)
    37  }
    38  
    39  func (d Generator) initGenerator(data makr.Data) error {
    40  	files, err := generators.FindByBox(packr.NewBox("../mail/init/templates"))
    41  	if err != nil {
    42  		return errors.WithStack(err)
    43  	}
    44  	g := makr.New()
    45  	for _, f := range files {
    46  		g.Add(makr.NewFile(f.WritePath, f.Body))
    47  	}
    48  
    49  	g.Should = func(data makr.Data) bool {
    50  		if d.SkipInit {
    51  			return false
    52  		}
    53  		if _, err := os.Stat(filepath.Join("mailers", "mailers.go")); err == nil {
    54  			return false
    55  		}
    56  		return true
    57  	}
    58  	return g.Run(".", data)
    59  }
    60  
    61  const mailerTmpl = `package mailers
    62  
    63  import (
    64  	"github.com/gobuffalo/buffalo/render"
    65  	"github.com/gobuffalo/buffalo/mail"
    66  	"github.com/pkg/errors"
    67  )
    68  
    69  func Send{{.opts.Name.Model}}() error {
    70  	m := mail.NewMessage()
    71  
    72  	// fill in with your stuff:
    73  	m.Subject = "{{.opts.Name.Title}}"
    74  	m.From = ""
    75  	m.To = []string{}
    76  	err := m.AddBody(r.HTML("{{.opts.Name.File}}.html"), render.Data{})
    77  	if err != nil {
    78  		return errors.WithStack(err)
    79  	}
    80  	return smtp.Send(m)
    81  }
    82  `
    83  
    84  const mailTmpl = `<h2>{{.opts.Name.Title}}</h2>
    85  
    86  <h3>../templates/mail/{{.opts.Name.File}}.html</h3>`