I am working on a project in which a James mailet receives a message with an attachment with a long file name, and the name needs to be changed to something shorter when delivering it to its destination. This is to meet a specific requirement.
javax.mail.internet.MimeMessage msg = mail.getMessage();
// Change file name.
String contentType = msg.getContentType();
System.out.println("content type: " + contentType);
if (contentType != null && contentType.contains("multipart")) {
try {
Multipart multipart = (Multipart) msg.getContent();
int totalNumberOfBodyParts = multipart.getCount();
for (int i = 0; i < totalNumberOfBodyParts; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
String bodyPartFileName = bodyPart.getFileName();
if (bodyPartFileName != null && !bodyPartFileName.isEmpty() && !"null".equalsIgnoreCase(bodyPartFileName)) {
System.out.println(" bodyPartFileName: " + bodyPartFileName);
if (bodyPartFileName.length() > 12) {
// Get the file name suffix.
int index = bodyPartFileName.lastIndexOf('.');
if(index > 0) {
multipart.removeBodyPart(bodyPart);
String extension = bodyPartFileName.substring(index + 1); // Everything past the dot.
// Get new file name.
String newFilePrefix = bodyPartFileName.substring(index - 8, index).replace("-", "_");
String newFileName = (newFilePrefix + "." + extension).toUpperCase();
System.out.println(" Proposed file name: " + newFileName);
// Set the new file name.
bodyPart.setFileName(newFileName);
// Replace existing body part with the one that has the new file name.
multipart.addBodyPart(bodyPart, i);
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
// Attempting to save the changes just made to the file name.
msg.saveChanges();
// This is to show that the file name change did not save.
if (contentType != null && contentType.contains("multipart")) {
try {
Multipart multipart = (Multipart) msg.getContent();
int totalNumberOfBodyParts = multipart.getCount();
for (int i = 0; i < totalNumberOfBodyParts; i++) {
BodyPart bodyPart = multipart.getBodyPart(i);
String bodyPartFileName = bodyPart.getFileName();
if (bodyPartFileName != null && !bodyPartFileName.isEmpty() && !"null".equalsIgnoreCase(bodyPartFileName)) {
// The name does not seem to have changed.
System.out.println(" bodyPartFileName after attempted change: " + bodyPartFileName);
}
}
} catch (IOException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
}
}
No stack traces are being produced. So I assume that no exceptions are being thrown when calling setFileName().
How can I change the name of the attachment before sending the message to its destination?
Related
java
As you can see in the below code in sonar its give the "Extract this nested try block into a separate method". I am not understand how to resolve this issue please anyone can help.
Vector<?> allFiles = channelSftp.ls(remoteDirectory + "/");
for (int i = 0; i < allFiles.size(); i++) {
LsEntry le = (LsEntry) allFiles.get(i);
String strName = le.getFilename();
if (strName.startsWith(prefixFileName)) {
fileName = strName;
break;
}
}
remoteFilePath = remoteDirectory + fileName;
localFilePath = localDirectory + fileName;
try {
channelSftp.get(remoteFilePath, localFilePath);
} catch (SftpException e) {
migrationRunBatchRepository.updateBatchStatus(migrationRunBatch.getMromRunSeqId(),
migrationRunBatch.getMromBatchSeqId(), MROMConstants.MIGRATION_RUN_STATUS_RETRY,
MROMConstants.MC_NM1TRIGGER_JOB_USER);
throw new FileTransferException("File Not Found in Remote Directory", e);
}
channelSftp.rm(remoteFilePath);
channelSftp.exit();
session.disconnect();
int count = migrationRunRepository.getCmRunIdCount(cmrunid);
if (acceptDuplicateCmRunId || count > 0) {
Long mromRunSeqId = (long) chunkContext.getStepContext().getJobParameters()
.get(MROMConstants.MROM_RUN_SEQ_ID);
I have some code to read people's inbox, with a filter on send TO or FROM. The time it takes to make it process the messages is far too long.
The search term filters my total emails down to 6 emails from a specific sender, yet to process the emails it takes 4 seconds to create my email objects. I'm wondering if there is a better / faster way to do this. since I want to use this for more than just 6 emails. I'm using imaps settings with user and password to authenticate.
public static List<Email> readBox(String host, String user, String pass, String protocol, String port,String downloadDir,String checksubject,String checkatt,List<String> checkfromemail,List<String> checktoemail,String mailFolder) throws Exception {
int iport = 0;
StopWatch stopwatch = new StopWatch();
stopwatch.start();
try{
iport = Integer.parseInt(port.trim());
}catch(Exception e){}
List<Email> emails = new ArrayList<Email>();
Properties props = new Properties();
Session session = Session.getDefaultInstance(props);
URLName urln = new URLName(protocol, host, iport, null, user, pass);
Store store = session.getStore(urln);
store.connect(host, user, pass);
Folder folder = store.getFolder(mailFolder);
folder.open(Folder.READ_WRITE);
try {
OrTerm orTerms = null;
SearchTerm terms = null;
if(checkfromemail.size()>0) {
SearchTerm [] search = new SearchTerm[checkfromemail.size()];
for(int j = 0; j < checkfromemail.size(); j++) {
search[j] = new FromStringTerm(checkfromemail.get(j).trim());
}
orTerms = new OrTerm(search);
}
if(checktoemail.size() > 0) {
SearchTerm [] search = new SearchTerm[checktoemail.size()];
for(int j = 0; j < checktoemail.size(); j++) {
search[j] = new RecipientStringTerm(Message.RecipientType.TO, checktoemail.get(0).trim());
}
orTerms = new OrTerm(search);
}
if(orTerms != null) {
emails = readInboxMailBox(folder.search(orTerms),downloadDir,checksubject,checkatt,checkfromemail,checktoemail,false,-1);
}else {
emails = readInboxMailBox(folder.getMessages(),downloadDir,checksubject,checkatt,checkfromemail,checktoemail,false,-1);
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}finally {
folder.close(false);
store.close();
}
stopwatch.stop();
System.out.println("readed emails in " + stopwatch.getTotalTimeMillis() + " miliseconds ");
return emails;
}
private static List<Email> readInboxMailBox(Message[] messages,String downloadDir,String checksubject,String checkatt,List<String> checkfromemail,List<String> checkmailto,boolean delete,int numberOfMessages) {
List<Email> emails = new ArrayList<Email>();
StopWatch stopwatch = new StopWatch();
stopwatch.start();
try {
// Get directory listing
for (int i = 0; i < messages.length; i++) {
// get last message
if(numberOfMessages > 0) {
if(i < ( messages.length - numberOfMessages)) {
continue;
}
}
Email email = new Email();
// from
email.from = messages[i].getFrom()[0].toString();
// cc list
Address[] toArray = null;
try {
toArray = messages[i].getRecipients(Message.RecipientType.TO);
} catch (Exception e) { toArray = null; }
if (toArray != null) {
for (Address to : toArray) {
email.to.add(to.toString());
}
}
// cc list
Address[] ccArray = null;
try {
ccArray = messages[i].getRecipients(Message.RecipientType.CC);
} catch (Exception e) { ccArray = null; }
if (ccArray != null) {
for (Address c : ccArray) {
email.cc.add(c.toString());
}
}
// subject
email.subject = messages[i].getSubject();
if(!checksubject.trim().equals("")) {
if(!email.subject.toLowerCase().contains(checksubject.toLowerCase().trim())) {
continue;
}
}
// received date
if (messages[i].getReceivedDate() != null) {
email.received = messages[i].getReceivedDate();
} else {
email.received = new Date();
}
// body and attachments
email.body = "";
Object content = messages[i].getContent();
if (content instanceof java.lang.String) {
email.body = (String) content;
} else if (content instanceof Multipart) {
Multipart mp = (Multipart) content;
for (int j = 0; j < mp.getCount(); j++) {
Part part = mp.getBodyPart(j);
String disposition = part.getDisposition();
if (disposition == null) {
MimeBodyPart mbp = (MimeBodyPart) part;
if (mbp.isMimeType("text/plain") || mbp.isMimeType("text/html")) {
// Plain
email.body += (String) mbp.getContent();
}
else if (mbp.isMimeType("multipart/*")) {
MimeMultipart mimeMultipart = (MimeMultipart) mbp.getContent();
try {
email.body += getTextFromMimeMultipart(mimeMultipart);
}catch(Exception e) {
e.printStackTrace();
}
}
}
// else if ((disposition != null) && (disposition.equalsIgnoreCase(Part.ATTACHMENT) || disposition.equalsIgnoreCase(Part.INLINE))) {
//
// if(decodeName(part.getFileName()).trim().endsWith(".vcf")){
// continue;
// }
// if(!checkatt.trim().equals("")) {
// String checkfile = decodeName(part.getFileName()).trim();
// if(!isFileMatchTargetFilePattern(checkfile,checkatt.trim())){
// continue;
// }
// }
// EmailAttachment attachment = new EmailAttachment();
//
// attachment.name = saveName(decodeName(part.getFileName()));
// File savedir = new File(downloadDir);
// savedir.mkdirs();
// File savefile = new File(downloadDir,attachment.name);
// String path = STR.Replace(savefile.getAbsolutePath(),attachment.name,"");
// attachment.path = path;
// attachment.size = saveFile(savefile, part);
// email.attachments.add(attachment);
//
// }
} // end of multipart for loop
} // end messages for loop
if(!checkatt.trim().equals("")) {
if(email.attachments.size()<=0) {
continue;
}
}
emails.add(email);
// Finally delete the message from the server.
if(delete) {
messages[i].setFlag(Flags.Flag.DELETED, true);
}else {
//messages[i].setFlag(Flags.Flag.SEEN, true);
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
}
stopwatch.stop();
System.out.println("processed emails in " + stopwatch.getTotalTimeMillis() + " miliseconds ");
return emails;
}
private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException{
String result = "";
int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result = result + "\n" + bodyPart.getContent();
break; // without break same text appears twice in my tests
} else if (bodyPart.isMimeType("text/html")) {
String html = (String) bodyPart.getContent();
result = result + "\n" + org.jsoup.Jsoup.parse(html).text();
} else if (bodyPart.getContent() instanceof MimeMultipart){
result = result + getTextFromMimeMultipart((MimeMultipart)bodyPart.getContent());
}
}
return result;
}
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 am trying to read my messages, I can get it to print the header but the from and the content are displayed funny.
Here is the code I am using to display the messages:
int j = message.length-1;
for (int i=j;i>=0;i--) {
System.out.println("Message " + (i + 1));
System.out.println("From : " + message[i].getFrom());
System.out.println("Subject : " + message[i].getSubject());
try {
System.out.println("Body: " + message[i].getContent());
} catch (IOException ex) {
System.out.println(ex);
}
}
The output is as follows:
Message 1:
From: [javax.mail.internet.InternetAddress;#175831e]
Subject: Hello //This is correct
Body: javax.mail.internet.MimeMultipart#15b5219
Why doesn't this print out the actual email address for the from statement? And why doesn't it print out the actual body content? (I am only interesting in the plain text.)
Whole code:
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.search.*;
import java.util.*;
import com.sun.mail.imap.*;
import java.io.*;
public class MailClient {
public static void main(String[] args) {
try {
Properties props = new Properties();
props.put("mail.store.protocol","imaps");
Session session;
session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com","email#gmail.com","password");
IMAPFolder folder = (IMAPFolder) store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
Flags seen = new Flags(Flags.Flag.SEEN);
FlagTerm unseenFlagTerm = new FlagTerm(seen,false);
Message message[] = folder.search(unseenFlagTerm);
int j = message.length-1;
for (int i=j;i>=0;i--) {
System.out.println("Message " + (i + 1));
System.out.println("From : " + message[i].getFrom());
System.out.println("Subject : " + message[i].getSubject());
try {
System.out.println("Body: " + message[i].getContent());
} catch (IOException ex) {
System.out.println(ex);
}
}
System.out.println(newMsg);
folder.close(false);
store.close();
}
catch (MessagingException e) {
System.out.println("Error: " + e);
}
}
}
Thanks!
For plain text and html messages:
String content= messages[i].getContent().toString();
For Multipart Messages:
Multipart multipart = (Multipart) messages[i].getContent();
for (int j = 0; j < multipart.getCount(); j++) {
BodyPart bodyPart = multipart.getBodyPart(j);
String disposition = bodyPart.getDisposition();
if (disposition != null && (disposition.equalsIgnoreCase("ATTACHMENT"))) { // BodyPart.ATTACHMENT doesn't work for gmail
System.out.println("Mail have some attachment");
DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());
}
else {
System.out.println("Body: "+bodyPart.getContent());
content= bodyPart.getContent().toString();
}
The JavaMail FAQ tells you how to access the main text body of a message.
change this
message[i].getFrom()
to
message[i].getFrom()[0].toString())
Try to use next:
message[i].writeTo(System.out);
i know how can we retrive the mails from INBOX folder...but now i want to retrieve mails from SENT ITEMS folder...i am using imap to retrieve the data...
Let me know what parameter i should pass in this function to get mails from SENT ITEMS folder
Folder folder=store.getFolder("inbox");i should change the inbox as some stirng i want to know that string...
There is not a standard name here. The IMAP spec requires that the inbox be called "INBOX", but no other folders are specifically defined. It's just a name of a folder after all - some providers will use "Sent", some will use "Sent Items" and you might even see some other variants about.
I'd recommend listing the folders that the server knows about, and selecting the appropriate one from there (either interactively, or perhaps grepping for "sent" in the name if running headless). A better option overall might be to make this a configurable parameter (if your application already has a properties file).
Of course, if this is a throwaway project you could just hard-code the value for the specific server in question. But if you want to do it properly, you'll need to be flexible.
I found the solution for my problem....
i used this code to list out the folders from mail server
and pass those values in getFolder() function...it's working fine..
Folder[] folderList = store.getDefaultFolder().list();
for (int i = 0; i < folderList.length; i++) {
System.out.println(folderList[i].getFullName());
}
Gmail stores sent mails under a folder called Sent Mail inside [Gmail] folder. So I was able to get the sent mail folder through this;
Folder sentMail = store.getFolder( "[Gmail]" ).getFolder( "Sent Mail" );
This code will retrieve all mails and will print the contents and store in local if have any attachment
public class MailReader {
Folder inbox;
public MailReader() {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
try {
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("imaps");
store.connect("imap.gmail.com", "username",
"password");
/* Mention the folder name which you want to read. */
inbox = store.getFolder("Inbox");
System.out.println("No of Unread Messages : "
+ inbox.getMessageCount() + " "
+ inbox.getUnreadMessageCount());
/* Open the inbox using store. */
inbox.open(Folder.READ_ONLY);
/*
* Get the messages which is unread in the Inbox Message messages[]
* = inbox.search(new FlagTerm( new Flags(Flag.SEEN), false));
*/
Message messages[] = inbox.getMessages();
/* Use a suitable FetchProfile */
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.CONTENT_INFO);
inbox.fetch(messages, fp);
try {
printAllMessages(messages);
inbox.close(true);
store.close();
} catch (Exception ex) {
System.out.println("Exception arise at the time of read mail");
ex.printStackTrace();
}
} catch (NoSuchProviderException e) {
e.printStackTrace();
System.exit(1);
} catch (MessagingException e) {
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]);
}
}
/* Print the envelope(FromAddress,ReceivedDate,Subject) */
public void printEnvelope(Message message) throws Exception {
Address[] a;
// FROM
if ((a = message.getFrom()) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("FROM: " + a[j].toString());
}
}
// TO
if ((a = message.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++) {
System.out.println("TO: " + a[j].toString());
}
}
String subject = message.getSubject();
Date receivedDate = message.getReceivedDate();
String content = message.getContent().toString();
System.out.println("Subject : " + subject);
System.out.println("Received Date : " + receivedDate.toString());
System.out.println("Content : " + content);
getContent(message);
}
public void getContent(Message msg) {
try {
String contentType = msg.getContentType();
System.out.println("Content Type : " + contentType);
Multipart mp = (Multipart) msg.getContent();
int count = mp.getCount();
for (int i = 0; i < count; i++) {
dumpPart(mp.getBodyPart(i));
}
} catch (Exception ex) {
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
}
public void dumpPart(Part p) throws Exception {
// Dump input stream ..
if (p.getFileName() == null) {
return;
}
System.out.println("filename:" + p.getFileName());
System.out.println(p.ATTACHMENT);
InputStream is = p.getInputStream();
File file = new File(p.getFileName());
FileOutputStream fout = null;
fout = new FileOutputStream(p.getFileName());
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream)) {
is = new BufferedInputStream(is);
}
int c;
System.out.println("Message : ");
while ((c = is.read()) != -1) {
fout.write(c);
}
if (fout != null) {
fout.close();
}
}
public static void main(String args[]) {
new MailReader();
}
}