i have a problem with a code of mine. I try to get the text of an email from my Mailserver. After I retrieve the mail, I analyse the message and try to get the bodypart with the type "text/plain" and/or "text/html".
I use following method to split up a MimeMultipart:
private String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException{
String result = "";
int count = mimeMultipart.getCount();
BodyPart bodypart;
String html;
System.out.println("Number of parts: "+count);
for (int i = 0; i < count; i++) {
bodypart=mimeMultipart.getBodyPart(i);
System.out.println("Type of part "+(i+1)+" "+bodypart.getContentType());
System.out.println("Class: "+bodypart.getClass());
if(bodypart.isMimeType("text/plain")){
try{
//if(bodypart==null){
// System.out.println("Null in bodypart");
//}else{
System.out.println((String)bodypart.getContent());//cant get Content!
//}
}catch (IOException e){
System.out.println("IO Exception on attachment"+(i+1)+": "+e+"\n");
}
//result=(String) bodypart.getContent();
}else if (bodypart.isMimeType("text/html")){
try{
html = (String) bodypart.getContent();//cant get Content!
System.out.println(org.jsoup.Jsoup.parse(html).text());
//result = org.jsoup.Jsoup.parse(html).text();
}catch (IOException e){
System.out.println("IOException on part"+(i+1)+": "+e+"\n");
}
}else if (bodypart.isMimeType("multipart/*")){
System.out.println("Openning Multipart bodypart...!\n");
getTextFromMimeMultipart((MimeMultipart) bodypart.getContent());
}else{
System.out.println("No none part?!: "+bodypart.getContentType());
}
}
return result;
}
My Problems lies in .getContent(). it always throws IOException: no Content, eventhough i know there is a text in my mail.
Following output was generated:
Trying:***mail Subject***...
-------------------------------------------------------------------------------
Number of parts: 1
Type of part 1 multipart/alternative;
boundary=_000_************************************************_(snippedout)
Class: class com.sun.mail.imap.IMAPBodyPart
Openning Multipart bodypart...!
Number of parts: 2
Type of part 1 text/plain; charset=Windows-1252
Class: class com.sun.mail.imap.IMAPBodyPart
IO Exception on attachment1: java.io.IOException: No content
Type of part 2 text/html; charset=Windows-1252
Class: class com.sun.mail.imap.IMAPBodyPart
IOException on part2: java.io.IOException: No content
Do I miss something crucial? Am i handling the bodypart correct?
Additional note:
Sorry for not providing the calling function. I have indeed opened the folder
Funktion it is called from:
public void findJunkonBody (String pfolder, String pdestfolder)throws MessagingException, IOException{
Folder folder ;
Store store = null;
Folder destfolder;
MailUtil mutil = new MailUtil(smtphost,user,pass,"imap");
String [] junktermsbody=new String[1];
junktermsbody[0]="Empfangsbestätigung";
try{
store=buildIMAPStore();
store.connect(smtphost,user,pass);
folder = store.getFolder(pfolder);
destfolder = store.getFolder(pdestfolder);
folder.open(Folder.READ_WRITE);
Message[] msgs = folder.getMessages();
int i;
int j;
MimeMultipart mmpart;
for (i=0; i<=(msgs.length-1);i++){
for(j=0;j<=(junktermsbody.length-1);j++){
if (msgs[i].isMimeType("text/plain")){
if(msgs[i].getContent().toString().contains(junktermsbody[j])){
System.out.println("Palin text: "+msgs[i].getSubject());
//move logik
}
}else if (msgs[i].isMimeType("multipart/*")){
mmpart =(MimeMultipart) msgs[i].getContent();
System.out.println("Trying:"+msgs[i].getSubject()+"...\n-------------------------------------------------------------------------------");
if (getTextFromMimeMultipart(mmpart).contains(junktermsbody[j])){
System.out.println("Time to move it!");
//move logik
}
}
}
}
folder.close(true);
}finally{
if (store != null) {store.close();}
//System.out.println("Junk on Body moved successfully");
System.out.println();
}
}
When it comes to plain/text messages you need to open first the java server mail folder.
You need to open the folder before reading the content.
Folder folder = message.getFolder();
// Open folder in read-only mode
if (folder.isOpen()) {
if ((folder.getMode() & Folder.READ_WRITE) != 0) {
folder.close(false);
folder.open(Folder.READ_ONLY);
}
} else {
folder.open(Folder.READ_ONLY);
}
now you can read the message body content:
Object content = message.getContent();
Related
i am trying to transfer files via socket. I've used only a single socket for communication( not according to FTP protocol i guess). The following code will transfer the first file successfully but is not able to tra nsfer second file as the filename doesn't change but the server gets the read bytes of the new data file. I think the problem is of the readUTF and writeUTF.
Here is my server side code. Remember this accepts the file.Not send file.
public int listenPort() throws IOException{
System.out.println("LISTENING");
try{
//this.dis = new DataInputStream(this.socketClient.getInputStream());
if( this.dis.available() != 0 ){
String filename = this.dis.readUTF();
this.fos = new FileOutputStream("/home/ankit07/" + filename);
int bytesRead = (int) IOUtils.copyLarge(this.dis,this.fos); //no of bytes copied
return bytesRead;
}else{
return 0;
}
}finally{
}
}
Here is my client side. Remember this side sends the file. Not accept
public void getFile(String filename) throws IOException{
try{
this.file = this.window.file;
DataOutputStream dos = new DataOutputStream(this.socketClient.getOutputStream());
dos.writeUTF(filename);
FileInputStream fis = new FileInputStream(this.file);
int readByte = (int) IOUtils.copyLarge(fis, dos);
System.out.println("FILE SENT : " + filename + " Bytes :" + readByte);
//this.socketClient.close();
}finally{
//if( this.os!=null) this.os.close();
if( this.window.file != null) this.window.file = null;
if( this.file != null) this.file = null;
//if( this.socketClient!=null) this.socketClient.close();
}
}
The file selections are done in other class window.
The method to select the file is in the window class. This has a public File property to hold the file and then i've called the getFile(String filename) to send the file name and to refer to the selected file, the client has File property to refer to the same file.
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
Object src = e.getSource();
if( src instanceof JButton ){ //Browse clicked
JFileChooser fc = new JFileChooser();
int returnVal = fc.showDialog(null, "SELECT FILE");
if( returnVal == JFileChooser.APPROVE_OPTION){
this.file = fc.getSelectedFile();
try {
this.sc.getFile(this.file.getName());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}else{
//unable to select file
}
}
}
Also i am not able to transfer large files like mp3 and video besides my initial problem. It would be helpful if you'd know any solutions.
Thanks you !!!!
You're sending filename, but then you're sending this.file. There's nothing here to show that they're always referring to the same file. Indeed you have a RS file, in this.window.file. You need to sort out all this confusion.
I have some issue in getting some attachment using ews java API 1.3 SNAPSHOT, i want to get Attachment in my email, here my code :
try {
ExchangeService service;
service.setUrl(new URI("https://" + myserver + "/ews/Exchange.asmx"));
ExchangeCredentials credentials = new WebCredentials(username, password);
service.setCredentials(credentials);
ItemView view = new ItemView(Integer.MAX_VALUE);
view.getOrderBy().add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
Folder folder = Folder.bind(service, WellKnownFolderName.Inbox);
FindItemsResults<Item> results = service.findItems(folder.getId(),view);
service.loadPropertiesForItems(results, new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.Attachments));
for (Item item : results) {
Item itm = Item.bind(service, item.getId(), new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.Attachments));
EmailMessage emailMessage = EmailMessage.bind(service, itm.getId(), new PropertySet(BasePropertySet.FirstClassProperties, EmailMessageSchema.Attachments));
if (emailMessage.getHasAttachments()) {
for (Attachment attachment : emailMessage.getAttachments()) {
String FileExtension = getFileExtension(attachment.getName());
File TempFile = File.createTempFile(attachment.getName(), FileExtension);
attachment.load(TempFile.getAbsolutePath());
}
}
}
} catch (Exception e) {
logger.error("Error ", e.getMessage());
}
My issue is it can get another email that has no attachment and always skip email that has an attachment, the example is like this,
In my inbox i have this email list
from: a#gmail.com (has attachment)
from: b#mycompany.com (no attachment)
from: c#hiscompany.com (has attachment)
from: d#mycompany.com (no attachment)
And when i run my code, it always get email that has no attachment, like this:
from: b#mycompany.com (no attachment)
from: d#mycompany.com (no attachment)
and skip the other email that has attachment, i have no idea how can this happen. Can someone help me please?
HashMap<String, HashMap<String, String>> attachments = new HashMap<String, HashMap<String, String>>();
if (emailMessage.getHasAttachments() || emailMessage.getAttachments().getItems().size() > 0) {
//get all the attachments
AttachmentCollection attachmentsCol = emailMessage.getAttachments();
log.info("File Count: " +attachmentsCol.getCount());
//loop over the attachments
for (int i = 0; i < attachmentsCol.getCount(); i++) {
Attachment attachment = attachmentsCol.getPropertyAtIndex(i);
//log.debug("Starting to process attachment "+ attachment.getName());
//FileAttachment - Represents a file that is attached to an email item
if (attachment instanceof FileAttachment || attachment.getIsInline()) {
attachments.putAll(extractFileAttachments(attachment, properties));
} else if (attachment instanceof ItemAttachment) { //ItemAttachment - Represents an Exchange item that is attached to another Exchange item.
attachments.putAll(extractItemAttachments(service, attachment, properties, appendedBody));
}
}
}
} else {
log.debug("Email message does not have any attachments.");
}
//Extract File Attachments
try {
FileAttachment fileAttachment = (FileAttachment) attachment;
// if we don't call this, the Content property may be null.
fileAttachment.load();
//extract the attachment content, it's not base64 encoded.
attachmentContent = fileAttachment.getContent();
if (attachmentContent != null && attachmentContent.length > 0) {
//check the size
int attachmentSize = attachmentContent.length;
//check if the attachment is valid
ValidateEmail.validateAttachment(fileAttachment, properties,
emailIdentifier, attachmentSize);
fileAttachments.put(UtilConstants.ATTACHMENT_SIZE, String.valueOf(attachmentSize));
//get attachment name
String fileName = fileAttachment.getName();
fileAttachments.put(UtilConstants.ATTACHMENT_NAME, fileName);
String mimeType = fileAttachment.getContentType();
fileAttachments.put(UtilConstants.ATTACHMENT_MIME_TYPE, mimeType);
log.info("File Name: " + fileName + " File Size: " + attachmentSize);
if (attachmentContent != null && attachmentContent.length > 0) {
//convert the content to base64 encoded string and add to the collection.
String base64Encoded = UtilFunctions.encodeToBase64(attachmentContent);
fileAttachments.put(UtilConstants.ATTACHMENT_CONTENT, base64Encoded);
}
//Extract Item Attachment
try {
ItemAttachment itemAttachment = (ItemAttachment) attachment;
PropertySet propertySet = new PropertySet(
BasePropertySet.FirstClassProperties, ItemSchema.Attachments,
ItemSchema.Body, ItemSchema.Id, ItemSchema.DateTimeReceived,
EmailMessageSchema.DateTimeReceived, EmailMessageSchema.Body);
itemAttachment.load();
propertySet.setRequestedBodyType(BodyType.Text);
Item item = itemAttachment.getItem();
eBody = appendItemBody(item, appendedBody.get(UtilConstants.BODY_CONTENT));
appendedBody.put(UtilConstants.BODY_CONTENT, eBody);
/*
* We need to check if Item attachment has further more
* attachments like .msg attachment, which is an outlook email
* as attachment. Yes, we can attach an email chain as
* attachment and that email chain can have multiple
* attachments.
*/
AttachmentCollection childAttachments = item.getAttachments();
//check if not empty collection. move on
if (childAttachments != null && !childAttachments.getItems().isEmpty() && childAttachments.getCount() > 0) {
for (Attachment childAttachment : childAttachments) {
if (childAttachment instanceof FileAttachment) {
itemAttachments.putAll(extractFileAttachments(childAttachment, properties, emailIdentifier));
} else if (childAttachment instanceof ItemAttachment) {
itemAttachments = extractItemAttachments(service, childAttachment, properties, appendedBody, emailIdentifier);
}
}
}
} catch (Exception e) {
throw new Exception("Exception while extracting Item Attachments: " + e.getMessage());
}
My issue goes as follows:
I have My code setup to read emails from a particular account. That part works perfectly.
the issue is with parsing the Email message. Separating attachments and email body(containing inline images).
My code goes like this:
Void readMessages(Folder folder){
Message[] messages = folder.getMessages();
// loading of message objects.
for (int messageNumber = 0; messageNumber < messages.length; messageNumber++) {
final Message currentMessage = messages[messageNumber];
logger.info("Handling the mail with subject " + currentMessage.getSubject());
logger.info("Content type for the current message is " + currentMessage.getContentType());
final String messageFileName = currentMessage.getFileName();
logger.info("File name for the message " + messageFileName + ". File name is blank "
+ StringUtils.isBlank(messageFileName));
Object messageContentObject = currentMessage.getContent();
if (messageContentObject instanceof Multipart) {
Multipart multipart = (Multipart) messageContentObject;
// downloading all attachments....
int attachmentCount = multipart.getCount();
logger.info("Number of attachments ");
for (int i = 0; i < attachmentCount; i++) {
Part part = (Part) multipart.getBodyPart(i);
downloadAttachment(part, folderPath.toString());
}
}
}
}
}
private void downloadAttachment(Part part, String folderPath) throws Exception {
String disPosition = part.getDisposition();
String fileName = part.getFileName();
String decodedText = null;
logger.info("Disposition type :: " + disPosition);
logger.info("Attached File Name :: " + fileName);
if (disPosition != null && disPosition.equalsIgnoreCase(Part.ATTACHMENT)) {
logger.info("DisPosition is ATTACHMENT type.");
File file = new File(folderPath + File.separator + decodedText);
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
} else if (fileName != null && disPosition == null) {
logger.info("DisPosition is Null type but file name is valid. Possibly inline attchment");
File file = new File(folderPath + File.separator + decodedText);
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
} else if (fileName == null && disPosition == null) {
logger.info("DisPosition is Null type but file name is null. It is email body.");
File file = new File(folderPath + File.separator + "mail.html");
file.getParentFile().mkdirs();
saveEmailAttachment(file, part);
}
}
protected int saveEmailAttachment(File saveFile, Part part) throws Exception {
BufferedOutputStream bos = null;
InputStream is = null;
int ret = 0, count = 0;
try {
bos = new BufferedOutputStream(new FileOutputStream(saveFile));
part.writeTo(new FileOutputStream(saveFile));
} finally {
try {
if (bos != null) {
bos.close();
}
if (is != null) {
is.close();
}
} catch (IOException ioe) {
logger.error("Error while closing the stream.", ioe);
}
}
return count;
}
The problem i get is when i run this code, i get an HTML file but the inline images is replaced by a sign for error image which indicates the image with no source.
Please help me out with. Let me know if any more info is required.
I also tried saving the body as an .eml file by changing:
File file = new File(folderPath + File.separator + "mail.html");
to
File file = new File(folderPath + File.separator + "mail.eml");
BUt i got the same results.
I wrote below code to convert email body text to pdf including inline images.
in code i replaced the image code(ex: cid:image001.jpg#01D17AAA.1EA2A6A0) with download image path. I am constructing the "hashmap" for image key and download path while downloading the image.
HTMLWorker htmlWorker = new HTMLWorker(document);
if(bodyStr!=null)
{
//find inline images
inlineImages=downloadInLineImage(mostRecentMatch, dynamicOutputDirectory);
if(inlineImages!=null)
{
for (Map.Entry<String, String> entry : inlineImages.entrySet()) {
//System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
bodyStr=bodyStr.replaceAll("cid:"+entry.getKey() , entry.getValue());
}
}
htmlWorker.parse(new StringReader(bodyStr));
}
Download Inline image with passing Item.
private HashMap<String,String> downloadInLineImage(Item item, String dynamicOutputDirectory)
throws Exception, ServiceLocalException {
//create output directory if not present
//bind the item to a new email message. if you do not bind, then the getHasAttachments() function will fail
EmailMessage mostRecentMatch = (EmailMessage)item;
String from = mostRecentMatch.getFrom().getAddress();
String user =StringUtils.substringBefore(from, "#");
AttachmentCollection collection=item.getAttachments();
HashMap<String,String> inlineFiles=new HashMap<String,String>();
if(collection.getCount()>0)
{
for (Attachment attachment : collection.getItems()) {
if(attachment.getIsInline())
{
FileAttachment currentFile = (FileAttachment) attachment;
String filePath=dynamicOutputDirectory+"/"+user+currentFile.getName();
File file=new File(filePath);
FileOutputStream fio=new FileOutputStream(file);
currentFile.load(fio);
inlineFiles.put(currentFile.getContentId(), filePath);
fio.close();
}
}
}
References to inlined images are replaced by cid: URNs like <img src="cid:SOMEID">, because there are no filenames in an email. SOMEID refers to the Content-ID of the Multipart "objects".
In order to get it work, you have to store the multipart attachments to files (e.g., temporary names) and replace the cid URNs by the real file names.
*I am working on an application which can read emails. I am using textview / edittext to display the mails. Right now I am able to fetch the email content as string and display it.
But Which is the best view to display emails with html content and images??
Please help me out.
Thank you :)
Edited:
I used webview as suggested by S.O. friends(thanks to #Andro Selva, #CFlex).
But I am facing a problem, Its displaying the email's body twice! :(
Once as a text/plain and again as a Text/html.
I have tried following codes to load webview.
webViewBody.loadData(details[3], "text/html", "UTF-8");
//webViewBody.loadDataWithBaseURL(null, details[3] , "text/html", "utf-8", null);
here details[3] is the email content.
What am i missing here!? :( Please help me out.
EDITED:
I have Added codes I have Used to get the message contents for displaying email content below.
public void getContent(Message msg)
{
try
{
Object o = msg.getContent();
if (o instanceof String)
{
if(((String) o).equalsIgnoreCase(""))
{
}
else
{
messageBody = (String)o+"STRING!!";
}
}
else if (o instanceof Multipart)
{
Multipart mp = (Multipart)o;
int count3 = mp.getCount();
for (int j = 0; j < count3-1; j++)
{
// Part are numbered starting at 0
BodyPart b = mp.getBodyPart(j);
Object o2 = b.getContent();
if (o2 instanceof String)
{
if(((String) o).equalsIgnoreCase(""))
{
}
else
{
messageBody = (String)o2+"MULTIPART!!";
}
}
} //End of for
}
else if (o instanceof InputStream)
{
//System.out.println("**This is an InputStream message**");
InputStream is = (InputStream)o;
// Assumes character content (not binary images)
//messageBody = convertStreamToString(is)+"INPUT STREAM!!";
int c;
while ((c = is.read()) != -1)
{
messageBody = convertToString(is)+"INPUT STREAM!!";
System.out.println(messageBody);
}
}
}
catch (Exception ex)
{
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
//TODO TEST CODES
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 String convertToString(InputStream inputStream)
{
StringBuffer string = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try
{
while ((line = reader.readLine()) != null)
{
string.append(line + "\n");
}
}
catch (IOException e)
{
}
return string.toString();
}
The control is always going to "else if (o instanceof InputStream)" condition. so its streaming email always and displaying complete email content. What am I missing here?
I think you will need to implement a WebView, because it can format the html AND display images.
AFAIK, A textView with html can format the content but cannot display the images.
Edit:
The following should work:
webViewBody.loadData(details[3], "text/html", null);
Probably you are displaying all the email content that can be composed by html and plain text content in the same email.
This is caused because this kind of email is multipart content and u need to split-it, you also need to separate attachments and images (embedded)
see if your "details" is not returning a multipart content body.
The detail gets displayed twice just because of two times you have written:
webViewBody.loadData(details[3], "text/html", "UTF-8");
webViewBody.loadDataWithBaseURL(null, details[3] , "text/html", "utf-8", null);
Probable Solution: Use either loadData() or loadDataWithBaseURL().
adding these lines solved the problem!
MailcapCommandMap mc = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mc.addMailcap("text/html;; x-java-content-handler=com.sun.mail.handlers.text_html");
mc.addMailcap("text/xml;; x-java-content-handler=com.sun.mail.handlers.text_xml");
mc.addMailcap("text/plain;; x-java-content-handler=com.sun.mail.handlers.text_plain");
mc.addMailcap("multipart/*;; x-java-content-handler=com.sun.mail.handlers.multipart_mixed");
mc.addMailcap("message/rfc822;; x-java-content-handler=com.sun.mail.handlers.message_rfc822");
CommandMap.setDefaultCommandMap(mc);
Thanks to everyone who helped me to solve this. :)
For a few weeks I have been developing a email client for android, I have been ignoring parsing email content for a while as I have never been able to get it to work. Thus, the time has come to ask for help!
I have been looking around and I have come across a few methods I have tried but never had much success with! Currently my closest attempt would have to be:
private String parseContent(Message m) throws Exception
{
//Multipart mp = (Multipart)c;
//int j = mp.getCount();
/*for (int i = 0; i < mp.getCount(); i++)
{
Part part = mp.getBodyPart(i);
System.out.println(((MimeMessage)m).getContent());
content = content + part.toString();
//System.out.println((String)part.getContent());
}*/
Object content = m.getContent();
String contentReturn = null;
if (content instanceof String)
{
contentReturn = (String) content;
}
else if (content instanceof Multipart)
{
Multipart multipart = (Multipart) content;
BodyPart part = multipart.getBodyPart(0);
part.toString();
contentReturn = part.getContent().toString();
}
return contentReturn;
}
But it does not work and I get gibberish such as "javax.mail.internet.MimeMultipart#44f12450".
Can anyone see where I am going wrong?
Thanks,
Rhys
None of the above suggestions is valid. You don't need to do anything complex here. Mimemessage has got message.writeTo(outputStream);
All you need to print the message is:
message.writeTo(System.out);
The above code will print the actual mime message to the console (or you can use any logger).
Save the content to .eml and you can open it in outlook. Simple as that!
Multipart multipart = (Multipart) content;
BodyPart part = multipart.getBodyPart(0);
part.toString();
contentReturn = part.getContent().toString();
When you have BodyPart part, you should keep testing
if(part.getContent() instanceof String){
...
}
I had the same issues while parsing Message of javax mail. In my workaround i found a weird thing. Listing mail from POP3 was not giving me Mail body content. So used IMAP which worked for me. Now i'm able to parse Text/plain as well as Text/Html and read the body. To parse the same i used following method.
public String printMessage(Message message) {
String myMail = "";
try {
// Get the header information
String from = ((InternetAddress) message.getFrom()[0])
.getPersonal();
if (from == null)
from = ((InternetAddress) message.getFrom()[0]).getAddress();
System.out.println("FROM: " + from);
String subject = message.getSubject();
System.out.println("SUBJECT: " + subject);
// -- Get the message part (i.e. the message itself) --
Part messagePart = message;
Object content = messagePart.getContent();
// -- or its first body part if it is a multipart message --
if (content instanceof Multipart) {
messagePart = ((Multipart) content).getBodyPart(0);
System.out.println("[ Multipart Message ]");
}
// -- Get the content type --
String contentType = messagePart.getContentType();
// -- If the content is plain text, we can print it --
System.out.println("CONTENT:" + contentType);
if (contentType.startsWith("TEXT/PLAIN")
|| contentType.startsWith("TEXT/HTML")) {
InputStream is = messagePart.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
String thisLine = reader.readLine();
while (thisLine != null) {
System.out.println(thisLine);
myMail = myMail + thisLine;
thisLine = reader.readLine();
}
}
System.out.println("-----------------------------");
} catch (Exception ex) {
ex.printStackTrace();
}
return myMail;
}
Hope it helps someone.
I also got the same error any tried almost every thing, but the solution worked for me is
private String getFinalContent(Part p) throws MessagingException,
IOException {
String finalContents = "";
if (p.getContent() instanceof String) {
finalContents = (String) p.getContent();
} else {
Multipart mp = (Multipart) p.getContent();
if (mp.getCount() > 0) {
Part bp = mp.getBodyPart(0);
try {
finalContents = dumpPart(bp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return finalContents.trim();
}
private String dumpPart(Part p) throws Exception {
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream)) {
is = new BufferedInputStream(is);
}
return getStringFromInputStream(is);
}
private String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
Hope this will help someone.
Not entirely sure, but what it sounds like is you want to convert a MimeMessage into a String. Strictly speaking, there is no "standard" translation for MimeMessage to String, but here is a chunk of code that I wrote a couple of years back that attempts to generate one such translation. Only tested on English messages, so i18n will have to be something you think about yourself.
Unfortunately SO's stupid filter seems to think that my code sample is an image and won't let me post it: take a look at the class at http://pastebin.com/pi9u5Egq : the code is doing a bunch of otherwise unnecessary things (it was spitting it out into HTML that was rendered using flying saucer), and also requires Jakarta Commons Lang, javamail and activation libraries, but it works for me. You would invoke it like this:
fetchText(message, null, false, false);
To get a text string. Try that out for size.