Sunday, 8 September 2013

Email Receiver using Java Mail API


In this tutorials we are going to see how to receive the email using java program.I used gmail SMTP server for receive email, you can use any SMTP server(provided by your host provider).The javax.mail.*; package used for receiving email, for that add latest version of mail.jar into your build path, I used javamail-1.4.7 version.Follow the simple steps for create simple email application for receiving using java
Create Java project called EmailReceiver in your eclipse IDE and then create package called com.javatutorialscorner.email.receiver under EmailReceiver project then create Java class called EmailReceiver .java under com.javatutorialscorner.email.receiver package.
EmailReceiver .java
package com.javatutorialscorner.email.receiver;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;

import com.sun.mail.pop3.POP3Store;

public class EmailReceiver {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

String host = "smtp.gmail.com";
String mailStoreType = "pop3";
String username = "yourmailid@gmail.com";
String password = "yourpassword";

try {
Properties receiverConfig = new Properties();
receiverConfig.put("mail.pop3.host", host);
Session session = Session.getDefaultInstance(receiverConfig);

POP3Store pop3Store = (POP3Store) session.getStore(mailStoreType);
pop3Store.connect(username, password);

Folder inbox = pop3Store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);

Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("************************************");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Message: "+ message.getContent().toString());
System.out.println("************************************");
}

inbox.close(false);
pop3Store.close();

} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

}

In this example POP3 protocol is used to receive email by java program.The Property is used to configure the POP3 configuration, The smtp.gmail.com is used as POP3 server.The session object contain information like host,port,username,etc..,The getDefaultInstance() method used to get session object.The POP3Store is used to connect POP3 server and The Folder class used to get INBOX folder

Now you can run the application and see the email message in your console.

Note:MIME Type message will be javax.mail.internet.MimeMultipart@488508 shown like this

0 comments

Post a Comment