Read Recent and Unseen message using javax.mail - java

I am using javax.mail to read messages from inbox folder using 'imaps' protocol. I am using the below code snippet:
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect();
store.getFolder("inbox");
inbox.open(Folder.READ_WRITE);
FlagTerm unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
FlagTerm recentFlagTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
But I am not getting any messages. I want the most recent message which is also still not read/seen. Please propose any better solution? I am still not sure what 'new Flags(Flags.Flag.RECENT) set TRUE or FALSE' do?

You haven't included all your code. Presumably you're using those two FlagTerms in an AndTerm, which you pass to the search method.
It's somewhat server-dependent when the RECENT flag is set on a message, and when it's cleared. If you open a folder and close it, it may clear all the RECENT flags, on the assumption that you've seen which messages are recent.
You might have better luck just ignoring the RECENT flag and only looking for the SEEN flag not being set.
You also need to decide whether "most recent" means "most recently received" or "most recently sent". The former is easy; it's just the last message in the returned array. The latter will require you to sort the returned messages by sent date.

Related

Where are SMS Drafts stored?

I have searched and searched and cannot seem to pull data from the draft's folder within the device. Basically I am wanting to pull the typed (unsent) message from the user's conversation, my thinking is that it was stored within Android as a draft. However if I try to search the draft folder using the uri-
Uri message = Uri.parse("content://sms/draft/");
No data is returned. I have adjusted it to remove the 'draft' portion and it does return all my inbox messages. I have ensured that the permissions have been set and accepted.

How to prepare (not send) an e-mail in outlook, with java? [duplicate]

This question already has an answer here:
Need to open ms outlook with attachments [duplicate]
(1 answer)
Closed 5 years ago.
I'm trying to write a program that, after the user reviews certain equipment and answers some questions about them, it creates a report and automatically sends it to a database.
The program itself is not very complicated, I have it more or less solved, but I fail in the part of sending the mail. I have been searching, and I have found the JavaMail API, and I have even learned to send emails with it, more or less, but my company blocks any attempt of an external program to send e-mail, so I have decided to give it a different approach and try that instead of sending it automatically, prepare the mail in the Outlook editor itself, ready to be sent, and that the user only has to click to send, after reviewing it.
But looking here, or Javamail documentation, or even googling, I can't find any reference to people doing it, even knowing that it can be done, as I've been using some programs that do this by themselves!
So, the question is: can I do this with JavaMail? If yes, could you provide me with an example, or something, to learn how to use it? If not, any other libraries able to do that?
Maybe this is a simple question, maybe Java itself has a function for doing it. But I've been looking for it for a week, and I can't find anything that I can use.
I'm very very new to programming (a bit more than a year), so try to keep the answer to a basic level that some novice can understand, please.
As an example, let's say I have an equipment called X. The programs asks me "Does X makes excessive noise?" and I check "Correct" button. Then, it asks "Has X a normal pressure level?", and I check "Incorrect" button, and add a comment "Pressure level to high". And so on, until I've answered every question. Then, when I have finished with X equipment, and push the "Finish" button, I want a "New Email" outlook window to pop out, with the receiver already fulfilled, "Equipment X 27/12/2017 morning revision" as subject, and the body something like:
"Noise revision: correct
Pressure level: incorrect Comment: Pressure level to high
Question 3: correct
Question 4: correct
etc."
I've solved already how to create the body, and assign every parameter to its place. The problem is the pop out and auto fulfilling thing, how to export all that data to outlook to be ready to be sent. And yes, bosses specify that I have to use outlook.
So I would propose to create and save a message with JavaMail as discussed here
Now, you cannot send the particular message right away because the message header does not contain the following line:
"X-Unsent":1
(which will actually instruct the outlook client that the message is in draft state)
So the code should look something like this:
(note that this is not tested, just copy pasted from different sources)
public static void createMessage(String to, String from, String subject, String body, List<File> attachments) {
try {
Message message = new MimeMessage(Session.getInstance(System.getProperties()));
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to));
message.setSubject(subject);
//make it a draft!!
message.setHeader("X-Unsent", "1");
// create the message part
MimeBodyPart content = new MimeBodyPart();
// fill message
content.setText(body);
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(content);
// add attachments
for(File file : attachments) {
MimeBodyPart attachment = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachment.setDataHandler(new DataHandler(source));
attachment.setFileName(file.getName());
multipart.addBodyPart(attachment);
}
// integration
message.setContent(multipart);
// store file
message.writeTo(new FileOutputStream(new File("c:/mail.eml")));
} catch (MessagingException ex) {
Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Mailkit.class.getName()).log(Level.SEVERE, null, ex);
}
}
Hope this helps.

