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();
}
Related
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();
}````
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/
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?
I am uploading image from url on ftp by this code.
Image uploaded successful but when i try to resize uploaded image get error as the follows.
String imageUrl = "http://www.totaldesign.ir/wp-content/uploads/2014/11/hamayesh.jpg";
FTPClient ftpClient = new FTPClient();
ftpClient.connect(ftp_server, ftp_port);
ftpClient.login(ftp_user, ftp_pass);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
// APPROACH #2: uploads second file using an OutputStream
URL url = new URL(imageUrl);
//**************select new name for image***********/
//get file extention
File file = new File(imageUrl);
String ext = getFileExtension(file);
//get file name from url
String fileName = imageUrl.substring(imageUrl.lastIndexOf('/') + 1, imageUrl.length());
String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));
//create new image name for upload
String img_name = "simjin.com_" + fileNameWithoutExtn;
//get current year time for image upload dir
Date date = new Date();
DateFormat yeae = new SimpleDateFormat("yyyy");
String current_year = yeae.format(date);
//create dirs if not exist
ftpClient.changeWorkingDirectory(current_year);
int dirCode = ftpClient.getReplyCode();
if (dirCode == 550) {
//create dir
ftpClient.makeDirectory(current_year);
System.out.println("created folder: " + current_year);
}
//get current month time for image upload dir
DateFormat month = new SimpleDateFormat("MM");
String current_month = month.format(date);
//create dirs if not exist
ftpClient.changeWorkingDirectory("/" + current_year + "/" + current_month);
dirCode = ftpClient.getReplyCode();
if (dirCode == 550) {
//create dir
ftpClient.makeDirectory("/" + current_year + "/" + current_month);
System.out.println("created folder: " + "/" + current_year + "/" + current_month);
}
String uploadDir = "/" + current_year + "/" + current_month;
//rename image file if exist
boolean exists;
String filePath = uploadDir + "/" + img_name + "." + ext;
exists = checkFileExists(filePath);
System.out.println("old file path=> " + exists);
//Rename file if exist
int i = 0;
while (exists) {
i++;
img_name = "simjin.com_" + fileNameWithoutExtn + i;
filePath = uploadDir + "/" + img_name + "." + ext;
exists = checkFileExists(filePath);
//break loop if file dont exist
if (!exists) {
break;
}
}
System.out.println("new file path=> " + filePath);
//set image name in array for return
result[0] = img_name;
//*************end select new name for image**********/
System.out.println("ftpClinet Replay Code=> " + ftpClient.getStatus());
//Start uploading second file
InputStream inputStream = new BufferedInputStream(url.openStream());
OutputStream outputStream = ftpClient.storeFileStream(filePath);
System.out.println("outputStream Status=> " + outputStream);
byte[] bytesIn = new byte[10240];
int read = 0;
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
}
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
after success upload. I want to resize image by thumbnailator:
if (completed) {
System.out.println("The file is uploaded successfully.");
String new_img_name = uploadDir + "/" + img_name + "-150x150" + "." + ext;
OutputStream os = ftpClient.storeFileStream(filePath);
Thumbnails.of(image_url).size(150, 150).toOutputStream(os);
}
in this section get this error:
OutputStream cannot be null
Where is my wrong? And how to fix it?
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);