Not able to search the email server with searchTerm using Mail API - java

An email is sent from lets say gg#gg.com with an attachment to 2 email id's .One, my email id and another xx#xx.com
I got that email. When i did mail search using java Mail API with email id as search criteria , it is not able to find it though i received that email.But when i forward it to the same email id's search criteria is working fine. Please let me know when email is received for the first time at that point why it is not able to search
Properties properties = System.getProperties();
properties.put("mail.smtp.host", ExchangeProperties.getSmtpHost());
properties.put("mail.pop3.connectiontimeout", String.valueOf(ExchangeProperties.getPop3ConnectionTimeout() * 1000));
properties.put("mail.pop3.timeout", String.valueOf(ExchangeProperties.getPop3Timeout() * 1000));
session = Session.getInstance(properties, null);
session.setDebug(logger.isDebugEnabled());
// Get the store
store = session.getStore("pop3");
store.connect(ExchangeProperties.getSmtpHost(), user, password);
Folder folder = store.getFolder(folderName)
Message[] foundMessages = folder.search(andTerm); //andTerm contains email id
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
folder.fetch(foundMessages, fp);

Since you're using pop3, all the searching is done by downloading all the messages to the client and searching them there. If you want the server to do the searching, use imap.
If the new message arrives while you have the pop3 folder open, you won't be able to see it. You need to close the folder and reopen it. That's a limitation of the pop3 protocol.
If none of that helps with your problem, I would need to know exactly which search term you're using, exactly what value you're searching for, and exactly what value appears in the email header.

Related

sending an email from different address

I'm writing a program that has auto response in it. i.e. for example there is an user ad his email address would be user#domain.com, when ever someone writes an email to this address, there should be an auto response sent (Which I'm able to do it). but this should be sent from autoReply#domain.com(this is what I'm unable to know on how to do this). autoReply#domain.com is a shared mail box.
I'm using ews in my program and the below block of code is responsible to send the auto response.
private void replyToEmailWithURLs(ItemId itemId, List matchedKeyWords, String fromAddress) throws Exception {
EmailMessage message = EmailMessage.bind(service, itemId, new PropertySet(BasePropertySet.IdOnly));
ResponseMessage responseMessage = message.createReply(false);
message.getReplyTo().add(new EmailAddress("autoReply#domain.com"));
// Add autoReply in CC
responseMessage.getCcRecipients().add("autoReply#domain.com");
String responseUrls = getTheResponseUrlsFromJsonFile(matchedKeyWords, fromAddress);
responseMessage.setBodyPrefix(new MessageBody(BodyType.HTML, responseUrls));
responseMessage.sendAndSaveCopy();
message.setIsRead(true);
}
Here I tried to add a replyTo using message.getReplyTo().add(new EmailAddress("autoReply#domain.com"));, even this doesn't work.
I've seen a post here set reply-to address in outgoing email EWS , I was confused on the way it is working(basically given in c#), please let me know how can I get this done in Java.
Thanks
I'm not familiar with EWS, but apparently the standard JavaMail API supports setting From or the sender address.

java mail download link for attachment

i'm using java mail api to download java mail message attachment.
i am using this link tutorial
download mail attachment
but my requirement is that when user read mail it only display download link for attachment and when click on the link file downloaded that time.
Thanks
Manish
I think you want to do the following:
Check, if it is a multipart message AND consists of several parts
1.1 If so, it has attachments. You should then retrieve the first text/plain or text/html part, which should be the text itself. You leave the other parts alone. But along the text you store some id or reference to the message on the server, that the text is taken from. Consider the following code.
Folder folderInbox = store.getFolder("INBOX");
Message[] arrayMessages = folderInbox.getMessages();
for (int i = 0; i < arrayMessages.length; i++) {
Message message = arrayMessages[i];
}
Now the class javax.mail.Message has a method getMessageNumber()::int.
If you store this message number and the folder name, in this case "INBOX",
you have an identifier, that will allow you to find the message on the server
again at a later time and do something with it, like downloading parts that have
not been retrieved yet.
So (pseudo code here) you basically have to do this.
var message_text = message.getFirstTextBodyPart();
var message_ident = (message.getFolderName(), message.getMessageNumber());
var message = (message_ident, message_text);
saveMessage(message);
showMessage(message);
1.2 In other cases, you download the entire message right now, as there are no parts for later retrieval.

