Swift-SMTP
Swift-SMTP copied to clipboard
HTML Body File Template with Variables
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?
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>
<% } %>
</p>
I would appreciate it if anyone has ideas on doing this. Thanks!
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.
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.
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?