You are on page 1of 3

Date: 20/10/2021

POP3 Protocol

Aim
To write a java program to read a message from inbox using POP3 protocol
Code
package mailtransfer;
import java.util.Properties;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.FlagTerm;

public class JavaMailPop3Reader {

public static void main(String args[]) throws Exception {


Scanner cin=new Scanner(System.in);
String host = "pop.gmail.com";
String user = "subhikshamaheshwari@gmail.com";
String password = "diamondring@506099";

System.out.println("----------------------");
System.out.println("POP3 Protocol");
System.out.println("----------------------");
Properties props = new Properties();
props.put("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.pop3.socketFactory.fallback", "false");
props.put("mail.pop3.socketFactory.port", "995");
props.put("mail.pop3.port", "995");
props.put("mail.pop3.host", "pop.gmail.com");
props.put("mail.pop3.user", user);

1
props.put("mail.store.protocol", "pop3");

// Creates a javax.mail.Authenticator
object. Authenticator auth = new
Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password);
}
};

// Creating mail session.


Session session = Session.getDefaultInstance(props, auth);

// Get the POP3 store provider and connect to the


store. Store store = session.getStore("pop3");
store.connect("pop.gmail.com", user, password);

// Get folder and open the INBOX folder in the store.


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

// Retrieve the messages from the folder.

int messageCount = inbox.getMessageCount();


System.out.println("\nTotal Messages in your inbox: " + messageCount+"\n");
//Message[] messages = inbox.getMessages();
System.out.println("Enter Number of message to print: ");
int num=Integer.parseInt(cin.nextLine());
int startMessage = messageCount-num;
int endMessage = messageCount;
Message[] messages = inbox.getMessages(startMessage, endMessage);
for (Message message : messages) {
boolean isMessageRead = true;
for (Flags.Flag flag : message.getFlags().getSystemFlags()) {
if (flag == Flags.Flag.SEEN) {
2
isMessageRead = true;
break;
}
}
message.setFlag(Flags.Flag.SEEN, true);
System.out.println("Subject: "+message.getSubject() +"\nStatus "
+ (isMessageRead ? " [READ]" : " [UNREAD]"));
}
inbox.close(true);
System.out.println("Done. . .");
store.close();
}
}
Output

Result
Thus ,the implementation of POP3 protocol was executed successfully and got the desired output

You might also like