Javax.mail.FolderNotFoundException: Sent Items not found - java

Hello im trying to retreive emails sent by my outlook mail but i have a prob in the folder name
I can retreive my mail inbox using the folder "Inbox" but i want the sent items folder
final String username = "XXXX#outlook.fr";
final String password = "XXXX";
Properties props = new Properties();
props.setProperty("mail.store.protocol", "imaps");
props.setProperty("mail.imap.port", "993");
props.setProperty("mail.imap.connectiontimeout", "5000");
props.setProperty("mail.imap.timeout", "5000");
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);
try {
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", username, password);
Folder inbox = store.getFolder("Sent Items");
inbox.open(Folder.READ_ONLY);
Message[] messages = inbox.getMessages();
for (int i = 0; i < messages.length; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("To: " + message.getRecipients(Message.RecipientType.TO));
System.out.println("Text: " + message.getContent().toString());
}
inbox.close(true);
store.close();
} catch (Exception e){
e.printStackTrace();
}
avax.mail.FolderNotFoundException: Sent Items not found
at com.sun.mail.imap.IMAPFolder.checkExists(IMAPFolder.java:455)
at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:1068)
at com.sun.mail.imap.IMAPFolder.open(IMAPFolder.java:1001)
at com.jsf.com.SendEmail.read2(SendEmail.java:61)
at com.jsf.com.SendEmail.main(SendEmail.java:11)

Related

Reading mails and from java using IMAP protocol but missing some file