Detect emails and response with a mail

If i got any email I want to response with a email from my code.
Am new to java, Is it possible with any api to detect mails?
I saw javamail api in this we can read and send mail. In this we need to pass server host. To read hotmail emails what host name we need to pass?
I find the following code.
Properties props =System.getProperties();
props.setProperty("mail.store.protocol","imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("server hostname","username","password");
can u prefer any tutorials for that and property key values and server hosts.
http://www.javatpoint.com/example-of-receiving-email-using-java-mail-api
here the solution to read mails
For reading mail
http://www.compiletimeerror.com/2013/06/reading-email-using-javamail-api-example.html
and get the To Address and send mail using
http://www.tutorialspoint.com/java/java_sending_email.htm

Sending email in Java by using database

I am currently doing a project where I am required to send an email to the specific address taken from database. However, the column "email" in database does not actually contain emails, but names instead. So in database there are full names in russian language like
"Иванов Александр" which is "Ivanov Alexandr". So when I type this name in the outlook it automatically finds his email: AIvanov#domainname.com. But in my java code when I use name "Иванов Александр" i keep getting error.
Here is my java code
File[] listOfFiles = outDir.listFiles();
if (outDir.isDirectory()) {
if (outDir.list().length > 0) {
for (File file : listOfFiles) {
Session session_m = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session_m);
message.setFrom (new InternetAddress("mmm#domainname.com", "mmm#domainname.com"));
InternetAddress i = new InternetAddress("\""+email+"\"", false);
message.addRecipient(Message.RecipientType.TO, i);
message.setSubject("test");
message.setText("test");
message.setHeader("Content-Type","text/plain;charset=windows-1251");
MimeBodyPart mbp1 = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
mbp1.setDataHandler(new DataHandler(fds));
mbp1.setFileName(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(mbp1);
System.out.println("[EmailHandler] Attaching the following file to email: " + fds.getName());
message.setContent(mp);
SMTPTransport t = (SMTPTransport)session_m.getTransport("smtp");
t.connect("mail.domainname.com", "main#domainname.com", null);
System.out.println("[EmailHandler] Sending email... ");
t.sendMessage(message, message.getAllRecipients());
file.delete();
Thread.sleep(3000);
}
} else {
System.out.println("[EmailHandler] Folder " + outDir.getName() + " is empty... nothing to attach");
}
} else {
System.out.println("Folder not found... Check the path");
}
In this code the String email is Иванов Александр.
And I kept getting this error
javax.mail.internet.AddressException: Local address contains control or whitespace in string ``Иванов Александр''
So would like to know the ways I can make this string go through.
Thank you.
The outlook uses its address book to map a name to one of the email. That is why it is working fine, if you manually try creating a new email and just put the name. Outlook simply do a lookup in the address book and find out the email address.
However, this is not the same with a java program. The program needs exact email address to send an email. Now there could be many ways to find out email address.
The simplest approach is to store the email address in one of the database table.
If the person is associated with the company's SMTP system/active directory; you could use java smtp API / active directory APIs to find out the email or alias (usually be the part of email id before #) and then create email id to be used into the program to send email.
You need to provide a valid mail address. If you are using a fixed structure for your mails just convert the name to latin characters and append #domain.com
If you are not using any rules for your mail adress creation then I suggest you to add an email field to the database
Don't know if this resolves your question though
Regards
Your program have to
Validate e-mail.
It can be implemented using regular expression: Using a regular expression to validate an email address
Get email from contact list when field contains only name. There are two library for working with outlook contacts:
Open source java library to read outlook emails, calendar etc

Check Email attachments for specific mail using imaps in java

How to check the no. of attachments for the selected mail using imap?
I am able to get the message body/headers but I am not able get the attachment specific to mail selected?
Here is the code I tried:
DataHandler handler = message.getDataHandler();
AttachedFileName= handler.getName();
This code will give the filenames of all the attachments in the inbox and not specific to a mail.
How do I go about doing this?
Let me know!
you can increase a value for an integer when an attachment is finished.so,number of values increased is number of attachments .
It's a simple think too ..

Categories