move (copy) IMAPMessage to another folder on the mail server

My application is checking the patterns of the subjects of the mails on the Inbox server folder and if some pattern is found, we should move the email (com.sun.mail.imap.IMAPMessage) to another folder - called 'test' for example (copy will do the job also).
I searched on the Internet for the solution but I could not find anything helpful.
Can you tell me how can I move / copy IMAPMessage from inbox to another folder on server?
Thank you
Presumably you're already using a com.sun.mail.imap.IMAPFolder?
That class has the method addMessages(Message[] msgs). Use it to add a Message to the new folder.
Alternatively, as mentioned by #gospodin, there's a copyMessages(Message[] msgs, Folder destinationFolder) method, which provides a shortcut for copying messages from their original folder to a new one.
It is a bad idea to move a message with methods like copyMessages(), addMessages() or appendMessage() and removing the old message, because these methods generates a new message. The new message have an different Message-ID in the header. If you response on the new message, the receiver cannot relate the response to his sent mail, because he does not know the new Message-ID. You have to cast the folder to a IMAPFolder. IMAPFolder has the method moveMessages(Message[] msgs, Folder targetFolder) to move messages without tampering the header Message-ID.
List<Message> tempList = new ArrayList<>();
tempList.add(myImapMsg);
Message[] tempMessageArray = tempList.toArray(new Message[tempList.size()]);
fromFolder.copyMessages(tempMessageArray, destFolder);

Exchange Web Services get Message Message-ID

I'm using the Java EWS library to try to sync messages from an Exchange mailbox. I'm able to get a list off all new messages created since the last sync date, however, I would really like to find out the Message-ID property of the message before loading it from exchange.
Background: I'm trying to integrate EWS sync into an existing mail storage system. The Message-ID identification is solely for performance reasons, as our system already has millions of messaged processed outside of EWS. Having to download them again would cause major performance overhead.
//Sample code to fetch the message from sync
ChangeCollection<ItemChange> icc = service.syncFolderItems( folder.getId()
, PropertySet.FirstClassProperties // propertySet
, null // ignoredItemIds
, 25 // maxChangesReturned
, SyncFolderItemsScope.NormalItems
, currSyncState );
for ( ItemChange ic : icc )
{
if (ic.getChangeType() == ChangeType.Create)
{
Item item = ic.getItem();
//how to get the Message-ID
}
Right now, the best way I see to retrieve the Message-ID is by calling ic.getItem().getInternetMessageHeaders() after calling ic.load(). But that requires loading the entire message from exchange, and I would to avoid this step.
Edit: Another way to grab the Message-ID is
EmailMessage em = EmailMessage.bind( service, item.getId() );
em.getInternetMessageId()
However, that still loads the entire message.
The other solution is to start associating messages by the ItemId, but even that's not perfect: http://daniellang.net/exchange-web-services-itemid-is-not-permanent/
More about Message-ID: http://en.wikipedia.org/wiki/Message-ID
I believe the solution is this:
EmailMessage em = EmailMessage.bind( service, item.getId(),
new PropertySet( EmailMessageSchema.InternetMessageId) );
Explanation :
We have to bind the item to an email message, but instead of grabbing all the info, we only ask for the ID and any additional properties we want through the PropertySet parameter.
Inspired by this answer: https://stackoverflow.com/a/22482779/138228

Unable to delete messages using JavaMail

I am using JavaMail to access an Exchange mailbox (private to the company I work for). My applicable code is as follows:
Store store = Session.getDefaultInstance(props, null).getStore("imap");
store.connect(...stuff...);
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
int numOfMessages = inbox.getMessageCount();
for (int i = 1; i<=numOfMessages; i++){
Message message = inbox.getMessage(i);
message.setFlag(Flags.Flag.DELETED, true);
System.out.println(message.getSubject());
}
inbox.close(true);
store.close();
It is accessing and printing out all of the message names properly. However, with each run through, it is printing the same names over and over, indicating that they weren't actually deleting.
Resolution: I found that I was throwing an error before the inbox.close(true) (in code I deemed inapplicable). I'm not marking it as an answer, because this isn't a real answer.
Try to call the saveChanges method on your Message object. Javadoc here.

Categories

Resources