I'm working on project in spring boot, where I need read details of the mails.
First I'm storing unread mails into message[] array and I'm reading first 50 mails and again next 50 mails and so on.
But when I do so some of the mails are missing out i.e., in 50 mails some number of mails are not read and details are not recorded.
Below is the function where I am doing all this operations.
Please help me to improve my code.
public List<Object> read(){
Properties properties = new Properties();
properties.setProperty("mail.host", "imap.gmail.com");
properties.setProperty("mail.port", "995");
properties.setProperty("mail.transport.protocol", "imaps");
String userName=resourceBundle.getString("mailUserName");
String password=resourceBundle.getString("mailPassword");
Session session = Session.getInstance(properties,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
});
try {
Store store = session.getStore("imaps");
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
SearchTerm recentTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
SearchTerm fromTerm = new FromTerm(new InternetAddress(resourceBundle.getString("receiveMailFrom")));
SearchTerm unreadTerm = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
SearchTerm subjectTerm = new SubjectTerm(this.subjectTerm);
SearchTerm subjectAndUnreadTerm = new AndTerm(subjectTerm, unreadTerm);
SearchTerm recentAndFromTerm = new AndTerm(recentTerm, fromTerm);
SearchTerm subjectAndUnreadAndFromTerm = new AndTerm(subjectAndUnreadTerm, fromTerm);
Message messages[] = inbox.search(subjectAndUnreadAndFromTerm);
List<Object> readParams=new ArrayList<>();
if (messages.length<count)
logger.info("Number of mails = " + messages.length);
else
logger.info("Number of mails = " + count);
for (Message message : messages) {
if(mailcount<count) {
Address[] from = message.getFrom();
logger.info("-------------------------------");
logger.info("Date : " + message.getSentDate());
logger.info("From : " + from[0]);
logger.info("Subject: " + message.getSubject());
logger.info("Content :");
fileNames = processMessageBody(message);
logger.info("--------------------------------");
mailcount +=1;
}
else{
break;
}
}
inbox.close(true);
store.close();
if(messages.length==0)
{
readParams.add(0);
return readParams;
}
else {
readParams.add(1);
readParams.add(fileNames);
return readParams;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

Unable to read custom header from email

I am adding custom header while sending email in Java. If anybody gives reply to that email I need to store the content of that email in database. I might receive multiple reply for that mail. So for identification I am adding custom header with unique value.
While reading unread email from inbox folder from imaps store, I am unable to read custom header. Other than custom header I am able to read other header.
I am reading email using below Class
public class OutLookReader_imaps {
Folder inbox;
public OutLookReader_imaps() throws IOException {
System.out.println("Inside MailReader()...");
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
Properties props = System.getProperties();
props.setProperty("mail.imaps.socketFactory.class", SSL_FACTORY);
props.setProperty("mail.imaps.socketFactory.fallback", "false");
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.socketFactory.port", "993");
props.put("mail.imaps.host", "outlook.office365.com");
try {
/* Create the session and get the store for read the mail. */
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore("imaps");
store.connect("outlook.office365.com", 993, "example#entransys.com", "password");
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
Message messages[] = inbox.search(unseenFlagTerm);
if (messages.length == 0) System.out.println("No messages found.");
System.out.println("No. of Unread Messages : " + inbox.getUnreadMessageCount());
System.out.println("No. of Messages : " + inbox.getMessageCount());
System.out.println("No. of Deleted Messages : " + inbox.getMode());
for (int i = 0; i < messages.length; i++) {
if (i > 10) {
System.exit(0);
inbox.close(true);
store.close();
}
System.out.println("Message " + (i + 1));
System.out.println("From : " + messages[i].getFrom()[0]);
System.out.println("Subject : " + messages[i].getSubject());
System.out.println("Sent Date : " + messages[i].getSentDate());
System.out.println("Header : " + messages[i].getAllHeaders());
System.out.println("Content : " + messages[i].getContent().toString());
System.out.println("Content Type : " + messages[i].getContentType());
System.out.println("Description : " + messages[i].getDescription());messages[i].getContent());
System.out.println("Unique Header : " + messages[i].getHeader("X-Universally-Unique-Identifier"));
System.out.println("Header uni : " + messages[i].getHeader("X-Uniform-Type-Identifier"));
Enumeration allHeaders = messages[i].getAllHeaders();
while (allHeaders.hasMoreElements()) {
Header header = (Header) allHeaders.nextElement();
String headerName = header.getName();
String headerVal = header.getValue();
System.out.println("Header Name : " + headerName);
System.out.println("Header Value : " + headerVal);
}
}
try {
inbox.close(true);
store.close();
} catch (Exception ex) {
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
} catch (MessagingException e) {
System.out.println("Exception while connecting to server: " + e.getLocalizedMessage());
e.printStackTrace();
System.exit(2);
}
}
public void printAllMessages(Message[] msgs) throws Exception {
for (int i = 0; i < msgs.length; i++) {
System.out.println("MESSAGE #" + (i + 1) + ":");
printEnvelope(msgs[i]);
}
}
public void printEnvelope(Message message) throws Exception {
Address[] a;
if ((a = message.getFrom()) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("Email From : " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
Date sentDate = message.getSentDate();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
System.out.println("Email Subject : " + subject);
if (receivedDate != null) {
System.out.println("Received Date: " + df.format(receivedDate));
}
System.out.println("Sent Date : " + df.format(sentDate));
}
public static void main(String args[]) throws IOException {
new OutLookReader_imaps();
}
}
Custom headers that you add to messages you send will not be added to messages that reply to the message you sent. There will usually be an In-Reply-To header or References header that includes the Message-ID of the message you sent, but even those are not guaranteed to be present. The most reliable way of associating replies with sent messages is probably to include a unique ID in the Subject of the message you sent.

How To Check Mail Validation in Selenium WebDriver?

i Need To Verify Email is Received or not in gmail. So That i Tried The Following Code. But i Didn't Get The Result. Can You Please Sort Me out This.
The Following Code is :
public static void getPassword(String email, String password) throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", email, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_WRITE);
System.out.println("Total Message:" + folder.getMessageCount());
System.out.println("Unread Message:" + folder.getUnreadMessageCount());
Message[] messages = null;
boolean isMailFound = false;
Message mailFromProx = null;
// Search for mail from Prox with Subject = 'Email varification Testcase'
for (int i = 0; i <= 5; i++) {
messages = folder.search(new SubjectTerm("Email varification Testcase"), folder.getMessages());
// Wait for 20 seconds
if (messages.length == 0) {
Thread.sleep(20000);
}
}
// Search for unread mail
// This is to avoid using the mail for which
// Registration is already done
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
mailFromProx = mail;
System.out.println("Message Count is: " + mailFromProx.getMessageNumber());
isMailFound = true;
}
}
// Test fails if no unread mail was found
if (!isMailFound) {
throw new Exception("Could not find new mail from iGotThis :-(");
// Read the content of mail and get password
} else {
String line;
StringBuffer buffer = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(mailFromProx.getInputStream()));
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
System.out.println(buffer);
String result = buffer.toString().substring(buffer.toString().indexOf("is:") + 1,
buffer.toString().indexOf("3. Start enjoying an easier life!"));
String resultxx = result.substring(4, result.length() - 1);
//Print passsword
System.out.println(resultxx);
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream(Constant.Path_UserPassFile);
// set the properties value in property file
prop.setProperty("User_Password", resultxx);
PropsUtils.setProperties().setProperty("User_Password", resultxx);
// save properties to project root folder
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
}
System.out.println("Password = " + prop.getProperty("User_Password"));
}
}
}
i Tried Searching Lot of Results , But Nothing Not Clear. Can You Please Provide Me Prefect Result.
if You Got Any Results Regarding The Mail Testing in Selenium Please Provide Here , Let Me Try Here.
Here is the working solution for your problem. It uses JAVAX MAIL API and JAVA code.
It does a lot more, so remove the code that u don't need.
public GmailUtils(String username, String password, String server, EmailFolder
emailFolder) throws Exception {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imap");
props.setProperty("mail.imaps.partialfetch", "false");
props.put("mail.imap.ssl.enable", "true");
props.put("mail.mime.base64.ignoreerrors", "true");
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imap");
store.connect("imap.gmail.com", 993, "<your email>", "<your password>");
Folder folder = store.getFolder(emailFolder.getText());
folder.open(Folder.READ_WRITE);
System.out.println("Total Messages:" + folder.getMessageCount());
System.out.println("Unread Messages:" + folder.getUnreadMessageCount());
messages = folder.getMessages();
for (Message mail : messages) {
if (!mail.isSet(Flags.Flag.SEEN)) {
System.out.println("***************************************************");
System.out.println("MESSAGE : \n");
System.out.println("Subject: " + mail.getSubject());
System.out.println("From: " + mail.getFrom()[0]);
System.out.println("To: " + mail.getAllRecipients()[0]);
System.out.println("Date: " + mail.getReceivedDate());
System.out.println("Size: " + mail.getSize());
System.out.println("Flags: " + mail.getFlags());
System.out.println("ContentType: " + mail.getContentType());
System.out.println("Body: \n" + getEmailBody(mail));
System.out.println("Has Attachments: " + hasAttachments(mail));
}
}
}
public boolean hasAttachments(Message email) throws Exception {
// suppose 'message' is an object of type Message
String contentType = email.getContentType();
System.out.println(contentType);
if (contentType.toLowerCase().contains("multipart/mixed")) {
// this message must contain attachment
Multipart multiPart = (Multipart) email.getContent();
for (int i = 0; i < multiPart.getCount(); i++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(i);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
System.out.println("Attached filename is:" + part.getFileName());
MimeBodyPart mimeBodyPart = (MimeBodyPart) part;
String fileName = mimeBodyPart.getFileName();
String destFilePath = System.getProperty("user.dir") + "\\Resources\\";
File fileToSave = new File(fileName);
mimeBodyPart.saveFile(destFilePath + fileToSave);
// download the pdf file in the resource folder to be read by PDFUTIL api.
PDFUtil pdfUtil = new PDFUtil();
String pdfContent = pdfUtil.getText(destFilePath + fileToSave);
System.out.println("******---------------********");
System.out.println("\n");
System.out.println("Started reading the pdfContent of the attachment:==");
System.out.println(pdfContent);
System.out.println("\n");
System.out.println("******---------------********");
Path fileToDeletePath = Paths.get(destFilePath + fileToSave);
Files.delete(fileToDeletePath);
}
}
return true;
}
return false;
}
public String getEmailBody(Message email) throws IOException, MessagingException {
String line, emailContentEncoded;
StringBuffer bufferEmailContentEncoded = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(email.getInputStream()));
while ((line = reader.readLine()) != null) {
bufferEmailContentEncoded.append(line);
}
System.out.println("**************************************************");
System.out.println(bufferEmailContentEncoded);
System.out.println("**************************************************");
emailContentEncoded = bufferEmailContentEncoded.toString();
if (email.getContentType().toLowerCase().contains("multipart/related")) {
emailContentEncoded = emailContentEncoded.substring(emailContentEncoded.indexOf("base64") + 6);
emailContentEncoded = emailContentEncoded.substring(0, emailContentEncoded.indexOf("Content-Type") - 1);
System.out.println(emailContentEncoded);
String emailContentDecoded = new String(new Base64().decode(emailContentEncoded.toString().getBytes()));
return emailContentDecoded;
}
return emailContentEncoded;
}
I would suggest you to use Nada email api which are disposable email addresses and very easy to get the content.
Check the examples here.
http://www.testautomationguru.com/selenium-webdriver-email-validation-with-disposable-email-addresses/

