Swift-SMTP icon indicating copy to clipboard operation
Swift-SMTP copied to clipboard

HTML Body File Template with Variables

Open MattTimmons opened this issue 2 years ago • 4 comments

Other SMTP / email libraries for JS or Python have the ability to "render" an html files and pass through variables.

ie.. pseudo code:

var htmlTemplate =  fs.readFileSync('./views/email-welcome.html', 'utf-8')

data = {
	orgName: organizationName,
	orgTitle: orgTitle,
	email: email,
}
var emailHTML = ejs.render(htmlTemplate, data);
_sendMailgunEmail(from, email, 'Welcome to my app!', emailHTML);

I know I can pass html as a string and use variable that way, but that would make a for a lot in one file. Any other suggestions or could something like this be possible as feature request?

MattTimmons avatar Dec 27 '21 15:12 MattTimmons

To add a bit more. I know I can load in an html file as string and use it..

let emailTemplateFile = Bundle.main.path(forResource: "myemail", ofType: "html")!
let contents = try? String(contentsOfFile: emailTemplateFile)
        
let htmlContent = Attachment(htmlContent: contents!)
let mail = Mail(
     from: fromEmail,
     to:emailUsers,
     cc: [],
     subject: "some email test",
     attachments: [htmlContent]
)

And then use a simple stringReplace to handle inline variables. However, one nice thing about the others is you can use bool/conditionals in your email templates as they render. Ie..

<p>
<% if (!userExists) { %>
	<strong>NOTE:</strong> You may need to change your password after you first log in.<br>
	Your temporary password:<br>
	<strong><%- password %></strong><br>
	&nbsp;
<% } %>
</p>

I would appreciate it if anyone has ideas on doing this. Thanks!

MattTimmons avatar Dec 27 '21 18:12 MattTimmons

For relatively simple use cases, perhaps you can keep your text/html in a struct. For example, something like this:

struct Message: CustomStringConvertible {
   let username: String
  var description: String {
    "Hello \(username)!  How are you?"
  }
}

When it comes to mailing then you should simply use Message(username: "Charlie").

If you really want to be able to read the contents from a file, you could perhaps use Codable and load from a JSON or have a custom Decoder. Or you could use a templating system like Stencil or Tuxedo.

dannys42 avatar Jan 01 '22 00:01 dannys42

I will look more into this. Loops are another good use for this.. like building a list of things in an email, all things I have come across recently. For simple things, like a username and one-time string, are fine, but more complex is obviously more difficult. I just thought I would highlight to desire to have something similar in this framework.

MattTimmons avatar Jan 01 '22 21:01 MattTimmons

Kitura already has a template engine in place for the web server component -- is it reasonable to try using Stencil, or does that wind up pulling in other unnecessary stuff?

sbeitzel avatar Jan 11 '22 00:01 sbeitzel