I would like to use java (SE) to read my Inbox in MS Outlook (2010) and then move message/email to another folder. I have tried to search on web, but found only licensed solutions or posts old couple of years. Does anyone have solution for this step? Thank you very much for your help!
Can be done using javax.mail, but a lot depends on the protocol of the server and authentication etc.
Anyways, here is a snippet (assuming imap):
Set your properties:
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imap.user", <user>);
props.setProperty("mail.imap.host", <host>);
props.setProperty("mail.imap.port", <port 143>);
...
Get a session and connect
Session mailSession = Session.getInstance(props);
Store mailStore = mailSession.getStore("imap");
mailStore.connect(<host>, <user>, <passwd>);
Folder dFolder = mailStore.getDefaultFolder();
Folder inbox = dFolder.getFolder(<connectFolder=INBOX?>);
inbox.open(Folder.READ_WRITE);
// Open destination folder, create if reqd
Folder destfolder = mailStore.getFolder(<destination folder>);
if (!destfolder.exists())
destfolder.create(Folder.HOLDS_MESSAGES);
Message []inMessages = inbox.getMessages();
if (inMessages .length != 0) {
inbox.copyMessages(inMessages , destfolder);
for (int i=0; i< inMessages.length; i++) {
// Custom Processor which readsMessages and performs some action.
// getProcessor().readMessage(inMessages[i]);
inMessages[i].setFlag(Flags.Flag.DELETED, true);
}
}
Hope this helps
Related
Trying to move from jcifs to jcifs-ng (the latest jar jcifs-ng-2.1.2.jar) to copy files to/from remote.
My code using old jcifs:
System.setProperty("jcifs.smb.client.responseTimeout", "10000");
System.setProperty("jcifs.smb.client.soTimeout", "2000");
if (winsIPList.trim().equals("")) {
System.setProperty("jcifs.smb.client.dfs.disabled", "true");
} else {
System.setProperty("jcifs.smb.client.dfs.disabled", "false");
System.setProperty("jcifs.netbios.wins", winsIPList.trim());
System.setProperty("resolveOrder", "DNS");
}
NtlmPasswordAuthentication auth = new
NtlmPasswordAuthentication(filesrvDomainIP, filesrvDomainUser,
filesrvDomainPassword);
smbRemoteFile = new SmbFile("smb:" + remoteFile.replace("\\", "/"), auth);
<here the code to copy file>
Found few examples in stackoverflow, but looks like they are old.
Part of them include usage of NtlmPasswordAuthentication(context, DomainIP, DomainUser,DomainPassword) which is deprecated in the last jcifs-ng package.
Others use
SmbFile smbRemoteFile = new SmbFile(remoteFile, someContext)
which is reported as undefined by compiler
Could somebody provide an example that works?
Working example:
BaseContext baseCxt = null;
Properties jcifsProperties = new Properties();
jcifsProperties.setProperty("jcifs.smb.client.enableSMB2", "true");
jcifsProperties.setProperty("jcifs.smb.client.dfs.disabled","true");
Configuration config = new PropertyConfiguration(jcifsProperties);
baseCxt = new BaseContext(config);
auth = baseCxt.withCredentials(new NtlmPasswordAuthenticator(DomainIP, DomainUser,
DomainPassword));
SmbFile smbRemoteFile = new SmbFile("smb:" + remoteFile.replace("\\", "/"), auth);
According to this issue: jcifs-ng Issue #36: Chicken/egg relationship between CIFSContext and credentials
Class NtlmPasswordAuthentication is replaced by NtlmPasswordAuthenticator.
So you might replace your NtlmPasswordAuthentication usage with:
NtlmPasswordAuthenticator auth = new NtlmPasswordAuthenticator(domain, username, password)
Besides, this answer might be helpful.
I am trying to retrieve my inbox using javamail and I have done that but now problem arises when I try to load the code it take lot of time in reading all emails as it read the whole inbox but I want that only few emails should be fetched that are most recent.
Properties properties = new Properties();
String host = "pop.gmail.com";// change accordingly
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", "995");
properties.put("mail.pop3.starttls.enable", "true");
Session emailSession = Session.getDefaultInstance(properties);
//create the POP3 store object and connect with the pop server
Store store = emailSession.getStore("pop3s");
store.connect(host, username, password);
//create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
LOG.info("messages.length---" + messages.length);
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
leadJSONObject = new JSONObject();
LOG.info("Email Number " + (i + 1));
LOG.info("This log is executed successfully");
leadJSONObject.put("emailFrom", message.getFrom()[0].toString());
leadJSONObject.put("emailSubject", message.getSubject());
leadJSONObject.put("emailText", message.getContent().toString());
planJSONArray.put(leadJSONObject);
}
//close the store and folder objects
emailFolder.close(false);
store.close();
Please Help how can I read only few emails. Thanks in Advance.
You may want to count the messages, then retrieve only a part of the total , e.g for the 50 first messages (or less if there isn't enough):
int total = emailFolder.getMessageCount();
Message[] messages = emailFolder.getMessages(1,Math.min(total,50));
cf. the javadoc of javax.mail.Folder.
I would like to fetch recent, unread emails with a specific subject in a particular folder from my gmail account. I am using JavaMail API as below but it returns 0 results. However if I just use subjectTerm alone, I see results. Please let me know where am I going wrong. Thank you.
Please note that I used messages[0] below instead of looping through messages array for code simplicity to paste it here.
public void openMailBox(String hostname, String username, String password, String folderName, String subject) throws MessagingException, GeneralSecurityException, IOException{
props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imaps.host", "imap.gmail.com");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.ssl.enable", "true");
props.put("mail.imaps.ssl.socketFactory", new MailSSLSocketFactory());
session = Session.getInstance(props);
store = session.getStore();
store.connect(username, password);
folder = store.getFolder(folderName);
folder.open(Folder.READ_ONLY);
messages = folder.search(getSearchTerm(subject));
if (messages[0].isMimeType("multipart/*")){
Multipart multipart = (Multipart) messages[0].getContent();
for(int i=0;i<multipart.getCount();i++) {
BodyPart bodyPart = multipart.getBodyPart(0);
if (bodyPart.isMimeType("text/*")) {
msg = msg+bodyPart.getContent().toString();
}
}
}else{
msg = messages[0].getContent().toString();
}
System.out.println(msg);
folder.close(true);
store.close();
}
public SearchTerm getSearchTerm(String subject){
subjectTerm = new SubjectTerm(subject);
unseenFlagTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
recentFlagTerm; = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
return new AndTerm(subjectTerm, new AndTerm(unseenFlagTerm, recentFlagTerm));
}
}
What mail server are you using?
Some mail servers don't implement the RECENT flag in any useful way, so messages might not be marked RECENT. Try leaving out the RECENT term and see if you get more results.
If that doesn't help, add code to dump out the flags for all messages and then post the JavaMail debug output that shows the flags for all messages along with the search request and response.
Note also that some IMAP servers don't fully or correctly implement the SEARCH command and so can't handle the kind of search you're doing.
Finally, note that you don't need to set the socketFactory property unless you're using MailSSLSocketFactory in a more interesting way than you've show in your example code above.
I have a bizarre problem that I can't seem to get a handle on. :(
I have a Web based application that sends emails. It does so by connecting a Windows based SMTP server that was setup on a local network. This SMTP server does not require a username or a passord from my code in order to send the emails. Most of the day and sometimes most of the week everything works beautifully, the emails are sent and users are happy. Then out of nowhere and for no apparent reason I start seeing the Exception in my log that says:
javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:398)
at javax.mail.Service.connect(Service.java:245)
at javax.mail.Service.connect(Service.java:194)
at javax.mail.Transport.send0(Transport.java:253)
at javax.mail.Transport.send(Transport.java:124)
I upgraded my java mail jar to the latest version hich I guess is called javax.mail.far these days. We're running Tomcat 7, and Windows Server 2008R2 and the mail server is a Microsoft one.
I don't understand why this works sometimes but then stops for no apparent reason. But what I really would like to do is fix this issue so that it does not appear again. If any one has seen something like this before and has any ideas I would love to hear them. Here's the Java code that sends the emails:
Properties props = System.getProperties();
if (mailhost != null)
props.setProperty("mail.smtp.host", mailhost);
// Get a Session object
Session session = Session.getDefaultInstance(props);
// Output the email in the log window
session.setDebug(true);
// construct the message
Message msg = new MimeMessage(session);
if (from != null)
msg.setFrom(new InternetAddress(from));
else
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(email.getTo(), false));
if ((email.getCc() != null) && (email.getCc().length() > 0))
msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(email.getCc(), false));
if ((email.getBcc() != null) && (email.getBcc().length() > 0))
msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(email.getBcc(), false));
msg.setSubject(email.getSubject());
// Check if Attachment file exists
if ((attachmentFile != null) && (attachmentFile.getFileName() != null) &&
(attachmentFile.getFileName().length() > 0) )
{
MimeMultipart multipart = new MimeMultipart();
// Set the Message Text
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(email.getBody());
multipart.addBodyPart(messageBodyPart);
// Set the Message Attachment
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
DataSource ds = new ByteArrayDataSource(attachmentFile.getInputStream(), attachmentFile.getContentType());
attachmentBodyPart.setDataHandler(new DataHandler(ds));
attachmentBodyPart.setFileName(attachmentFile.getFileName());
multipart.addBodyPart(attachmentBodyPart);
// If we also have a PDF attachment
if (PDFAtch != null)
{
MimeBodyPart pdfAttachmentBodyPart = new MimeBodyPart();
ds = new ByteArrayDataSource(PDFAtch.getAttachment(), "application/pdf");
pdfAttachmentBodyPart.setDataHandler(new DataHandler(ds));
pdfAttachmentBodyPart.setFileName(PDFAtch.getFilename());
multipart.addBodyPart(pdfAttachmentBodyPart);
}
// Put parts in message
msg.setContent(multipart);
}
else if (PDFAtch != null)
{
MimeMultipart multipart = new MimeMultipart();
// Set the Message Text
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(email.getBody());
multipart.addBodyPart(messageBodyPart);
MimeBodyPart pdfAttachmentBodyPart = new MimeBodyPart();
DataSource ds = new ByteArrayDataSource(PDFAtch.getAttachment(), "application/pdf");
pdfAttachmentBodyPart.setDataHandler(new DataHandler(ds));
pdfAttachmentBodyPart.setFileName(PDFAtch.getFilename());
multipart.addBodyPart(pdfAttachmentBodyPart);
msg.setContent(multipart);
}
else
msg.setText(email.getBody());
msg.setHeader("X-Mailer", "EWarranty MailSender");
msg.setSentDate(email.getDateSent());
// send the thing off
Transport.send(msg);
logger.debug("Message sent successfully to "+email.getTo());
Thank you in advance for any and all help.
Posting the answer for those who may run into a similar problem.
Setting the following 2 properties seems to have done the trick, at least so far. :)
props.setProperty("mail.smtp.auth", "false");
props.put("mail.smtp.port", "25"); // Default port
I spoke to my email admin and he told me that the main port that our email server uses is in fact 25.
I did not change the way I create the session. At least not yet. BTW that link that Bill provided is an outstanding read and I highly recommend clicking on it and reading it.
Thanks everyone
Change Session.getDefaultInstance to Session.getInstance and see if that helps.
I've got the same problem and finally I've solved it.
The main problem is using system global properties:
Properties props = System.getProperties();
Other thread in your process can set mail.smtp.auth to true.
You should just use you own local properties:
Properties properties = new Properties();
I am using mstor to read the mbox email messages, but i am not able to connect to the store using the urlName name which i m passing, by default its connecting to other
location on my macbine.Do i need to create the store using mstor JCR before proceed to connect to the store?
Session session = Session.getDefaultInstance(new Properties());
Store store = session.getStore(new URLName("mstor:C:/mailbox/MyStore/Inbox"));
store.connect();
Folder inbox = store.getDefaultFolder().getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message m = inbox.getMessage(0);
Any suggetions are helpful
Thanks in advance..
//Set the Properties as shown below:
Properties properties = new Properties();
this.properties.setProperty("mail.store.protocol", "mstor");
this.properties.setProperty("mstor.mbox.metadataStrategy", "none");
this.properties.setProperty("mstor.mbox.cacheBuffers", "disabled");
this.properties.setProperty("mstor.cache.disabled", "true");
this.properties.setProperty("mstor.mbox.bufferStrategy", "mapped");
this.properties.setProperty("mstor.metadata", "disabled");
//Also mstor count for messages start from 1 and not 0. so change it to 1.
Store store = session.getStore(new URLName("mstor:C:/mailbox/MyStore/Inbox"));
store.connect();
Folder inbox = store.getDefaultFolder().getFolder("inbox");
inbox.open(Folder.READ_ONLY);
Message m = inbox.getMessage(1);