JAVA message.getAllRecipients().length returns incorrect value

I'm using javax.mail, IMAP provider and want to get number of recipients.
My email message has 3 recipients, but
System.out.println("AllRecipients: " + message.getAllRecipients().length);
and
System.out.println("Recipients: " + message.getRecipients(Message.RecipientType.TO).length);
returns value = 1.
Code:
public void checkEmail() throws MessagingException
{
String host = "imap.example.host";
Integer port = 993;
String username = "exampleLogin";
String password = "examplePassword";
String provider = "imaps";
String folderMail = "inbox";
Properties properties = new Properties();
properties.put("mail.imap.host", host);
properties.put("mail.imap.socketFactory.port", port);
properties.put("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.put("mail.imap.auth", "true");
properties.put("mail.imap.port", port);
Session session = Session.getDefaultInstance(properties, new javax.mail.Authenticator(){protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("username","password");
}
});
Store store = session.getStore(provider);
store.connect(host, port, username, password);
try
{
Folder folder = store.getFolder(folderMail);
folder.open(Folder.READ_WRITE);
Message[] messages = folder.getMessages();
System.out.println("messages in folder: " + messages.length);
for (int messageNumber = 0, messageCount = messages.length; messageNumber < messageCount; messageNumber ++)
{
Message message = messages[messageNumber];
System.out.println("---------------------------------");
System.out.println("Email #: " + messageNumber);
System.out.println("Subject: " + message.getSubject());
System.out.println("AllRecipients: " + message.getAllRecipients().length);
}
folder.close(false);
}
catch (FolderNotFoundException e)
{
System.out.println(System.currentTimeMillis() + " :: Folder " + folderMail + " not found or empty");
}
System.out.println("FINISH");
}
can anyone help?

