简体   繁体   中英

Email body with dynamic content in Java

I need to find a way how to send e-mails with dynamic content from my application in Java. In example:

Dear < Name > < Last name >, this is your new password < password >.

So when i send the mail the tags will change their values: < Name >= user's name, < Last name >=user's last name, < password >= user's password

So can somebody give me an advice or send me a link of some tutorial?

This involves the use of basic variables. Have a look at Sending Email using JavaMail API and use variables to set the users first and last name as well as their password as part of the body of the message.

Use java.text.MessageFormat .

String template = "Dear {0} {1}, this is your new password {2}.";
String message = MessageFormat.format(template, "Jeff", "Atwood", "killskeet");

Alternatively, use String#format() :

String template = "Dear %s %s, this is your new password %s.";
String message = String.format(template, "Jeff", "Atwood", "killskeet");

This only requires strict ordering of parameters.

You could build the message with a StringBuilder and insert the name, lastName, and password variables directly. Or you could write your message in a text file along with the variables (as you've written in your post) and parse the text file.

You can use apache velocity to send emails with dynamic content. No strict ordering of parameters is required. you just need place holders and set them in velocity context. The template engine will replace the dynamic content.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM