开发者

How to format outgoing email - Create in code or use templates with replaceable values?

What is the best practice to create templates for outgoing email? Should I have each class create the html for the specific email? Should I have a text template with placeholders that are replaced by a common method?

In the first option, I'd have a sendEmail method that takes the formatted html string and send the email. Multiple classes would call this method after creating the html representation of the email.

In the second option, I'd envision having a number of text files like

<html>
  <title>{emailTitle}</title>
  Your user name is: {userName}
</html>

then a method that takes a hash map of keys, loads the appropriate text file and then replaces each key in the hash map with the value. This seems to have more flexibility as the code doesn't have to know anything about the html to create and you could change the email without changing code (only by removing values - adding a new key would require code changes).

What is the best practice to format email? Is there another option I should consider? I have to send four or five different types of emails - new registration, password reset,开发者_运维问答 order confirmation, etc.

I am using Java, but the question is fairly language agnostic - some languages may make it easier for templating, but I'm asking about normal best practices.


Templates are more flexible because (like you say) your designers can edit them without having to touch the code. More importantly, it enforces a separation between the business logic and the view.

So, this is definitely my preference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