Image File Compression before download into path using Java - java

I am Downloading Image from Gmail, what the problem here is , Image file upto 6MB, So it will take some more time in order to complete its download process. So my Question is Shall i compress image while downloading(ie Before save into path)? I have looked some Image compression examples in java,but all are taking image from one path then compress and finally stores that compressed image into some other folder.
If you want code for download attachment from gmail, Please click here . Could you please help me out to find the solution?
/*Downloading EmailAttachment into localfolder*/
public void downloadEmailAttachments(String protocol, String host, String port, String userName, String password,
String tempDirectory,String saveDirectory,String MessageID,String HeaderID,String emailDate,String emailSubject, MessageContext context) {
logger.info("===Inside downloadEmailAttachments Process====");
Properties properties = getServerProperties(protocol, host, port);
Session session = Session.getDefaultInstance(properties);
int status = 0;
try {
Store store = session.getStore(protocol);
store.connect(userName, password);
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
logger.info("No of Unread Messages : " + folderInbox.getUnreadMessageCount());
/* create a search term for all "unseen" messages*/
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen, false);
SearchTerm searchTerm = new AndTerm(new MessageIDTerm(HeaderID), new SubjectTerm(emailSubject));
Message[] arrayMessages = folderInbox.search(searchTerm);
if(arrayMessages != null && arrayMessages.length > 0){
Message message = arrayMessages[0];
Address[] fromAddress = message.getFrom();
String msgId=mimeMessage.getMessageID();*/
String from = fromAddress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType();
String messageContent = "";
String modifiedsubject=subject.toUpperCase().replaceAll("\\s+", "");
String attachmentname = "";
if(modifiedsubject.contains("SELLMYCAR")){
if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
//String fileName = part.getFileName();
// part.setFileName(ESBMessageID+":"+new Date());
// String fileName = part.getFileName()+":"+ESBMessageID+":"+new Date();
String fileName = part.getFileName();
fileName=fileName.substring(0, fileName.lastIndexOf(".")).concat(".jpg");
System.out.println("Modified FileName:" + fileName);
attachmentname = fileName;
/*part.saveFile(saveDirectory + File.separator + fileName);*/
part.saveFile(tempDirectory + File.separator + fileName);
logger.info("Files are downloaded into "+ tempDirectory+" successfully");
if (attachmentname.length() > 1) {
attachmentname = attachmentname.substring(0, attachmentname.length());
}
/*FileMove Process*/
moveFile(tempDirectory,fileName,saveDirectory,MessageID,context);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
// print out details of each message
logger.info("Message # :");
logger.info("\t From: " + from);
//logger.info("\t UserName: " + name);
logger.info("\t Subject: " + subject);
logger.info("\t Sent Date: " + sentDate);
//logger.info("\t UserMailID: " + email);
logger.info("\t Attachments: " + attachmentname);
logger.info("\t LocalDownloadpath: " + saveDirectory);
} else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
}
}
// disconnect
folderInbox.close(false);
store.close();
} catch (MessagingException ex) {
logger.info("Could not connect to the message store");
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}````

Related

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/

How to read eml file contains in eml file using Javamail API