How to get HTML formatting to work with multiple emails using JavaMail

I'm trying to send multiple emails that use HTML for formatting, but only the first email gets sent as HTML, the rest are sent as plain text.
Anyone know what the problem could be?
Here's my code for sending the multiple emails:
public static int sendEmail(int ind) throws AddressException, MessagingException, InterruptedException, IOException {
mailServerProperties = System.getProperties();
mailServerProperties.put("mail.smtp.port", "587");
mailServerProperties.put("mail.smtp.auth", "true");
mailServerProperties.put("mail.smtp.starttls.enable", "true");
getMailSession = Session.getDefaultInstance(mailServerProperties, null);
generateMailMessage = new MimeMessage(getMailSession);
generateMailMessage.setSubject("Greetings");
Transport transport = getMailSession.getTransport("smtp");
transport.connect("smtp.gmail.com", email, password);
Person perp;
for(int i = ind; i < people.size(); i++){
perp = people.get(i);
generateMailMessage.setRecipient(Message.RecipientType.TO, new InternetAddress(perp.email));
emailBody = "Dear " + perp.name + ", <br><br> Testing. <br><br>The Tester";
generateMailMessage.setContent(emailBody, "text/html; charset=utf-8");
generateMailMessage.setSubject("Greetings"+i);
try{
transport.sendMessage(generateMailMessage, generateMailMessage.getAllRecipients());
System.out.println(i);
} catch(Exception SMTPSendFailedException) {
System.out.println("Number "+i+" failed");
ind = i;
break;
}
ind = i;
}
System.out.println("round done");
transport.close();
return ind;
}
http://pastebin.com/JXyTBFFX

Categories