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 use JavaMail API to send and receive emails?

This tutorial looks to explain how one can make use of Java, in order to send and receive emails in a pretty simple manner. Also, before delving into the technicalities of the task at hand, we shall look into a fair bit of background information

We are all aware of the fact that one of biggest advantages brought about by the Internet, is the ability of instant communication, no matter where people may be located. With regards to this, there have certainly been so many developments on this front. Starting with instant messaging and video calling to the one of oldest forms, i.e. email, we have seen a great amount of progress being made. However, it is still definitely true that the most formal of all electronic forms of communication happens to the email. Now, while there are plenty of email services, both paid and free, one can always make use of Java, which is a powerful programming language, to build email applications that are platform, as well as protocol independent. This is exactly what we shall learn in the coming sections of this article.

What if JavaMail API?

An API, or Application Programming Interface, is basically a bunch of tools and rules that is meant for the development of software applications.

In a similar way, the JavaMail API is one that offers email sending and fetching abilities in Java-based applications. The framework it provides is platform and protocol independent for building messaging and mail applications. It basically consists of abstract classes, which define objects for a mail system. The API, as such, happens to be an optional package, allowing for composing, sending and reading emails.

What you need to know?

JavaMail API, being based on the Java programming language, is easy to use if you are competent with the basics of Java. This will also make it easier for you to learn how the API framework can be used fully.

Setting up the environment

When you are looking to send emails with a Java application, the process happens to be fairly simple enough. However, almost all applications require some kind of an environment to run on and so is the case here. You will need to install the JavaMail API and also the Java Activation Framework in your machine first. However, if you happen to be using Java SE 6 or higher, it is not required that you have the Java Activation Framework in your computer.

Both of these though, can be downloaded from Java’s official website. After downloading them, you will need to unzip them. The top level directories will have several jar files belonging to these applications. You must add the activation.jar and mail.jar files to your CLASSPATH.

The SMTP server

In order to be able to send emails, we make use of the SMTP (Simple Mail Transfer Protocol) server. This can be done in a few ways.

  • You can install and make use of Apache James or Postfix server, by installing them.
  • You can also choose to make use of the SMTP server provided by the host for free.
  • Another option to go with is make use of the SMTP server provided by companies, like yahoo or Gmail.

Here, we have chosen to go with the second option. We make use of the JangoSMTP server to send emails. Visit the site, create and account and then configure your email address.

Figure 1. Jango SMTP settings

Now that we are aware of the few basic prerequisites, we shall learn how to send a simple email using JavaMail API.

Sending simple emails

The sending process of a simple email comprises of a few basic steps, which are mentioned below.

  • The first step is to get a session.
  • Then, go on to create a MimeMessage in default message, and set the details, like Subject, from, and to.
  • Then, the actual message is set, like – message.setText(“write here”);
  • The final step is to use the Transport object to send the message.

Creating the Java Class

We shall create a Java class file named Emailsend, with the contents given below. Let us have a look at different parts of the code.

Listing 1. Showing Emailsend.java

The below defined code is mainly to import all the various packages that we shall be requiring in our code.

packagejavamaildemo;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

Now we will have the main class to execute the function. Here we are setting the properties, authentication details, session objects etc.

