javamail mark gmail message as read - java

Note: added after answer:
Thanks.. Yeah I had tried the Flag.SEEN to true and saveChanges.. I also had read getContent marks it read. I tried using it in the for statement that loops through the messages. But I got the messages again from the folder anyways in the next loop. I was assuming the folder was live, so grabbing the content, then grabbing the messages again from the folder with the filter to not get any seen should work, but I was still getting the same message. I could try closing the folder and reopen as a test to see if it's marked. Also if I go over to my client and click the message, then my code stops seeing it even in the loop, so I was hoping to do the same in the code.
original:
I'm using javamail to get email from a gmail account, it's working great, when I get the message I'd like to mark it as read, can anyone give me some direction? Here is my current code:
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", eUserName, ePassWord);
// Get folder
Folder folder = store.getFolder("INBOX");
if (folder == null || !folder.exists()) {
return null;
}
folder.open(Folder.READ_ONLY);
// Only pull unread
FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
Message messages[]; // = folder.search(ft);
for(int x = 0; x < timeOutInSeconds; x++) {
log.reportMessage("looking for emails");
try {
folder.getMessages();
messages = folder.search(ft);
if (messages.length > 0) {
for (Message message : messages) {
//log.reportMessage("found message: should not see again, marking read");
// want to mark as read
}
}
Thread.sleep(1000);
}
catch(Exception ex) {
}
}
// Close connection
folder.close(false);
store.close();
return null;
}
catch (NoSuchProviderException ex) {
return null;
}
catch (MessagingException ex) {
return null;
}
}

First of all, you can't mark a message as read if you are using a POP3 server - the POP3 protocol doesn't support that. However, the IMAP v4 protocol does.
You might think the way to do this is to get the message, set the Flags.Flag.SEEN flag to true, and then call message.saveChanges(). Oddly, this is not the case.
Instead, the JavaMail API Design Specification, Chapter 4, section "The Flags Class" states that the SEEN flag is implicitly set when the contents of a message are retrieved. So, to mark a message as read, you can use the following code:
myImapFolder.open(Folder.READ_WRITE);
myImapFolder.getMessage(myMsgID).getContent();
myImapFolder.close(false);
Or another way is to use the MimeMessage copy constructor, ie:
MimeMessage source = (MimeMessage) folder.getMessage(1)
MimeMessage copy = new MimeMessage(source);
When you construct the copy, the seen flag is implicitly set for the message referred to by source.

One liner that will do it WITHOUT downloading the entire message:
single message:
folder.setFlags(new Message[] {message}, new Flags(Flags.Flag.SEEN), true);
all messages:
folder.setFlags(messages, new Flags(Flags.Flag.SEEN), true);
Other methods of calling getContent() or creating a copy with new MimeMessage(original) cause the client to download the entire message, and creates a huge performance hit.
Note that the inbox must be opened for READ_WRITE:
folder.open(Folder.READ_WRITE);

Well this post is old but the easiest solution hasnĀ“t been posted yet.
You are accessing the Message.
message.setFlag(Flag.SEEN, true);

for (Message message : messages) {
message.setFlag(Flags.Flag.SEEN,true);
}
and change the below line
folder.open(Folder.READ_ONLY);
to this
folder.open(Folder.READ_WRITE);

You may also consider having a public static int max_message_number, and storing in it the message[i].getMessageNumber(); as soon as you read a message. Then before reading any message just check if the max_message_number < message[i].getmessageNumber(). If true then don't print this message (as it has been already read)

message.setFlag( Flag.SEEN,true ) give "cannot find symbol"
message.setFlag( Flags.Flag.SEEN,true ) seems good.

If you are using a for loop to read or check a mail one by one, the code can be as follows to mark a gmail message as read:
Message[] unreadMessages = inbox.search(new FlagTerm(new Flags(Flag.SEEN), false));
for (int q = 0; q < unreadMessages.length; q++) {
unreadMessages[q].setFlag(Flag.SEEN, true);
}
What this code does is that it makes it unread one by one.
And also folder/inbox needs to be READ_WRITE, instead of READ_ONLY:
folder.open(Folder.READ_WRITE);

You can also try
head over to the gmail settings > Forwarding and POP/IMAP
from the dropdown of When messages are accessed with POP
select mark Gmail's copy as read and save the changes

To mark the mail as read, you just have to call the mailmessage.getContent() method.
Whether you use IMAP or POP, calling that method on a specific mail mark it as Read

