简体   繁体   中英

Send email via outlook with mail merge using Java

I have a set of contacts in my database. I want my application to build a custom email template for my clients.

My client can set a custom placeholders such as company name, address:

For example:

Dear <<name>>,

This is to inform you that our <<company name>>, located in  <<address>> ...

Sincerely,
<<sender>>

After the template is setup I can then use this as a body to my email. Recipients are then fetched from the database.

I am aware of the java.awt.Desktop package which allows me to create a MAIL URI and open it using the user's default email client. The problem is how can I incorporate the mail merge into it? Can you please guide me on existing libraries or solutions to this?

Use the JavaMail library for sending mails. You will find plenty of examples if you search for "JavaMail example", among others: Sending email via Gmail SMTP example . Regarding the placeholders I would simply use the String.replace function.

  1. You will need to control how the variables in the template are setup. I dont think you can parse an arbitrary string and find out if there are variables in it. Hence when a user is adding a variable, make sure that you insert a variable that your program will understand into the email body. Thats a no brainer but thought I'll add it for completeness.

  2. You could save the email body as a velocity template, making sure the variables you added our velocity templating language compliant. Velocity would be easier than string.replace() if there are complicated templates that are being set up. If its a simple one then String.replace() would do. http://velocity.apache.org/

  3. Next use the java mail library to send it directly from your java program, or launch the default email client of the box using the Desktop class.

EDIT:

If you would like to open outlook then you will need to use Desktop.mail() API. You can pre-populate the to,cc, bcc, subject and body fields in the outlook send email window by constructing an appropriate URI and passing it to Desktop.mail()

 mailto:duke@sun.com?SUBJECT=Happy New Year!&BODY=Happy New Year, Duke!

Have a look here for more info: http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/

For multiple recipients, separating the email addresses with commas should work. If that doesn't, try with a semi colon. Outlook uses semicolon..

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