How to write java program to read new emails from any emailid - java

Hi I want to write a java program where I will provide my email id and password. and I want to read all new unread messages that arrived to that email id. I donot know how to write program for that.
The below program works fine for gmail. but it does not work for yahoomail because for yahoo pop3 is not configured. I want a generic code which will work for all email id.
import java.io.*;
import java.util.*;
import javax.mail.*;
public class ReadMail {
public static void main(String args[]) throws Exception {
// String host = "pop.gmail.com";
// String user = "xyz";
// String password = "12345";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
}

You need to know more than just login-pass. Things like mail server address, mail server type, port for connections, etc.
You should probably check out Java Mail API, or Commons Email.
UPD:
You create a Session using Session.getDefaultInstance() method (which takes connection Properties object and authenticator), get a Store from this Session using Session.getStore() method, get a Folder from that store using Store.getFolder("FOLDER_NAME") method, open that Folder, using Folder.open(Folder.READ) method, and get all messages, using something like Message[] messages = inboxFolder.getMessages();
Is that what you were looking for?
UPD2:
There is simply no way to write a generic program, which will work with any mail provider, using just server path, userID and password. Because different mail servers are configured differently. They talk differen protocols (imap/pop3/pop3 ssl) on different ports. There's always some guy, who has configured his mail server to talk imap over ssl on 31337 port only, all the other ports and protocols are banned. And this guy breaks your program. So, you'll have to specify all this properties in your properties object. Look here for properties, you'll have to specify.
UPD3:
On second thought, you actually have one option. Just try connecting to the server using different protocols. If that does not help, start iterating through ports. The one that fits is your configuration. If that's really what you want.

You need the javax.mail package, and the documentation of it. Read the documentation. Then you know.

There are two ways to do it:
1) Google provides API's to access mail you could use that library which provides more control over your mails. See here: http://code.google.com/apis/gmail/. In the same way try for other email providers.
2) Simple mail client(you could find it easily googling), but you need to look at headers to identify which mails are read/unread etc.

You need a registry where you can get the properties for a given mail service.
For instance, instead of specifying a pop3 host, you could specify the name of a .properties file that would contain the host, the port, the protocol, etc...
If your .properties file contains the protocol, for instance mail.store.protocol=pop3, you could use session.getStore() (with no argument), and the same code could be used for pop3, imap, pop3s, imaps.

Related

FTPSClient, What values to give for Remote and Local

I am new to FTPSClient i trying to connect to a FTPS created in my laptop. i don't exactly what some of the methods working and their parameter meaning.
For example,
In my code i have created a FTPSClient as below:
FTPSClient ftps =new FTPSClient();
Then connected to a server use connect() method with ip address.
ftps.connect("172.xx.xx.xxx");
After every step i will check the reply code using.
ftps.getReplyCode();
In the below code i know that
username = system username
password = the password to login
ftps.login(username, password);
In the my system in Internet Information Service(IIS). Created an ftp server with ssl and given the below directory to share.
C:\Users\karan-pt2843\Desktop\FTPS
Want to send the file in below directory to the server.
D:\sam.txt
Now i want to store a file in the server in the given above directory and i tried using
remote="";
local="";
InputStream input;
input = new FileInputStream(local);
ftps.storeFile(remote, input);
input.close();
I don't know what value to give for remote and local. please help me with the values to give on them and the what happens internal.
// Use passive mode as default because most of us are
// behind firewalls these days.
ftps.enterLocalPassiveMode();
...
String remote = "samFromClient.txt"; //Place on FTP
String input = "D:/sam.txt" //Place on your Client
//Your FTP reads from the inputstream and store the file on remote-path
InputStream input = new InputStream(new FileInputStream(input));
ftps.storeFile(remote, input);
input.close();
ftps.logout();
...
Taken from: Apache example

Why iterating over all java mail user's folders very slow?