The easiest way to do that is set the folder to be read or written into or from. Means like this...
Folder inbox = null;
inbox.open(Folder.READ_WRITE);
the Folder class should be imported.

Related

return a single message from array of messages

I just have requirement that i have an array of type Messages. so i want to return a Messages from them. Can anyone help me how to do that?
public static Message getContent(String user, String pswd, String sub, String to)
throws MessagingException, IOException {
Session imapSession1 = TestMail.greenMail.getImap().createSession();
Store store = imapSession1.getStore("imap");
store.connect("foo", "password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
// Getting only unread messages.
Flags flags = new Flags();
flags.add(Flag.SEEN);
FlagTerm flagTerm = new FlagTerm(flags, false);
Message[] msgs = inbox.search(flagTerm);
Message ms = msgs[0];
return ms;
}
I tried to return first message as shown above, but it is throwing IndexOutOfBoundsException: 0
So can anyone help me with this. Thanks in advance.
Either there is a problem with your previous code or there are no unread messages but either way msgs is empty after you have search the inbox - you just need to check msgs.length > 0 first and if it is not then decide what you want to do. You could return an Optional (Java8 feature and you would need to change the method signature to match) or simply return null or throw an exception depending on your needs. All 3 scenarios then need appropriate handling in the calling code.
NOTE that it is unlikely that throwing an Exception is the correct approach unless the code is only called when there should be unread messages.

How to read mail with java mail API (String cannot be cast to Multipart)

I am trying to write a simple code that will read messages from gmail inbox.
I have found some examples, but non of them is working.
Most promising is code I've found on CompilatimEerror.com, BUT whatever I try I get this error:
java.lang.ClassCastException: java.lang.String cannot be cast to javax.mail.Multipart
Here is my code:
import java.util.*;
import javax.mail.*;
public class ReadingEmail {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getInstance(props, null);
Store store = session.getStore();
store.connect("imap.gmail.com", "yourEmailId#gmail.com","password");
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message msg = inbox.getMessage(inbox.getMessageCount());
Address[] in = msg.getFrom();
for (Address address : in) {
System.out.println("FROM:" + address.toString());
}
Multipart mp = (Multipart) msg.getContent(); // here it breaks
BodyPart bp = mp.getBodyPart(0);
System.out.println("SENT DATE:" + msg.getSentDate());
System.out.println("SUBJECT:" + msg.getSubject());
System.out.println("CONTENT:" + bp.getContent());
} catch (Exception mex) {
mex.printStackTrace();
}
}
}
There is no connection error, as it gets the subject, date, and all this stuff, but the email body is a mystery. There will be no attachments, I will get only simple mails(this is a part of greater project)
What I am looking for is to read the unread mail (and then delete this message, so the inbox will be permanently empty(spam will be deleted manually)).
I lack knowledge about web programing/structures, and all that pop's, imaps and stuff is a blank space.
Also keep in mind that I am a novice programmer and this is the first time that I go outside of my computer with my code unfortunately straight into the problems of protocols / authentication / getting things from internet.
I went through a lot of pages, but never found an explanation that would allow me to create it myself...
Are you related to this guy?
The JavaMail FAQ has pointers to lots of helpful information, including the JavaMail project page, sample code, etc. You'll also find pointers to some useful background material and tutorials here.

getting the 'seen' flag doesn't seem to work

I'm playing around with java's default pop3 implementation and having trouble getting it to read the actual state of flags (i think).
Here's the (abbreviated) code:
Store store = null;
Folder folder = null;
try
{
Session mailSession = Session.getInstance(new Properties(), null);
store = mailSession.getStore("pop3");
store.connect(host, addr, pwd);
folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
for (Message msg : folder.getMessages())
{
if (msg.isSet(Flag.SEEN))
continue;
LOG.debug("processing email titled '" + msg.getSubject()
+ "' from '" + msg.getFrom()[0] + "'");
... do some stuff
msg.setFlag(Flag.SEEN, true);
}
}
finally
{
if (folder != null)
folder.close(true);
if (store != null)
store.close();
}
The problem is that each time the above code is executed, the same messages (all of them) are processed because the call to msg.isSet(Flag.SEEN) always returns false, even though I have set it to true in the previous iteration.
The webmail client even reflects the flag being set (title changes from bold to normal font).
Does anyone know what I'm doing wrong?
thanks, p.
further reading tells me that pop3 doesn't support setting/getting these flags, only deleting messages.
it does seem that pop3 supports setting the flag (since i could see the flag had been set successfully in the webmail program) but could not subsequently read the flags state.
thankfully my mail server supports imap which does everything as expected. I just had to change my code from mailSession.getStore("pop3") to mailSession.getStore("imap").

