This can be silly questions, but....
The code below works perfectly to retrieve all emails from gmail. However, after running the app once, gmail sets "Status: POP is enabled for all mail that has arrived since EXECUTION_APP_TIME" in its "Forwarding and POP/IMAP" settings and the app stops getting the old messages (that makes sense).
I need to get all messages from gmail every time I execute the app, but it only works once. Than I need to change the configuration in "Forwarding and POP/IMAP" to "Enable POP for all mail (even mail that's already been downloaded)" in my gmail after every single execution.
Does anyone know how I could sort it out?
Is there any way to set it automatically through code.
Here is the source code:
public void connect(){
Properties props = new Properties();
props.put("mail.pop3.host" , "pop.gmail.com");
props.put("mail.pop3.user" , username);
// Start SSL connection
props.put("mail.pop3.socketFactory" , 995 );
props.put("mail.pop3.socketFactory.class" , "javax.net.ssl.SSLSocketFactory" );
props.put("mail.pop3.port" , 995);
Log.e("asdasd", "teste");
Session session = Session.getDefaultInstance(props , new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication( username , password);
}
});
try {
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", 995 , username , password);
Folder fldr = store.getFolder("Inbox");
fldr.open(Folder.HOLDS_MESSAGES);
int totalMsg = fldr.getMessageCount();
int unread = fldr.getUnreadMessageCount();
System.out.println("Total MSG: " + totalMsg + " unreaed: " + unread );
Message[] messages = fldr.getMessages();
//Message[] msg = fldr.search(new FlagTerm(new Flags(Flag.SEEN), false));
Message[] msg = messages;
System.out.print("size " + messages .length);
if (messages.length == 0) System.out.println("No messages found.");
for (int i = 0; i < messages.length; i++) {
System.out.println("Subject : " + messages[i].getSubject());
if(messages[i].getSubject().equals("test223")){
System.out.println("Message " + (i + 1));
System.out.println("From : " + messages[i].getFrom()[0]);
System.out.println("Subject : " + messages[i].getSubject());
Object content = messages[i].getContent();
if (content instanceof String)
System.out.print((String)content);
/* text/plain = String
* multipart" = Multipart
* MimeMessage
* input stream = Unknown Data Handler
*/
Multipart multipart = (Multipart) msg[i].getContent();
for (int x = 0; x < multipart.getCount()-1; x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
System.out.println("Mail have some attachment : ");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
} else {
System.out.println(bodyPart.getContent());
}
}
}
}
fldr.close(true);
store.close();
} catch(Exception exc) {
System.out.println(exc + " error");
}
}
Related
I have written code checking the mail fetching the recipients calculating their lengths and based on that calculation forwarding the mail to the same id, its all working fine, but my mail is forwarded as attached mail. i don't want that. i want simple mail to be forwarded.
Please suggest where i am lacking
public class CheckingMail {
public static void main(String[] args) {
String host = "mycompanyname.com";
String mailStoreType = "pop3";
String username = "myemailid.com";
String password = "mypassword";
check(host, mailStoreType, username, password);
}
public static void check(String host, String mailStoreType,String username, String password) {
try {
System.out.println("\n\n1 creating the properties field");
//create properties field
Properties properties = new Properties();
properties.put("mail.pop3.host", host); //The POP3 server to connect to.
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
// Get a Session
Session emailSession = Session.getInstance(properties);
System.out.println("\n\n2 Get a Session="+emailSession);
System.out.println("\n\n3 create the POP3 store object and connect with the pop server");
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
// Store store = emailSession.getStore(mailStoreType);
store.connect(host,username,password);
System.out.println("\n\n4create the folder object and open it");
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
System.out.println("\n\n5 retrieve the messages from the folder in an array and print it");
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
System.out.println("\n before for loop");
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
// MimeMessage message = new MimeMessage(emailSession);
System.out.println("---------------------------------");
System.out.println("Email Number =" + (i + 1));
//System.out.println("To Recipients =" + message.getRecipients(Message.RecipientType.TO));
System.out.println("Subject = " + message.getSubject());
System.out.println("From =" + message.getFrom()[0]);
// System.out.println("Text =" + message.getContent().toString());
/*===================== To and CC starts here ===============================*/
Address[] address;
StringBuffer msg_buffer_to = new StringBuffer(50);
// TO
if ((address = message.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < address.length; j++) {
msg_buffer_to.append(address[j]);
System.out.println("\t\t\tTO " + address[j]);
}
}
StringBuffer msg_buffer_cc = new StringBuffer(50);
// CC
if ((address = message.getRecipients(Message.RecipientType.CC)) != null) {
for (int j = 0; j < address.length; j++) {
msg_buffer_cc.append(address[j]);
System.out.println("\t\t\tCC " + address[j]);
}
}
//counting the length here for both To and CC...
System.out.println("\n\n\t total length is== "+(msg_buffer_to.length()+msg_buffer_cc.length())+"\n\n");
/*************************************Merging of forward class***********************************************************/
if((msg_buffer_to.length()+msg_buffer_cc.length())>100)
{
System.out.println("\n\t Address length crossed the limits\t\n");
//forward mailing starts here
// Properties properties = new Properties();
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3s.host", "mycompanyname.com");
properties.put("mail.pop3s.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "mycompanyname.com");
properties.put("mail.smtp.port", "25");
Session session = Session.getInstance(properties,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mymailid.com","mypassword");
}
});
try{
// session.setDebug(true);
// Get a Store object and connect to the current host
// Create a Folder object and open the folder
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
if (messages.length != 0) {
// Get all the mail ids from the message
String from = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
if (from != null) {
System.out.println("From:" + from);
}
String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
if (to != null) {
System.out.println("To: " + to);
}
String subject = message.getSubject();
if (subject != null) {
System.out.println("Subject: " + subject);
}
Message forward = new MimeMessage(session);
// Fill in header
forward.setRecipients(Message.RecipientType.TO,InternetAddress.parse("mymailid.com"));
forward.setSubject("Fwd: " + message.getSubject());
forward.addFrom(InternetAddress.parse(from));
forward.setFrom(new InternetAddress("mymailid.com"));
// Create the message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
// Create a multipart message
Multipart multipart = new MimeMultipart();
// set content
messageBodyPart.setContent(message, "message/rfc822");
// Add part to multi part
multipart.addBodyPart(messageBodyPart);
// Associate multi-part with message
forward.setContent(multipart);
forward.saveChanges();
Transport.send(forward);
// Send the message by authenticating the SMTP server
// Create a Transport instance and call the sendMessage
System.out.println("message forwarded successfully....");
// } // end if
// }
}// end if
catch(Exception e) {
e.printStackTrace();
}
}
}
//close the store and folder objects
System.out.println("\n\n6 close the store and folder objects");
emailFolder.close(false);
store.close();
} catch (MessagingException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}![enter image description here](https://i.stack.imgur.com/EPe3t.jpg)
Sorry i am bit late for posting the complete solution for forwarding the mail on the basis of character length as the text mail instead of attached mail. Consider this as accepted answer. I hope it serves the purpose.
public class CheckingMail {
public static void main(String[] args) {
String host = "mycompanyname.com";
String mailStoreType = "pop3";
String username = "myemailid.com";
String password = "mypassword";
check(host, mailStoreType, username, password);
}
public static void check(String host, String mailStoreType,String username, String password) {
try {
System.out.println("\n\n1 creating the properties field");
Properties properties = new Properties();
properties.put("mail.pop3.host", host); //The POP3 server to connect to.
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getInstance(properties);
System.out.println("\n\n2 Get a Session="+emailSession);
System.out.println("\n\n3 create the POP3 store object and connect with the pop server");
Store store = emailSession.getStore("pop3s");
store.connect(host,username,password);
System.out.println("\n\n4create the folder object and open it");
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
System.out.println("\n\n5 retrieve the messages from the folder in an array and print it");
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
System.out.println("\n before for loop");
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("Email Number =" + (i + 1));
System.out.println("Subject = " + message.getSubject());
System.out.println("From =" + message.getFrom()[0]);
Address[] address;
StringBuffer msg_buffer_to = new StringBuffer(50);
if ((address = message.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < address.length; j++) {
msg_buffer_to.append(address[j]);
System.out.println("\t\t\tTO " + address[j]);
}
}
StringBuffer msg_buffer_cc = new StringBuffer(50);
if ((address = message.getRecipients(Message.RecipientType.CC)) != null) {
for (int j = 0; j < address.length; j++) {
msg_buffer_cc.append(address[j]);
System.out.println("\t\t\tCC " + address[j]);
}
}
System.out.println("\n\n\t total length is== "+(msg_buffer_to.length()+msg_buffer_cc.length())+"\n\n");
if((msg_buffer_to.length()+msg_buffer_cc.length())>100)
{
System.out.println("\n\t Address length crossed the limits\t\n");
properties.put("mail.store.protocol", "pop3");
properties.put("mail.pop3s.host", "mycompanyname.com");
properties.put("mail.pop3s.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
properties.put("mail.smtp.auth", "true");
properties.put("smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "mycompanyname.com");
properties.put("mail.smtp.port", "25");
Session session = Session.getInstance(properties,new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("mymailid.com","mypassword");
}
});
try{
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
if (messages.length != 0) {
String from = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
if (from != null) {
System.out.println("From:" + from);
}
String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));
if (to != null) {
System.out.println("To: " + to);
}
String subject = message.getSubject();
if (subject != null) {
System.out.println("Subject: " + subject);
}
Message forward = new MimeMessage(session);
forward.setRecipients(Message.RecipientType.TO,InternetAddress.parse("mymailid.com"));
forward.setSubject("Fwd: " + message.getSubject());
forward.addFrom(InternetAddress.parse(from));
forward.setFrom(new InternetAddress("mymailid.com"));
MimeBodyPart messageBodyPart = new MimeBodyPart();
Multipart multipart = new MimeMultipart();
messageBodyPart.setContent(message.getContent(), "message/rfc822");
multipart.addBodyPart(messageBodyPart);
forward.setContent(multipart);
forward.saveChanges();
Transport.send(forward);
System.out.println("message forwarded successfully....");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
System.out.println("\n\n6 close the store and folder objects");
emailFolder.close(false);
store.close();
} catch (MessagingException e){
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}
I am able to get mail subject and body contents using Java Api.
But in my application i received a template in an email which contains a url behind an image. I need to get that url, I found that the url was displayed when i view the source for that email manually.
Remember that i am not downloading the email instead i am connecting to mail server and then reading the mail data for any specific user
Is there a way that i can view the source of email like i am getting the subject of mail.
Here is the code:
import org.jsoup.Jsoup;
import javax.mail.*;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.util.Properties;
public class VerifyEmails {
public Message message;
public int i, n;
public String result;
public void check(String host, String user, String password) throws IOException, MessagingException {
Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.imap.user", user);
properties.put("mail.imap.port", "143");
properties.put("mail.imap.starttls.enable", "false");
Session emailSession = Session.getDefaultInstance(properties);
Store store = emailSession.getStore("imap");
System.out.println("test1 " + store);
store.connect(host, user, password);
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (i = 0, n = messages.length; i < n; i++) {
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("Email contents are :" + message.getContentType());
System.out.println("Email headers are :" + message.getContent());
}
if (message instanceof MimeMessage) {
MimeMessage m = (MimeMessage) message;
Object contentObject = message.getContent();
if (contentObject instanceof Multipart) {
BodyPart clearTextPart = null;
BodyPart htmlTextPart = null;
Multipart content = (Multipart) contentObject;
int count = content.getCount();
for (int i = 0; i < count; i++) {
BodyPart part = content.getBodyPart(i);
if (part.isMimeType("text/plain")) {
clearTextPart = part;
String test = String.valueOf(clearTextPart.getAllHeaders());
System.out.println("check1" + test);
break;
} else if (part.isMimeType("text/html")) {
htmlTextPart = part;
}
}
if (clearTextPart != null) {
result = (String) clearTextPart.getContent();
String test = String.valueOf(clearTextPart.getAllHeaders());
System.out.println("check2" + test);
System.out.println("plain text: " + result);
} else if (htmlTextPart != null) {
String html = (String) htmlTextPart.getContent();
result = Jsoup.parse(html).text();
System.out.println("html text: " + result);
}
} else if (contentObject instanceof String) // a simple text message
{
result = (String) contentObject;
System.out.println("String text: " + result);
} else // not a mime message
{
result = null;
System.out.println("null : " + result);
}
emailFolder.close(false);
store.close();
}
}
}
I am using the following code to successfully retrieve messages from my Gmail account.
// Import Statements
public class ConfirmEmail {
WebDriver driver;
Folder inbox;
String gmailID = "xxxxxxxxxxx#gmail.com";
String gmailPass = "xxxxxxxx";
String storeMessage;
public ConfirmEmail()
{
}
public void MailReader() {
System.out.println("Inside MailReader()...");
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
/* Set the mail properties */
Properties props = System.getProperties();
// Set manual Properties
props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.pop3.socketFactory.fallback", "false");
props.setProperty("mail.pop3.port", "995");
props.setProperty("mail.pop3.socketFactory.port", "995");
props.put("mail.pop3.host", "pop.gmail.com");
try
{
/* Create the session and get the store for read the mail. */
Session session = Session.getDefaultInstance(
System.getProperties(), null);
Store store = session.getStore("pop3");
store.connect("pop.gmail.com", 995, gmailID,
gmailPass);
/* Mention the folder name which you want to read. */
// inbox = store.getDefaultFolder();
// inbox = inbox.getFolder("INBOX");
inbox = store.getFolder("INBOX");
/* Open the inbox using store. */
inbox.open(Folder.READ_ONLY);
/* Get the messages which is unread in the Inbox */
Message messages[] = inbox.search(new FlagTerm(new Flags(
Flags.Flag.SEEN), false));
System.out.println("No. of Unread Messages : " + messages.length);
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try
{
printAllMessages(messages);
inbox.close(true);
store.close();
}
catch (Exception ex)
{
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
}
catch (MessagingException e)
{
System.out.println("Exception while connecting to server: "
+ e.getLocalizedMessage());
e.printStackTrace();
System.exit(2);
}
}
public void printAllMessages(Message[] msgs) throws Exception
{
for (int i = 0; i < msgs.length; i++)
{
System.out.println("MESSAGE #" + (i + 1) + ":");
printEnvelope(msgs[i]);
}
}
public void printEnvelope(Message message) throws Exception
{
Address[] a;
// FROM
if ((a = message.getFrom()) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("FROM: " + a[j].toString());
}
}
// TO
if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("TO: " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
Date sentDate = message.getSentDate(); // receivedDate is returning
// null. So used getSentDate()
String content = message.getContent().toString();
System.out.println("Subject : " + subject);
if (receivedDate != null) {
System.out.println("Received Date : " + receivedDate.toString());
}
System.out.println("Sent Date : " + sentDate.toString());
System.out.println("Content : " + content);
getContent(message);
}
public void getContent(Message msg)
{
try {
String contentType = msg.getContentType();
System.out.println("Content Type : " + contentType);
Multipart mp = (Multipart) msg.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++) {
dumpPart(mp.getBodyPart(i));
}
} catch (Exception ex) {
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
}
public void dumpPart(Part p) throws Exception {
// Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream)) {
is = new BufferedInputStream(is);
}
int c;
System.out.println("Message : ");
while ((c = is.read()) != -1) {
System.out.write(c);
}
}
}
With this code I am successfully able to print messages to console. Works flawlessly 100% of the time.
However, I need to store the "bodyPart" (i.e, the actual message or body of message) in a String so I could search the String using Regex. I need to extract links begining with http.
How can I convert the message to a string?
Thanks
I'm not quite sure what you are asking (because you said you already print out your Messages ... so when you print them, why can't you store them in a String?)
if you realy just want the bodyPart stored in a String variable:
Multipart mp = (Multipart) msg.getContent();
BodyPart bp = mp.getBodyPart(0);
String content = bp.getContent().toString();
I got all the mail, but I want to extract mail according to the date.
public void downloadEmailAttachments(String host, String port,String userName, String password) {
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", port);
properties.put("mail.pop3.user",userName);
properties.put("mail.password",password);
// SSL setting
properties.setProperty("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.pop3.socketFactory.fallback", "false");
properties.setProperty("mail.pop3.socketFactory.port",
String.valueOf(port));
Session session = Session.getDefaultInstance(properties);
try {
// connects to the message store
Store store = session.getStore("pop3");
store.connect(host,userName, password);//change here............
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
Message[] arrayMessages = folderInbox.getMessages();
for (int i = 0; i < arrayMessages.length; i++) {
Message message = arrayMessages[i];
Address[] fromAddress = message.getFrom();
String from = fromAddress[0].toString();
Address[]toAdress=message.getAllRecipients();
String to=toAdress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType().toString();
String messageContent = "";
// store attachment file name, separated by comma
String attachFiles = "";
if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
String fileName = part.getFileName();
attachFiles += fileName + ", ";
part.saveFile(saveDirectory + File.separator + fileName);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
if (attachFiles.length() > 1) {
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
}
} else if (contentType.contains("text/plain")
|| contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
// print out details of each message
System.out.println("Message #" + (i + 1) + ":");
System.out.println("\t From: " + from);
System.out.println("\t to: " + to);
System.out.println("\t Subject: " + subject);
System.out.println("\t Sent Date: " + sentDate);
System.out.println("\t Message: " + messageContent);
System.out.println("\t Attachments: " + attachFiles);
}
// disconnect...............
folderInbox.close(false);
store.close();
} catch (NoSuchProviderException ex) {
System.out.println("No provider for pop3.");
ex.printStackTrace();
} catch (MessagingException ex) {
System.out.println("Could not connect to the message store");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Searching for a period or in general by time is done by the server only if you use IMAP to connect.
Example:
SearchTerm term = null;
Calendar cal = null;
cal = Calendar.getInstance();
Date minDate = new Date(cal.getTimeInMillis()); //get today date
cal.add(Calendar.DAY_OF_MONTH, 1); //add 1 day
Date maxDate = new Date(cal.getTimeInMillis()); //get tomorrow date
ReceivedDateTerm minDateTerm = new ReceivedDateTerm(ComparisonTerm.GE, minDate);
ReceivedDateTerm maxDateTerm = new ReceivedDateTerm(ComparisonTerm.LE, maxDate);
term = new AndTerm(term, minDateTerm); //concat the search terms
term = new AndTerm(term, maxDateTerm);
Message messages[] = folderInbox.search(term); //search on the imap server
If you instead of IMAP use POP3, I guess your only choice is to filter (on the client) on the entire list of messages that you fetched from the server, iterating over it, like #user2310289 was telling you:
for (Message message : messages) {
if (message.getSentDate().after(minDate) && message.getSentDate().before(maxDate))
{
//do whatever you want with your filtered by period message
}
}
I hope I helped you.
While I am trying to connect through java mail
the server is responding unexpected
the problem is that sometimes the same program connects and get the mails but some times it throws
javax.mail.AuthenticationFailedException: EOF on socket at
com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:208) at
javax.mail.Service.connect(Service.java:295) at
javax.mail.Service.connect(Service.java:176) at
newpackage.PmsPOP3Client.main(PmsPOP3Client.java:44)
error
when server says
S: +OK Hello there.
C: CAPA
S: +OK Here's what I can do:
i can connect and fetch all mails
S: EOF
i cant even connect to server
my code
import java.util.*;
import javax.mail.*;
import javax.mail.event.ConnectionEvent;
import javax.mail.event.ConnectionListener;
import javax.mail.internet.*;
public class PmsPOP3Client {
public static void main(String[] args) throws Exception {
try {
String host = "host";
String user = "user";
String password = "pass";
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Store store = session.getStore("pop3");
System.out.println("store.getURLName() = " + store.getURLName());
store.connect(host, user, password);
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
String from = InternetAddress.toString(messages[i].getFrom());
if (from != null) {
System.out.println("From: " + from);
}
String replyTo = InternetAddress.toString(
messages[i].getReplyTo());
if (replyTo != null) {
System.out.println("Reply-to: " + replyTo);
}
String to = InternetAddress.toString(
messages[i].getRecipients(Message.RecipientType.TO));
if (to != null) {
System.out.println("To: " + to);
}
String cc = InternetAddress.toString(
messages[i].getRecipients(Message.RecipientType.CC));
if (cc != null) {
System.out.println("Cc: " + cc);
}
String bcc = InternetAddress.toString(
messages[i].getRecipients(Message.RecipientType.BCC));
if (bcc != null) {
System.out.println("Bcc: " + to);
}
String subject = messages[i].getSubject();
if (subject != null) {
System.out.println("Subject: " + subject);
}
Date sent = messages[i].getSentDate();
if (sent != null) {
System.out.println("Sent: " + sent);
}
Date received = messages[i].getReceivedDate();
if (received != null) {
System.out.println("Received: " + received);
}
System.out.println();
}
folder.close(true);
store.close();
} catch (Exception e) {
e.printStackTrace();
}
} }
You should probably try using pop3s as the protocal instead of pop3 as the following
Store store = session.getStore("pop3s");
You may need to check whether there is some port contention on your server. It may be either due to some other program using the same port sometimes and clashing with your own mail server. Check the server machine for firewall/virus scans/ etc which may block port temporarily and stopping the clients to connect.