Properties props = System.getProperties();
props.put("mail.imap.connectiontimeout",5000);
Session session = Session.getInstance(props);
Store store = session.getStore("imap");
for(50K users){
//login,password changed in loop
String[] folders = {"inbox", "f1", "f2", "f3", "spam"};
store.connect(serverAddress, login + emailSuffix, password);
for (int i = 0; i < folders.length; i++) {
Folder x = store.getFolder(folders[i]);
x.open(Folder.READ_ONLY);
System.out.println("folder " + folders[i] + " of " + login);
x.getUnreadMessageCount();
x.close(false);
}
store.close();
}
I'm using same store for all connections, changed service_count in dovecot according to this answer in order to improve imap-dovecot performance but I see only first iteration and after that code hangs or does next system.out after long time.
Actually, I need to grab all old messages of all users + count all unread messages as I want to migrate from pure Java Mail to some custom format. I didn;t manage even to just iterate over all users and folders for each user because even simple store.connect hangs after 1-st iteration!
I personally think that bottleneck is my dovecot config, but it uses default limits (1000 connections) which looks good.
My I somehow improve my dovecot or connect my store only once for all users or somehow fetch all messages of all users and unreadMessagesCount of all users in other way?
PS. The only alternative to programmatic way is some bash script in maildir which whill read each message from file system and pass it to some rest which converts to my custom format) but it much more harder than Java it's too difficult to parse smptp, parse seen flags from file name and so on.
UPDATE
I found apache commons net imapclient which works very fast.
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
My code is the following
IMAPClient client = new IMAPClient();
client.connect("localhost");
for(50K users){
client.login(login + emailSuffix, password);
for (int i = 0; i < folders.length; i++) {
System.out.println(client.select("INBOX"); //prints true, it's ok
}
}
Looks like it connects faster than java mailapi because it may
connect once to host and after that login for each user. May I somehow repeat such behavior in JavaMail API?
How may I grab messages with apache commons client? All methods return boolean or void, so it's looks like just server checking library am I right? Is it possible to somehow get useful info from imapclient?
Finally solved my problem by simple iterating over file system (I have maildir format).
I guess Java Mail API makes new dovecot auth for each user in store.connect while it should just connect once (consume dovecot auth) and after that login for each user (consume dovecot imap-login). That's why I waited 1 minute for each iteration - it's std idle for auth process in dovecot config. I'm not sure but looks so.
Apache lib works fast but it's just testing library for pinging server, checking connection and other imap operations. It returns boolean result about operations but not useful information(

Paho client for java generating folder like paho101658642587966-tcp1270011883. what is the importance of this?

I am using Paho client for java to connect to activeMq over mqtt. I noticed one strange thing. There are several folder created having names like "paho101658642587966-tcp1270011883" and having empty .lck files. Why are these used and when are they created.
These files are created to store inflight messages for QOS2 message before their delivery to the broker can be confirmed.
They are created by the MQTTDefaultFilePersistence class, you can change the directory name and path by creating your own MQTTDefaultFilePresistence object and passing it to the MQTTClient constructor.
You can also switch to a in memory store, but this will change how QOS2 messages are handled if the client crashes before a delivery can be confirmed.
You can specify the /tmp directory for client execution as:
String receiverId = UUID.randomUUID().toString();
IMqttClient receiver = new MqttClient(
"tcp://" + properties.getProperty("host") + ":" + properties.getProperty("port"), receiverId, new MqttDefaultFilePersistence("/tmp"));

How to access outlook public folders using Java?

Using Java I want to access certain Outlook public folders. I tried below code
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
Store store = session.getStore("imap");
store.connect("imap4.<something>.com", "<my user id>", "<my password>");
Folder folder = store.getFolder("Public Folders/");
folder.open(Folder.READ_ONLY);
Message[] messages = folder.getMessages();
if(messages.length == 0){
System.out.println("no message");
}
for(Message message : messages){
System.out.println(message.getSubject());
}
I have tried different combinations for "Public Folders". Every time I get:
Exception in thread "main" javax.mail.FolderNotFoundException: Public Folders/ not found
at com.sun.mail.imap.IMAPFolder.checkExists(IMAPFolder.java:302)
at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:885)
at MailReader.main(MailReader.java:23)
Please let me know if there is any way to access Outlook public folders.
The way I used in one of my projects was EWS Java API. Here's a link to some tutorial: http://blogs.msdn.com/b/exchangedev/archive/2013/01/03/ews-java-api-1-2-get-started.aspx It's not the easiest thing I've ever done though.
Looks like Microsoft removed the ability to access public folders through the IMAP protocol in Exchange 2007 and they have no plans to restore it.

Using Java mail Pop3 cannot seem to delete emails from Gmail

I have a java program that acts as a POP3 client using javax.mail. I am able to list and retrieve the contents of a Gmail inbox no problem. However, I cannot seem to delete emails. Here is the (important parts of the) code:
POP3Store sto=... another method creates and connects the POP3Store
Folder ibx=sto.getFolder("INBOX");
ibx.open(Folder.READ_WRITE);
Message[] msgarr=ibx.getMessages();
for(int mi=0; mi<msgarr.length; mi++) {
...do stuff with the message
msgarr[mi].setFlag(Flags.Flag.DELETED, true);
}
ibx.close(true); //folder.close(true) indicates to expunge the folder
sto.close();
After running this and seeing it handle each message, I go into Gmail and the emails are still there, and even showing as unread. If I re-run the java client, it will see and handle the same emails.
This same code happily deletes emails from an exchange server.
How can I get Gmail to delete emails?
Gmail handles POP deletion specially.
You can configure what Gmail should do when a message is deleted through POP in Gmail Settings, on the Forwarding and POP / IMAP tab.
As SLaks says, Gmail is a special case where it has its own settings for controlling deletion that override whatever the client wants to do.
It can be edited in the Forwarding and POP / IMAP
However, I want to add that for a message to be considered "downloaded" by Gmail, you need to have retrieved the content of each message, and in the case of multipart message types, the content of each part within that message.
Here's some example code that I use to force the deletion of unwanted messages from Gmail:
// Grab the content to get the email off the server
// folder is of type javax.mail.Folder and is already in the correct state to get messages from the mail store (Gmail)
Message msg = folder.getMessage(1);
Multipart multipart = (Multipart) msg.getContent();
int partcount = multipart.getCount();
for (int count = 0; count < partcount; count++) {
multipart.getBodyPart(count);
}
If you prepend "recent:" in your pop3 username you will solve.
Example: recent:yourusername#gmail.com
This connects to gmail using Recent Mode

Categories

Resources