i'm trying the very simple Email Client in java.
When i launch the programe i have an error message:
Exception in thread "main" javax.mail.AuthenticationFailedException: EOF on socket
at com.sun.mail.pop3.POP3Store.protocolConnect(POP3Store.java:146)
at javax.mail.Service.connect(Service.java:297)
at javax.mail.Service.connect(Service.java:156)
at SimpleEmailClient2.main(SimpleEmailClient2.java:21)
Java Result: 1
Why?
i use Gmail account and i set the POP and IMAP enabled
What could be the possible error in my code?
Thank you
here is the code:
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
public class SimpleEmailClient2 {
public static void main(String[] args) throws Exception {
Properties props = new Properties();
String host = "pop.gmail.com";
String provider = "pop3";
Session session = Session.getDefaultInstance(props, new MailAuthenticator());
Store store = session.getStore(provider);
store.connect(host, null, null);
Folder inbox = store.getFolder("INBOX");
if (inbox == null) {
System.out.println("No INBOX");
System.exit(1);
}
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
System.out.println("Message " + (i + 1));
messages[i].writeTo(System.out);
}
inbox.close(false);
store.close();
}
}
class MailAuthenticator extends Authenticator {
public MailAuthenticator() {
}
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("email#gmail.com", "password");
}
}
I don't believe gmail supports the pop3 provider; you have to use pop3s instead. Otherwise this should work fine.
Oracle has information on connecting javamail to gmail here.
Specifically it looks like you're failing when trying to establish the connection, likely because you don't specify a username/password to connect to. Try connecting using something like:
store.connect(host, "user618111#gmail.com", "[myPassword]");
Related
This question already has answers here:
How can I send an email by Java application using GMail, Yahoo, or Hotmail?
(14 answers)
Closed 2 years ago.
I am trying to make automatic message which will be sent on email but, when i start my program i get :
com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;
I want it to be sent from localhost not exact email with password and username.
code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.Session;
import javax.mail.Transport;
public class Email
{
public static void main(String[] args) throws IOException {
String recipient = "test#gmail.com";
String sender = "sender#gmail.com";
String host = "localhost";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(sender));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient));
message.setSubject("Test sub");
message.setText("Test MSG");
Transport.send(message);
System.out.println("Sent.");
} catch (AddressException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
}
To run this class i am using javax.mail.jar.
Does somebody know where the problem is ?
It's trying to connect to the mail server at localhost but you don't have one running. To send smtp emails you'll have to connect to a mail server. The default port is 25. That's why the message says:
Couldn't connect to host, port: localhost, 25
So update your host property to point to where a server is running. You can use SMTP settings from say a gmail account to do this easily.
This might help.
https://www.siteground.com/kb/google_free_smtp_server/
we have an Exchange Server and i wanted to test sending a mail with it. But somehow i always get the error:
com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.1 Message rejected as spam by Content Filtering.
at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2108)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1889)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at Test.sendMailJava(Test.java:89)
at Test.main(Test.java:29)
i tried looking at our exchange if anonymous users were allowed and they are, our Printer also send Mails without any authentification.
Here is my Java code, hope someone can help:
import java.net.URI;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import org.simplejavamail.email.Email;
import org.simplejavamail.mailer.Mailer;
import org.simplejavamail.mailer.config.ProxyConfig;
import org.simplejavamail.mailer.config.ServerConfig;
import org.simplejavamail.util.ConfigLoader;
public class Test {
public static void main(String[] args) {
//// // TODO Auto-generated method stub
sendMailJava();
}
public static void sendMailJava()
{
String to = "Recipient"
// Sender's email ID needs to be mentioned
String from = "Sender";
// Assuming you are sending email from localhost
String host = "Server Ip-Adress";
// Get system properties
Properties properties = System.getProperties();
// Setup mail server
properties.setProperty("mail.smtp.host", host);
properties.setProperty("mail.smtp.port", "25");
properties.setProperty("mail.imap.auth.plain.disable","true");
properties.setProperty("mail.debug", "true");
Session session = Session.getDefaultInstance(properties);
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(session);
// Set From: header field of the header.
message.setFrom(new InternetAddress(from));
// Set To: header field of the header.
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
// Set Subject: header field
message.setSubject("Subject");
// Now set the actual message
message.setContent("Content", "text/html; charset=utf-8");
// Send message
Transport.send(message);
System.out.println("Sent message successfully....");
}catch (MessagingException mex) {
mex.printStackTrace();
}
}
}
I also tried SimpleMail, but there is the same error.
The Connection to the smtp Server seems to work, but the message cannot be send, cause of the error above. What could it be?
Greetings,
Kevin
Edit:
i found my error, i don't know why our printers can send maisl without errors but it seems i had to whitelist my ip at our exchange server. Code was completely fine.
thanks for the help
I know you are wanting the smtp option, but I have a feeling the issue is how your server is setup and not in your code. If you get the EWS-Java Api, you can log into your exchange server directly and grab mail that way. Below is the code that would make that work:
public class ExchangeConnection {
private final ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2); // change to whatever server you are running, though 2010_SP2 is the most recent version the Api supports
public ExchangeConnection(String username, String password) {
try {
service.setCredentials(new WebCredentials(username, password));
service.setUrl(new URI("https://(your webmail address)/ews/exchange.asmx"));
}
catch (Exception e) { e.printStackTrace(); }
}
public boolean sendEmail(String subject, String message, List<String> recipients, List<String> filesNames) {
try {
EmailMessage email = new EmailMessage(service);
email.setSubject(subject);
email.setBody(new MessageBody(message));
for (String fileName : fileNames) email.getAttachments().addFileAttachment(fileName);
for (String recipient : recipients) email.getToRecipients().add(recipient);
email.sendAndSaveCopy();
return true;
}
catch (Exception e) { e.printStackTrace(); return false; }
}
}
In your code you just have to create the class, then use the sendEmail method to send emails to whomever.
Your JavaMail code is not authenticating to your server, which may be why the server is rejecting the message with that error message. (Spammers often use open email servers.)
Change your code to call the Transport.send method that accepts a user name and password.
I would like to send an email using my Java Application.
When I press a button, there should be automatically sent an email , but somehow I didn't find the solution yet.
I found a lot of example codes in the internet, but it doesn't matter if I use Gmail / gmx or outlook, I always receive the message :
"Could not connect to SMTP host: mail.gmx.net, port: 587;
nested exception is:
java.net.ConnectException: Connection timed out: connect"
Based on the domain, so the host is mail.gmx.net or smtp.office365.com etc..
So I think there's somehow a connection problem, but I wasn't able to fix it.
Do you have some ideas / codes that worked for you ?
Thank you in advance.
Tobias
Use this code for send Email .This works fine for me
package SendMail;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* #author akash073
*
*/
public class CrunchifyJavaMailExample {
//static Properties mailServerProperties;
// static Session getMailSession;
// static MimeMessage generateMailMessage;
public static void main(String args[]) throws AddressException, MessagingException {
generateAndSendEmail();
System.out.println("\n\n ===> Your Java Program has just sent an Email successfully. Check your email..");
}
public static void generateAndSendEmail() throws AddressException, MessagingException {
String smtpHost="put Your Host";
String smtpUser="UserName in full #somthing.com";
String smtpPassword="your password";
int smtpPort=25;//Port may vary.Check yours smtp port
// Step1
System.out.println("\n 1st ===> setup Mail Server Properties..");
Properties mailServerProperties = System.getProperties();
//mailServerProperties.put("mail.smtp.ssl.trust", smtpHost);
// mailServerProperties.put("mail.smtp.starttls.enable", true); // added this line
mailServerProperties.put("mail.smtp.host", smtpHost);
mailServerProperties.put("mail.smtp.user", smtpUser);
mailServerProperties.put("mail.smtp.password", smtpPassword);
mailServerProperties.put("mail.smtp.port", smtpPort);
mailServerProperties.put("mail.smtp.starttls.enable", "true");
System.out.println("Mail Server Properties have been setup successfully..");
// Step2
System.out.println("\n\n 2nd ===> get Mail Session..");
Session getMailSession = Session.getDefaultInstance(mailServerProperties, null);
MimeMessage generateMailMessage = new MimeMessage(getMailSession);
generateMailMessage.setFrom (new InternetAddress (smtpUser));
generateMailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("akash073#waltonbd.com"));
generateMailMessage.addRecipient(Message.RecipientType.CC, new InternetAddress("akash073#gmail.com"));
generateMailMessage.setSubject("Greetings from Crunchify..");
String emailBody = "2.Test email by Crunchify.com JavaMail API example. " + "<br><br> Regards, <br>Crunchify Admin";
generateMailMessage.setContent(emailBody, "text/html");
System.out.println("Mail Session has been created successfully..");
// Step3
System.out.println("\n\n 3rd ===> Get Session and Send mail");
Transport transport = getMailSession.getTransport("smtp");
// Enter your correct gmail UserID and Password
// if you have 2FA enabled then provide App Specific Password
transport.connect(smtpHost,smtpPort, smtpUser, smtpPassword);
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
transport.close();
}
}
For more info crunchify
I found that javamail only support socks. Is there any solution I can use to support http proxy?
public class MailConnectionTest {
public static void main(String args[]) throws MessagingException {
Properties props = MailConnectionTest.getProperties();
Session session = Session.getDefaultInstance(props, null);
String protocol = "pop3";
String host = "pop.163.com";
String username = "email username";
String password = "1Qaz2wsx3edc&";
Store store = session.getStore(protocol);
store.connect(host, username, password);
System.out.println("Success");
}
private static Properties getProperties() {
Properties props = System.getProperties();
props.put("mail.debug", "false");
// Proxy
props.put("proxySet", "true");
props.put("http.proxyHost", "proxyAdderss");
props.put("http.proxyPort", "8080");
return props;
}
}
As per the latest release of Javamail API 1.6.2 , JavaMail supports accessing mail servers through a web proxy server and also authenticating to the proxy server. Please see my code below.
import java.io.IOException;
import java.net.Authenticator;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Flags.Flag;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.search.FlagTerm;
public class ReadMailProxy {
public static void receiveMail(String userName, String password) {
try {
String proxyIP = "124.124.124.14";
String proxyPort = "4154";
String proxyUser = "test";
String proxyPassword = "test123";
Properties prop = new Properties();
prop.setProperty("mail.imaps.proxy.host", proxyIP);
prop.setProperty("mail.imaps.proxy.port", proxyPort);
prop.setProperty("mail.imaps.proxy.user", proxyUser);
prop.setProperty("mail.imaps.proxy.password", proxyPassword);
Session eSession = Session.getInstance(prop);
Store eStore = eSession.getStore("imaps");
eStore.connect("imap.mail.yahoo.com", userName, password);
Folder eFolder = eStore.getFolder("Inbox");
eFolder.open(Folder.READ_WRITE);
Message messages[] = eFolder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), false));
System.out.println(messages.length);
for (int i = messages.length - 3; i < messages.length - 2; i++) {
Message message = messages[i];
System.out.println("Email Number::" + (i + 1));
System.out.println("Subject::" + message.getSubject());
System.out.println("From::" + message.getFrom()[0]);
System.out.println("Date::" + message.getSentDate());
try {
Multipart multipart = (Multipart) message.getContent();
for (int x = 0; x < multipart.getCount(); x++) {
BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
System.out.println("Mail have some attachment : ");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
} else {
System.out.println(bodyPart.getContent());
}
}
} catch (Exception e) {
System.out.println("Content: " + message.getContent().toString());
}
message.setFlag(Flag.SEEN, true);
}
eFolder.close(true);
eStore.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
receiveMail("umesh#yahoo.com", "test123");
}
}
javamail api 1.6 supports web server proxy
set these properties
mail.protocol.proxy.host
mail.protocol.proxy.port
for smtp set as
mail.smtp.proxy.host
mail.smtp.proxy.port
See the JavaMail FAQ:
How do I configure JavaMail to work through my proxy server?
... Without such a SOCKS server, if you want to use JavaMail to access mail servers outside the firewall indirectly, you might be able to use a program such as Corkscrew or connect to tunnel TCP connections through an HTTP proxy server. JavaMail does not support direct access through an HTTP proxy web server.
The implementation only support basic authentication for web proxy. You can find the source code in com.sun.mail.util.SocketFetcher.
Since javamail support NTLM authentication already, it is not hard to support NTLM authentication for web proxy.
I am testing the Microsoft Exchange Web Service Java API (version 1.2) to read mails from a server. Here is my code:
String url = "https://my-server/EWS/exchange.asmx";
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.setTraceEnabled(true);
service.setCredentials(new WebCredentials("user", "password"));
service.setUrl(url.toURI());
Mailbox mailbox = new Mailbox("foo#bar.com");
FolderId folder = new FolderId(WellKnownFolderName.Inbox, mailbox);
ItemView view = new ItemView(10);
view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
FindItemsResults<Item> items = service.findItems(folder, view);
Unfortunately, this code throws the following error:
Exception in thread "main" microsoft.exchange.webservices.data.EWSHttpException: Connection not established
at microsoft.exchange.webservices.data.HttpClientWebRequest.throwIfConnIsNull(Unknown Source)
at microsoft.exchange.webservices.data.HttpClientWebRequest.getResponseCode(Unknown Source)
at microsoft.exchange.webservices.data.EwsUtilities.formatHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeServiceBase.traceHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeServiceBase.processHttpResponseHeaders(Unknown Source)
at microsoft.exchange.webservices.data.SimpleServiceRequestBase.internalExecute(Unknown Source)
at microsoft.exchange.webservices.data.MultiResponseServiceRequest.execute(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.findItems(Unknown Source)
at microsoft.exchange.webservices.data.ExchangeService.findItems(Unknown Source)
at foo.bar.TestMail.main(TestMail.java:52)
I'm not able to understand what is wrong with the current code. Do you have any clue, or at least some tests to try?
Note that the web-service (https//my-server/exchange.asmx) is accessible to my Java code.
Not sure if it can help, but I've found that in the traces displayed by the logs:
<Trace Tag="EwsResponse" Tid="1" Time="2013-01-28 10:47:03Z">
<html><head><title>Error</title></head><body>The function requested is not supported
</body></html>
</Trace>
EDIT
I've made another test. This time, I use the defaults credentials - so my own email account - using service.setUseDefaultCredentials(true); instead of setting the WebCredentials object. The connection is still not established, but I get another error (I've took only the interesting part of the trace log):
<h1>You are not authorized to view this page</h1>
You do not have permission to view this directory or page using the credentials that you supplied because your Web browser is sending a WWW-Authenticate header field that the Web server is not configured to accept.
(...)
<h2>HTTP Error 401.2 - Unauthorized: Access is denied due to server configuration.<br>Internet Information Services (IIS)</h2>
Of course, I can't access nor change anything on the Exchange server side. Is there a way to make the authentication successful?
The problem is due to the authentication scheme used. By default, EWS uses NTLM, but my Exchange server is not configured to accept this kind of authentication. I have to use LDAP authentication.
I got the above mentioned error and spend many hours trying to fix it. My ultimate solution was to give up on EWS Version 1.2 completely and use the following javax.mail code like this:
package javaapplication4;
import java.util.Date;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.MimeMessage;
public class JavaApplication4 {
public static void main(String[] args) throws Exception {
new JavaApplication4().send_email();
}
private void send_email() throws Exception
{
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.yourserver.net");
props.put("mail.from", "yourusername#youremailaddress.com");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.ssl.enable", "false");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "587");
Authenticator authenticator = new Authenticator();
props.setProperty("mail.smtp.submitter", authenticator.getPasswordAuthentication().getUserName());
Session session = Session.getInstance(props, authenticator);
MimeMessage msg = new MimeMessage(session);
msg.setFrom();
msg.setRecipients(Message.RecipientType.TO, "yourusername#youremailaddress.com");
// also tried #gmail.com
msg.setSubject("JavaMail ssl test");
msg.setSentDate(new Date());
msg.setText("Hello, world!\n");
Transport transport;
transport = session.getTransport("smtp");
transport.connect();
msg.saveChanges();
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
private class Authenticator extends javax.mail.Authenticator {
private PasswordAuthentication authentication;
public Authenticator() {
String username = "yourusername#youremailaddress.com";
String password = "yourpassword";
authentication = new PasswordAuthentication(username, password);
}
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
}
}
You will need to get the javamail-1.4.7 and load the mail.jar from (http://www.oracle.com/technetwork/java/index-138643.html) into the project.
One thing we did which shed light on the situation is download Thunderbird mail client which can auto-discover information about the exchange server to make sure all of our settings were right.
This is an Example of EWS JAVA api 1.2,This is one of the ways you can try
package com.ea.connector.exchange;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import microsoft.exchange.webservices.data.BasePropertySet;
import microsoft.exchange.webservices.data.ExchangeCredentials;
import microsoft.exchange.webservices.data.ExchangeService;
import microsoft.exchange.webservices.data.FindItemsResults;
import microsoft.exchange.webservices.data.Item;
import microsoft.exchange.webservices.data.ItemSchema;
import microsoft.exchange.webservices.data.ItemView;
import microsoft.exchange.webservices.data.LogicalOperator;
import microsoft.exchange.webservices.data.OffsetBasePoint;
import microsoft.exchange.webservices.data.PropertySet;
import microsoft.exchange.webservices.data.SearchFilter;
import microsoft.exchange.webservices.data.SortDirection;
import microsoft.exchange.webservices.data.WebCredentials;
import microsoft.exchange.webservices.data.WebProxy;
import microsoft.exchange.webservices.data.WellKnownFolderName;
import org.apache.commons.httpclient.NTCredentials;
import com.ea.connector.exchange.bean.ExchangeConnectionParamBean;
import com.ea.connector.exchange.util.ExchMessageProperties;
import com.ea.connector.net.ExchGetItemRequest;
public class Test {
protected static ArrayList<String> propertiesToFetch = new ArrayList<String>();
private static ExchangeService mService;
// private Settings mSettings;
//
// private int imailCount;
private Date dStartDate;
private Date dEndDate;
private static ExchangeConnectionParamBean objParamBean;
public void setPropertiesToBeFetched(List<String> filter) {
propertiesToFetch.addAll(filter);
}
public Date getConnectorStartDate() {
return dStartDate;
}
public void setConnectorStartDate(Date dStartDate) {
this.dStartDate = dStartDate;
}
public ExchangeConnectionParamBean getParamBean() {
return objParamBean;
}
public void setParambean(ExchangeConnectionParamBean objParambean) {
Test.objParamBean = objParambean;
}
public Date getConnectorEndDate() {
return dEndDate;
}
public void setConnectorEndDate(Date dEndDate) {
this.dEndDate = dEndDate;
}
public static void main(String []args) throws URISyntaxException,Exception
{
setCredentialsAndGetExchRequest();
System.out.println("conncection established");
}
protected static ExchGetItemRequest setCredentialsAndGetExchRequest() throws URISyntaxException,Exception{
#SuppressWarnings("unused")
FindItemsResults<Item> resultMails;
mService = new ExchangeService();
mService.setUrl(new URI("https://outlook.office365.com/EWS/Exchange.asmx"));
WebProxy paramWebProxy=new WebProxy("ptbproxy.domain.com",8080);
mService.setWebProxy(paramWebProxy);
ExchangeCredentials cred = new WebCredentials("EA_Test_mailbox#domain.com","Zuxu0000");
NTCredentials ntCredentials = new NTCredentials("EA_Test_mailbox#domain.com","Zuxu0000", "",
"");
mService.setCredentials(cred);
// ProxyHost httpProxy=new ProxyHost("ptbproxy.domain.com",8080);
// UsernamePasswordCredentials cred1=new UsernamePasswordCredentials("EA_Test_mailbox#domain.com","Zuxu0000");
// ExchGetItemRequest req = new ExchGetItemRequest(String.valueOf(new URI("http://outlook.office365.com/EWS/Exhanges.asmx")),ntCredentials);
ExchGetItemRequest req = new ExchGetItemRequest("https://outlook.office365.com/EWS/Exhange.asmx",ntCredentials);
SearchFilter filter = getSearchFilter();
PropertySet propertySet = new PropertySet(BasePropertySet.IdOnly);
ItemView itemView = new ItemView(1000, 0, OffsetBasePoint.Beginning);
itemView.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Descending);
itemView.setPropertySet(propertySet);
//mService.setTimeout(500000);
req.setProperties(new ExchMessageProperties().getExchMessageProperties(propertiesToFetch));
/*Fetching of mail ids start here*/
resultMails = getMails(filter, itemView);
return req;
}
protected static SearchFilter getSearchFilter() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date d1 = sdf.parse("2014-11-04 00:00:00");
Date d2 = sdf.parse("2014-11-05 00:00:00");
SearchFilter greaterThanEq = new SearchFilter.IsGreaterThanOrEqualTo(
ItemSchema.DateTimeReceived,sdf.format(d1));
SearchFilter lessThan = new SearchFilter.IsLessThan(
ItemSchema.DateTimeReceived, sdf.format(d2));
SearchFilter mailFilter = new SearchFilter.IsEqualTo(
ItemSchema.ItemClass, "IPM.Note");
return new SearchFilter.SearchFilterCollection(LogicalOperator.And,
greaterThanEq, lessThan, mailFilter);
}
private static FindItemsResults<Item> getMails(SearchFilter searchFilter,
ItemView itemView) throws Exception {
FindItemsResults<Item> items = null;
int count = 0;
int maxTries = 3;
while (true) {
try {
items = mService.findItems(WellKnownFolderName.Inbox,
searchFilter, itemView);
break;
} catch (Exception e) {
if (++count == maxTries)
throw e;
}
}
return items;
}
}