Parse headers from template

Parse the processed template for headers and populates matching header
editors accordingly.
Those are then stripped from the template body before prepending it
and remaining header fields to the composer content.

The motivation for this is keeping receiver, sender and subject
lines in the template file and generating the message subject with the
date functions.
This commit is contained in:
Robert Günzler 2019-11-25 13:39:25 +01:00 committed by Drew DeVault
parent c1d57977af
commit 31e3e9f56e
1 changed files with 39 additions and 3 deletions

View File

@ -179,8 +179,7 @@ func (c *Composer) AddTemplate(template string, data interface{}) error {
if err != nil { if err != nil {
return err return err
} }
c.PrependContents(bytes.NewReader(templateText)) return c.addTemplate(bytes.NewReader(templateText))
return nil
} }
func (c *Composer) AddTemplateFromString(template string, data interface{}) error { func (c *Composer) AddTemplateFromString(template string, data interface{}) error {
@ -192,7 +191,44 @@ func (c *Composer) AddTemplateFromString(template string, data interface{}) erro
if err != nil { if err != nil {
return err return err
} }
c.PrependContents(bytes.NewReader(templateText)) return c.addTemplate(bytes.NewReader(templateText))
}
func (c *Composer) addTemplate(tmpl io.Reader) error {
reader, err := mail.CreateReader(tmpl)
if err != nil {
return errors.Wrap(err, "mail.CreateReader")
}
defer reader.Close()
// populate header editors
header := reader.Header
mhdr := (*message.Header)(&header.Header)
for _, editor := range c.editors {
if mhdr.Has(editor.name) {
editor.input.Set(mhdr.Get(editor.name))
mhdr.Del(editor.name)
}
}
part, err := reader.NextPart()
if err != nil {
return errors.Wrap(err, "reader.NextPart")
}
c.PrependContents(part.Body)
var (
headers string
fds = mhdr.Fields()
)
for fds.Next() {
headers += fmt.Sprintf("%s: %s\n", fds.Key(), fds.Value())
}
if headers != "" {
headers += "\n"
}
c.PrependContents(bytes.NewReader([]byte(headers)))
return nil return nil
} }