I am developing an application that needs to send out mails to customers. Part of the message should be populated with runtime values. And the remaining part is static. How can I achieve this? The static part can be changed.So I need to place the static part outside the programming logic.
Well, it looks like your project has two core issues: 1. sending email (via JavaMail or the simple mail transfer protocol (SMTP) for examples) 2. creating your email body (by merging the static info with the dynamic info)
How you go about both depend on what restrictions will be placed on your program. For instance, if you are making some kind of servlet that runs on GoDaddy, they won't allow you to use the SMTP I don't think. However, they do give you access to the java mail library so you can use that.
Personally, I prefer the SMTP method because it is fast and allows nice flexibility. But since it is not as widely allowed 'in the real world', I would suggest you go the JavaMail route. I haven't used it in a bit, so can't offer specifics, but I know that you can find some simple easy tutorials on using JavaMail. It's quite easy, you shouldn't have any difficulties barring strange firewalls or something.
For the second part of your project, creating the email body, perhaps you could try storing the static part of your email in a file. Here's an example:
Thank you for bla bla bla...
So, when it is time to send an email, your program can read in this form letter from the file into something such as a String or StringBuffer. Then, you can scan this String and look for your 'hotspots' such as [toName] and [fromName] and substitute them with your runtime variables:
A simple way of doing this would be to copy from the original (generic) String to a new String, token by token (where a token could be defined as any word separated by a space), until you come across a token that is a 'hotspot', and when you do, instead of writing the literal value of that token (the hotspot), write the runtime value that is supposed to replace it.
I know that using StringTokenizer is frowned upon these days.. another way of implementing that functionality is to use java.util.regex. You can split a string with a defined token (for instance a space) and then are given an array of the individual components of the string. That would be handy for you purpose I would think. I mentioned StringTokenizer though because I found it easier to learn.
Whew! Hope that gives you ideas!
posted 11 years ago
Thanks for your elaborate reply.
The first part of sending the mail has been done already, so the next part was composing the message.
Your suggestion defintely looks interesting and looks like a perfect fit for my requirement. I'll try and implement the same.