github.com/segakazzz/buffalo@v0.16.22-0.20210119082501-1f52048d3feb/genny/mail/mail.go (about)

     1  package mail
     2  
     3  import (
     4  	"text/template"
     5  
     6  	"github.com/gobuffalo/genny/v2"
     7  	"github.com/gobuffalo/genny/v2/gogen"
     8  	"github.com/gobuffalo/packr/v2"
     9  )
    10  
    11  // New mailer generator. It will init the mailers directory if it doesn't already exist
    12  func New(opts *Options) (*genny.Group, error) {
    13  	gg := &genny.Group{}
    14  
    15  	if err := opts.Validate(); err != nil {
    16  		return gg, err
    17  	}
    18  
    19  	if !opts.SkipInit {
    20  		g, err := initGenerator(opts)
    21  		if err != nil {
    22  			return gg, err
    23  		}
    24  		gg.Add(g)
    25  	}
    26  
    27  	g := genny.New()
    28  	h := template.FuncMap{}
    29  	data := map[string]interface{}{
    30  		"opts": opts,
    31  	}
    32  	t := gogen.TemplateTransformer(data, h)
    33  	g.Transformer(t)
    34  
    35  	fn := opts.Name.File().String()
    36  	g.File(genny.NewFileS("mailers/"+fn+".go.tmpl", mailerTmpl))
    37  	g.File(genny.NewFileS("templates/mail/"+fn+".plush.html.tmpl", mailTmpl))
    38  	gg.Add(g)
    39  
    40  	return gg, nil
    41  }
    42  
    43  func initGenerator(opts *Options) (*genny.Generator, error) {
    44  	g := genny.New()
    45  
    46  	g.Box(packr.New("github.com/gobuffalo/buffalo/genny/mail/init/templates", "../mail/init/templates"))
    47  	h := template.FuncMap{}
    48  	data := map[string]interface{}{
    49  		"opts": opts,
    50  	}
    51  	t := gogen.TemplateTransformer(data, h)
    52  	g.Transformer(t)
    53  
    54  	g.Should = func(r *genny.Runner) bool {
    55  		_, err := r.FindFile("mailers/mailers.go")
    56  		return err != nil
    57  	}
    58  	opts.Name.Titleize()
    59  	return g, nil
    60  }
    61  
    62  const mailerTmpl = `package mailers
    63  
    64  import (
    65  	"github.com/gobuffalo/buffalo/render"
    66  	"github.com/gobuffalo/buffalo/mail"
    67  )
    68  
    69  func Send{{.opts.Name.Resource}}() error {
    70  	m := mail.NewMessage()
    71  
    72  	// fill in with your stuff:
    73  	m.Subject = "{{.opts.Name.Titleize}}"
    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 err
    79  	}
    80  	return smtp.Send(m)
    81  }
    82  `
    83  
    84  const mailTmpl = `<h2>{{.opts.Name.Titleize}}</h2>
    85  
    86  <h3>../templates/mail/{{.opts.Name.File}}.plush.html</h3>`