I have an EML file which contains another EML file as an attachment.
When I try to fetch an attachment file using JAVAMAIL API, getDisposition value indicates attachment but getfileName() displays NULL.
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
InputStream source = new FileInputStream("C:\\Mail1496085.eml");
MimeMessage message = new MimeMessage(mailSession, source);
System.out.println("Subject : " + message.getSubject());
System.out.println("From : " + message.getFrom()[0]);
System.out.println("--------------");
System.out.println("Body : " + message.getContent());
String contentType = message.getContentType();
if (contentType.contains("multipart")) {
System.out.println("Multipart EMail File");
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
System.out.println("Parts:::"+numberOfParts);
String wi="IM-67890-PROCESS";
String saveDir = System.getProperty("user.dir")+"\\Docs";
saveDir=saveDir + File.separator+wi;
boolean file =new File(saveDir).mkdir();
if (file) {
System.out.println("Directory: " + wi + " created");
// logger.debug("Directory: " + workItem + " created");
}
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
String disposition=part.getDisposition();
if (Part.ATTACHMENT.equalsIgnoreCase(disposition)) {
// this part is attachment
String fileName = part.getFileName();
String extension="";
System.out.println("Attached File Name::"+fileName);
saveDir=saveDir + File.separator + fileName;
int i=fileName.lastIndexOf(".");
if(i>0)
{
extension=fileName.substring(i+1);
}
if(extension.equalsIgnoreCase("eml"))
{
part.saveFile(saveDir);
extractEML(saveDir, wi);
System.out.println("This is a eml file");
}
else if(extension.equalsIgnoreCase("msg"))
{
part.saveFile(saveDir);
extractMSG(saveDir,wi);
System.out.println("This is a msg file");
}
else
{
System.out.println("This is other file");
}
} else {
System.out.println("Not an eml file");
System.out.println("File Name::"+part.getFileName());
}
}
}
}
public static void extractEML(String emlPath,String wi) throws MessagingException, IOException
{
//String fileName="";
String path=System.getProperty("user.dir") + File.separator + "Docs" + File.separator + wi + File.separator + "EML_PDF";
boolean file =new File(path).mkdir();
if(file)
{
System.out.println("Folder EML_PDF Created Successfully");
}
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
InputStream source = new FileInputStream(emlPath);
MimeMessage message = new MimeMessage(mailSession, source);
System.out.println("Subject : " + message.getSubject());
System.out.println("From : " + message.getFrom()[0]);
System.out.println("--------------");
System.out.println("Body : " + message.getContent());
String contentType = message.getContentType();
if (contentType.contains("multipart")) {
System.out.println("Multipart EMail File");
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
System.out.println("Parts:::"+numberOfParts);
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
String fileName = part.getFileName();
String extension="";
path=path + File.separator + fileName;
int i=fileName.lastIndexOf(".");
if(i>0)
{
extension=fileName.substring(i+1);
}
if(extension.equalsIgnoreCase("pdf"))
{
part.saveFile(path);
}
}
}
}
}
File names for attachments are optional. You need to fix your program to work without a file name.
Properties props = new Properties();
Session mailSession = Session.getDefaultInstance(props, null);
InputStream inputStream = new FileInputStream(FilePath);
MimeMessage message = new MimeMessage(mailSession, inputStream);
MimeMessageParser mimeParser = new MimeMessageParser(message);
mimeParser.parse();
List<DataSource> dsl = mimeParser.getAttachmentList();
for(DataSource ds : dsl) {
InputStream file = ds.getInputStream();
}

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?

Fetch mail in descending order of date using pop3

Here I got all the email in ascending order, means mail retrieved according to last date. I need the reverse.
public void downloadEmailAttachments(String host, int port,String userName, String password)
{
Properties properties = new Properties();
properties.put("mail.pop3.host", host);
properties.put("mail.pop3.port", port);
properties.put("mail.pop3.user",userName);
properties.put("mail.password",password);
properties.setProperty("mail.pop3.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.pop3.socketFactory.fallback", "false");
properties.setProperty("mail.pop3.socketFactory.port",
String.valueOf(port));
Session session = Session.getDefaultInstance(properties);
try {
Store store = session.getStore("pop3");
store.connect(host,userName, password);
Folder folderInbox = store.getFolder("INBOX");
folderInbox.open(Folder.READ_ONLY);
Message[] arrayMessages = folderInbox.getMessages();
for (int i = 0; i < arrayMessages.length; i++) //max=puruna date=after,min=ajika date...
{
if (arrayMessages[i].getSentDate().after(maxDate) && arrayMessages[i].getSentDate().before(minDate))
{
Message message = arrayMessages[i];
Address[] fromAddress = message.getFrom();
String from = fromAddress[0].toString();
Address[]toAdress=message.getAllRecipients();
String to=toAdress[0].toString();
String subject = message.getSubject();
String sentDate = message.getSentDate().toString();
String contentType = message.getContentType().toString();
String messageContent = "";
String attachFiles = "";
if (contentType.contains("multipart")) {
// content may contain attachments
Multipart multiPart = (Multipart) message.getContent();
int numberOfParts = multiPart.getCount();
for (int partCount = 0; partCount < numberOfParts; partCount++) {
MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
// this part is attachment
String fileName = part.getFileName();
attachFiles += fileName + ", ";
part.saveFile(saveDirectory + File.separator + fileName);
} else {
// this part may be the message content
messageContent = part.getContent().toString();
}
}
if (attachFiles.length() > 1) {
attachFiles = attachFiles.substring(0, attachFiles.length() - 2);
}
} else if (contentType.contains("text/plain")
|| contentType.contains("text/html")) {
Object content = message.getContent();
if (content != null) {
messageContent = content.toString();
}
}
System.out.println("Message #" + (i + 1) + ":");
System.out.println("\t From: " + from);
System.out.println("\t to: " + to);
System.out.println("\t Subject: " + subject);
System.out.println("\t Sent Date: " + sentDate);
System.out.println("\t Message: " + messageContent);
System.out.println("\t Attachments: " + attachFiles);
}
new EmailAttachmentReceiver().setSaveDirectory(saveDirectory);
}
folderInbox.close(false);
store.close();
}
You can use Comparator for sorting process
Message[] arrayMessages = folderInbox.getMessages();
Comparator<Message> messageComparator = new Comparator<Message>( {
public int compare(Message m1, Message m2) {
if (m1.getSentDate() == null || m2.getSentDate() == null)
return 0;
return m2.getSentDate().compareTo(m1.getSentDate());
}
});
Arrays.sort(arrayMessages, messageComparator);

Categories