Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login

You must be logged to download. Click here to login


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation


MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to process email using JavaMail API

The tutorial intend to cover the processing of emails making use of Java APIs

There is one attribute that each and every web applications has which is the potential to send the email. The email could be a successful registration of the user, welcome message, reminder of the password, confirmation of the order etc. The content of these emails could differ from message to message however each of these messages could have a different processing technique. A message needs to be constructed, transmit it to the mail server and then it is delivered.

In order to program in Java, one of the most common is the JavaMail API that is used to connect to the server and then deliver the email to the recipient. The disadvantage of this technique is that in case you make use of this API more than once then the need is to make use f the wrapper. Based on the way of writing the code, the wrapper is made use of in order to deliver the mail of one type. It could be the password reminder, welcome mail or any other category of email.

A look at the Email Templates

Java Mail API

Figure 1: Java Mail API

We will now look at the template of the email that comprises of the XML files. This contains a root element as well as the siblings of the same where in we have the root as the and siblings as subject, body and from element.

Also we have the non-mandatory elements known by the name of to, cc as well bcc. We all make use of email client in our day to day lives and are well acquainted with the definition of these elements. We can make use of these optional elements as well in case we want to incorporate more than one address in our email. The below lists one of the templates of email:

Listing 1: Email Template

    <subject>This is the subject of the email message</subject> 
    <body>This is the body of email .</body> 

Modification of the email templates

We need to keep in mind the features provided by the property files, one of them is the usage of MessageFormat class. This is used in order to replace the placeholders in the properties. The replacement is done with the values passed at the time of implementation. Assume in case the errors are being put in the property file, one of the error is of the file not being found, then the property can be written like as below:

Listing 2: Error Handling in Property File

file.not.found.err=Error,file could not be find {0}.
At compile and run time, make use of MsgFormat as below:

ResBundle bundle = ResBundle.getBundle(
	"MyProps", currentLocal); 
Object argument    = { "sample file.txt" }; 
String newString      = MsgFormat.format(

Finally we will have newString containing the error. The error could be something like could not find file some_file.txt. We have the MessageFormat that has the potential to format any string. This means that we can incorporate the same tokens and utilize them in a property file. This is incorporated in the subject and body elements of the email template we are using.

How to process the email?

Post the creation of the email template, time now is to process the same. We can select multiple libraries that can be used to process our email. The benefit of these libraries is that an easy route is identified for the mapping of the elements that are present in the XML file. The mapping is done to a data structure. Let us look at the advantage of using the same which enables to pick out the required elements from the XML document. This is done without the need to parse the elements.

The below lists the method that has the potential to read the data from the file: This is then copied to the email template.

Listing 3: Method to read the data from the file

public static getEmailTemplate(InputStream) 
    Parse parse = new parse(); 
    parse.addObjectCreate("email", EmailTemplate.class); 
    parse.addBeanPropertySetter("email/subject", "subject"); 
    parse.addBeanPropertySetter("email/body", "body"); 
    parse.addBeanPropertySetter("email/from", "from"); 
    parse.addCallMethod("email/to", "addTo", 0); 
    parse.addCallMethod("email/cc", "addCc", 0); 
    parse.addCallMethod("email/bcc", "addBcc", 0); 
        return (EmailTemplate)parse(Stream); 
    catch (Exception e) 
        log.error("Error: ", e); 
        return null; 
    catch (Exception e) 
        log.error("Error: ", e); 
        return null; 

The example listed above needs to be understood very carefully. The very first step we saw is to initiate the object and then trigger the methods. This triggering is used to set up the rules of the data mapping. We initiated the addObjectCreate() method, that is required so as to set the rule. This is done in order to generate the object EmailTemplate. This is done every time the element of the email is faced.

A look at the remainder of EmailTemplate Class

getEmailTemplate() method is generally regarded as to the prime element of the template of the email. Other than this, all the other attributes are mere properties. We have good number of string properties hereby, primarily three.

These three properties are: the body, subject, and from address. Also we have three ArrayList properties by the name of to, CC, and BCC lists. All these properties comprises of the strings as members. Also we have getters and setters listed for all these properties and then we have "add" methods that are being used for the collections. There are three additional convenience methods: getToAddresses(), getCcAddresses(), and getBccAddresses(). As far as the JavaMail API is concerned, the addresses are transmitted in the traditional type of arrays and then we have these sorts of methods that are normally made use of to convert the ArrayLists of String objects into the arrays. These arrays are generally required by JavaMail.

Glance at EmailSender

Post the parsing of the email template, we are now ready to deliver the email. We have an EmailSender class that comprises of static as well as the overloaded method. These overloaded methods are sendEmail(). We have quite a good number of ways in order to call the method:

Listing 4: EmailSender

public static void sendEmailMessage( 
    String To, 
    EmailTemplate Template, 
    String[] Args)

These arguments are generally self explanatory, lists To as the first address for the email and we can always make use of the recipient addresses in our email templates. However in majority of the cases, the need is to define the address of the recipient. This is to be done at the run time. Example, in case you need to get the welcome email, then it needs to be sending to the email of the recipient address.

Talking about the second argument, it is the EmailTemplate and then we have final arguments list, used to pass to MessageFormat. This is done when the subject and body of the email is parsed. It all depends on the code that is being triggered so as to come up with the array of information that is being made use of to customize the template of the email. There are lot of other methods as well which is used to make the triggering of method easy and simpler.

For the reason that all of the CC: as well as the BCC: addresses needs to be defined and that too within the template of the email, managing the same is very easy, we make use of the methods in the EmailTemplate class. This then incorporates other recipients as well to the email.

Alternate way of processing email

Let us see how to process the email templates making use of the servlet. Below lists the code to do the same:

Listing 5: Email template with servlet

// Get the email template. 
InputStream template = 
EmailTemplate alert = .getEmailTemplate(template); 
// This is used to come up with the email body section that comprises of the real time data of the user. 
String[] args = { "Sender" }; 
EmailSender.sendEmail("", alert, args);

As seen above, the very first step is to make use of this approach by converting the template into the Input Stream. Since we are making use of the servlet, we here get the file from the ServletContext. Though we have some good number of ways as well in order to achieve this, this one is the best to use. Post this, we need to pass the InputStream to the EmailTemplate.getEmailTemplate() method and then we just need to set up the arguments array in order to formalise the email therby triggering the EmailSender.sendEmail() method.


This concludes the tutorial on the email processing making use of JavaMail API. See you next time.

Software developer with more than 5 years of development on Java, HTML, CSS.

What did you think of this post?
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!

> More info about MrBool Credits
You must be logged to download.

Click here to login