Javamail performance

I've been using javamail to retrieve mails from IMAP server (currently GMail). Javamail retrieves list of messages (only ids) in a particular folder from server very fast, but when I actually fetch message (only envelop not even contents) it takes around 1 to 2 seconds for each message. What are the techniques should be used for fast retrieval?
here is my code:
try {
IMAPStore store = null;
if(store!=null&&store.isConnected())return;
Properties props = System.getProperties();
Session sessionIMAP = Session.getInstance(props, null);
try {
store = (IMAPStore) sessionIMAP.getStore("imaps");
store.connect("imap.gmail.com",993,"username#gmail.com","password");
} catch (Exception e) {
e.printStackTrace();
}
IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
System.out.println("start");
Message[] msgs = folder.getMessages(1,10);
long ftime = System.currentTimeMillis();
FetchProfile fp=new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(msgs, fp);
long time = System.currentTimeMillis();
System.out.println("fetch: "+(time-ftime));
for (Message message : msgs) {
System.out.println(message.getSubject());
Address[] from = message.getFrom();
for (Address address : from) {
System.out.println(address);
}
Address[] recipients = message.getAllRecipients();
for (Address address : recipients) {
System.out.println(address);
}
}
long newTime = System.currentTimeMillis();
System.out.println("convert: "+(newTime-time));
}catch (Exception e) {
e.printStackTrace();
}
}
I believe that Gmail throttles the IMAP message reads to one every second or so. You might be able to speed it up with multiple IMAP connections.
Please set the Property mail.imap.fetchsize with the required size. the default is 16k.
In case you increase the size of this property, retrieve speed will go up.
props.put("mail.imap.fetchsize", "3000000");
Note that if you're using the "imaps" protocol to access IMAP over SSL, all the properties would be named "mail.imaps.*".
Good Luck.
Yaniv
I'm not sure if this is a Javamail issue as much as it may be a Gmail issue. I have an application that retrieves mail from a number of sources, including Gmail, and Gmail is definitely the slowest. The Javamail api is pretty straightforward, but it would be hard to make suggestions without seeing what you are currently doing.
I'm running into the same thing. After profiling, I noticed that getBody was being called every time I tried to do a message.getFrom() like you are, even though I was only accessing fields that should be covered by the Envelope flag. See https://java.net/projects/javamail/forums/forum/topics/107956-gimap-efficiency-when-only-reading-headers

Can I perform a search on mail server in Java?

I am trying to perform a search of my gmail using Java. With JavaMail I can do a message by message search like so:
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "myUsername", "myPassword");
Folder inbox = store.getFolder("Inbox");
inbox.open(Folder.READ_ONLY);
SearchTerm term = new SearchTerm() {
#Override
public boolean match(Message mess) {
try {
return mess.getContent().toString().toLowerCase().indexOf("boston") != -1;
} catch (IOException ex) {
Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
} catch (MessagingException ex) {
Logger.getLogger(JavaMailTest.class.getName()).log(Level.SEVERE, null, ex);
}
return false;
}
};
Message[] searchResults = inbox.search(term);
for(Message m:searchResults)
System.out.println("MATCHED: " + m.getFrom()[0]);
But this requires downloading each message. Of course I can cache all the results, but this becomes a storage concern with large gmail boxes and also would be very slow (I can only imagine how long it would take to search through gigabytes of text...).
So my question is, is there a way of searching through mail on the server, a la gmail's search field? Maybe through Microsoft Exchange?
Hours of Googling has turned up nothing.
You can let the server do the search for you, with the appropriate IMAP command. The SEARCH command will only get you so far, what you probably need is the SORT command. SORT isn't implemented in JavaMail but the documentation shows how you can implement it yourself:
http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/IMAPFolder.html#doCommand(com.sun.mail.imap.IMAPFolder.ProtocolCommand)
(I couldn't figure out how to link to a URL with parentheses)
Connect to the Exchange IMAP store and use javax.mail.search.SearchTerm

Categories

Resources