public class Emailsend {
    public static void main(String[] args) {
        // The email ID of the recipientis to be mentioned here.
        String to = "emailrecipient@yahoomail.com";
        // The email ID of the recipient is to be mentioned here.
        String from = "emailsender@outlook.com";
        final String username = "keithsoloman"; //change as per your setting
        final String password = "**********"; //change as per your setting
        // Taking into consideration that you are sending the email through relay.jangosmtp.net
        String host = "relay.jangosmtp.net";
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", "25");
        // Getting the Session object.
        Session sesion = Session.getInstance(props,
            new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
        try {
            // Creation of a default MimeMessage object.
            Message msge = new MimeMessage(sesion);
            // Setting From: the header field of the header.
            msge.setFrom(new InternetAddress(from));
            // Setting To: the header field of the header.
            msge.setRecipients(Message.RecipientType.TO,
                InternetAddress.parse(to));
            // Setting the Subject: the header field
            msge.setSubject("Testing of Subject for JavaMail");
            // Now, we set the actual message to be sent
            msge.setText("Hello!This is a sample testing message to check" +
                "email sending using JavaMailAPI ");
            // Sending of the message
            Transport.send(msge);
            System.out.println("The message has been successfully sent....");
        } catch (MessagingException excp) {
            throw new RuntimeException(excp);
        }
    }
}

Since we are making use of the SMTP server that is offered by JangoSMTP, which is of course the host here, the username and password is necessary to be authenticated. Authentication of the password is done by thejavax.mail.PasswordAuthentication class.

Compilation and running

Just like any other program, once the code is ready, we should look to compile and run it to see where it stands. Here, we have saved the file Emailsend.java in the directory - /home/keithsolomon/JavaMailAPITEST. Since the jar files, javax.mail.jar and activation.jar are already in the CLASSPATH, we do not need to include them again. Now, we use the following command for the compilation process.

javac -cp /home/keithsolomon/activation.jar:/home/keithsolomon/javax.mail.jar: Emailsend.java

After the compilation process, we then run the code.

java -cp/home/keithsolomon/activation.jar:/home/keithsolomon/javax.mail.jar: Emailsend

On executing the above command, you will see a message on your console, like

The message has been successfully sent....

Verifying the output

Now, since we have sent the email message to the destination email, we can log into it and then check for the message in the inbox.

Receiving emails

We have just learnt how to send emails using the JavaMail API. Now, we shall delve into how you can receive emails via this application framework.

Here, we shall look to write a Java class file names Emailfetch, which is capable of reading the several kinds of emails, like –

  • Basic simple emails.
  • Emails that bear attachments.
  • And, emails that have an inline image.

The steps that we take to implement the receiving of emails are –

