Unable to delete messages using JavaMail - java

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.

Related

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.

Read Recent and Unseen message using javax.mail

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.

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

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

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.

Categories

Resources