  • Getting the Session object is the very first step, just like while sending.
  • Creation of a POP3 store and then a connection to it.
  • Creation of a Folder object and opening of the same in the mailbox.
  • Retrieval of messages.
  • Closing the folder and then storing objects.

Creating the Java Class

We basically create a Java class file by the name of Emailfetch, with the contents given below.

Listing 2. Example showing Emailfetch.java

package javamaildemo;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Store;

Again here, we are importing a large number of packages and classes that we shall need in this part of the program.

public class Emailfetch {
    public static void fetch(String hostpop3, String storagetype, String usr,
            String passwrd) {
            try {
                // creating the properties field
                Properties propts = new Properties();
                propts.put("mail.store.protocol", "pop3");
                propts.put("mail.pop3.host", hostpop3);
                propts.put("mail.pop3.port", "995");
                propts.put("mail.pop3.starttls.enable", "true");
                Session emailsesion = Session.getDefaultInstance(propts);
                emailsesion.setDebug(true);
                

The above part of the code is meant for the creation of the POP3 store object and the establishing a connection with the POP server.

                    Store storage = emailsesion.getStore("pop3s");
                    storage.connect(hostpop3, usr, passwrd);
                    Folder mailfolder = store.getFolder("INBOX");
                    mailfolder.open(Folder.READ_ONLY);
                    

Here, we have just created the folder object mailfolder that is used for storing the fetched emails and then opened it for read - only access.

                        BufferedReader brread = new BufferedReader(new InputStreamReader(
                            System.in));
                        

Further, we go ahead and retrieve the messages from the folder in an array, msges, and print it.

                            Message[] msges = mailfolder.getMessages();
                            System.out.println("msges.length is -" + msges.length);
                            for (int a = 0; a & lt; msges.length; a++) {
                                Message msges = msges[a];
                                System.out.println("*******************************");
                                writeportion(msges);
                                String lines = brread.readLine();
                                if ("YES".equals(lines)) {
                                    msge.writeTo(System.out);
                                } else if ("QUIT".equals(brread)) {
                                    break;
                                }
                            }
                            emailfolder.close(false);
                            storage.close();
                        }

Now, we just close the storage and the folder objects after the retrieval process.

catch (NoSuchProviderException excp) {
    excp.printStackTrace();
} catch (MessagingException excp) {
    excp.printStackTrace();
} catch (IOException excp) {
    excp.printStackTrace();
} catch (Exception excp) {
    excp.printStackTrace();
}
}

public static void main(String[] args) {
        String hosting = "pop.outlook.com"; // change as per need
        String mailStorage = "pop3";
        String usrname =
            "yournamehere@outlook.com"; // change as per need
        String passwrd = "***********"; // change as per need

After we have mentioned the host, email address and password, we are calling the method fetching. This method is meant for checking the content type, following which, it processes and fetches content of messages.

    fetching(hosting, mailStorage, usrname, passwrd);
}
public static void writeportion(Part p) throws Exception {
        if (p instanceof Message) //Callingthe method writeenvelope
            writeenvelope((Message) p);
        System.out.println("******************************");
        System.out.println("TYPE of CONTENT: " + p.getContentType());

Here, we are checking if the content is in plain text.

      
if (p.isMimeType("text/plain")) {
	System.out.println("This is in simple plain text");
    System.out.println("*************************");
    System.out.println((String) p.getContent());
} 

Here, we are checking if the email is has any attachments and then fetching them.

 
else if (p.isMimeType("multipart/*")) {
	System.out.println("This has a multipart");
    System.out.println("*************************");
    Multipart mpart = (Multipart) p.getContent();
    int counter = mpart.getCount();
    for (int b = 0; b< count; b++)
    writeportion(mpart.getBodyPart(b));
} 

In this part, we check if the content happens to be a nested message.

      
else if (p.isMimeType("message/rfc822")) {
	System.out.println("This is a nested message!");
    System.out.println("*************************");
    writeportion((Part) p.getContent());
} 

We also check for any inline image in the content.

     else if (p.isMimeType("image/jpeg")) {
         System.out.println("*************************> image/jpeg");
         Object obj = p.getContent();
         InputStream xyz = (InputStream) obj;
         // Construction of the byte array required
         System.out.println("xyz.length = " + xyz.available());
         while ((a = (int)((InputStream) xyz).available()) & gt; 0) {
             int rslt = (int)(((InputStream) xyz).read(bArray));
             if (result == -1)
                 int a = 0;
             byte[] barray = new byte[xyz.available()];
    
             break;
         }
         FileOutputStream fil = new FileOutputStream("/tmp/image.jpg");
         fil.write(barray);
     } else if (p.getContentType().contains("image/")) {
         System.out.println("Type of content " + p.getContentType());
         File fi = new File("image" + new Date().getTime() + ".jpg");
         DataOutputStream out = new DataOutputStream(
             new BufferedOutputStream(new FileOutputStream(fi)));
         com.sun.mail.util.BASE64DecoderStream test =
             (com.sun.mail.util.BASE64DecoderStream) p
             .getContent();
         byte[] buffr = new byte[1024];
         int bytesread;
         while ((bytesread = test.read(buffr)) != -1) {
             output.write(buffr, 0, bytesread);
         }
     } else {
         Object obj = p.getContent();
         if (obj instanceof String) {
             System.out.println("This is a string.");
             System.out.println("****************************");
             System.out.println((String) obj);
         } else if (obj instanceof InputStream) {
             System.out.println("This is just an input stream.");
             System.out.println("****************************");
             InputStream is = (InputStream) obj;
             is = (InputStream) obj;
             int c1;
             while ((c1 = is.read()) != -1)
                 System.out.write(c1);
         } else {
             System.out.println("This is an unknown type.");
             System.out.println("****************************");
             System.out.println(obj.toString());
         }
     }
 }

This method will print FROM, TO and SUBJECT of the email messages.

    public static void writeenvelope(Message m1) throws Exception {
        System.out.println("This is the message envelope");
        System.out.println("***************************");
        Address[] add;
        // FROM
        if ((add = m1.getFrom()) != null) {
            for (int i = 0; i & lt; add.length; i++)
                System.out.println("FROM: " + add[i].toString());
        }
        // TO
        if ((add = m1.getRecipients(Message.RecipientType.TO)) != null) {
            for (int i = 0; i & lt; add.length; i++)
                System.out.println("TO: " + add[i].toString());
        }
        // SUBJECT
        if (m1.getSubject() != null)
            System.out.println("SUBJECT: " + m1.getSubject());
    }
}

Compiling and running

Once you compile and run the above code, using the same process as we did with the first example, you shall get the output.

Conclusion

The above example can very easily teach you the process of how to send and receive emails, making use of the JavaMail API. The process can be adopted when you are looking to use it for the development of mail and messaging applications.



Website: www.techalpine.com Have 16 years of experience as a technical architect and software consultant in enterprise application and product development. Have interest in new technology and innovation area along with technical...

What did you think of this post?
Services
[Close]
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
[Close]
You must be logged to download.

Click here to login