ClassCastException at Multipart mp = (Multipart) msg[i
i want to get the attachments from emails. most of the times it works, but then i send a new mail and nothing works anymore. does anybody knows how to handle this problem, that it works really anything i need it.
here a short extract out of my code:
Properties props = System.getProperties();
Session session = Session.getDefaultInstance(props, null);
Store store = session.getStore("pop3");
store.connect(hostname, username, password);
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
System.out.println(folder.getMessageCount() + " Nachricht(en) vorhanden");
Message [] msg = folder.getMessages();
for (int i=0; i < msg.length; i++){
Files tmp = new Files();
Address[] adr = msg.getFrom();
tmp.setEmail(adr[0].toString());
Multipart multipart = (Multipart) msg[i].getContent();
String inputFile = null;
for(int j=0; j < multipart.getCount(); j++){
inputFile = processPart(multipart.getBodyPart(j));
}//for
Hi,
Only if the type of your content is multipart you should cast it to multipart.
msg.getContentType();
Tricae
maybe this code will help:
you should call the dumpPart method like this
dumpPart( msg );
Store store;
Folder folder;
static boolean verbose = false;
static boolean debug = false;
static boolean showStructure = true;
private static void dumpPart(Part part) throws
Exception {
if (part instanceof Message)
dumpEnvelope((Message) part);
/** //Dump input stream ..
InputStream is = part.getInputStream();
// If "is" is not already buffered, wrap a
BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
is = new BufferedInputStream(is);
int c;
while ((c = is.read()) != -1)
System.err.write(c);
pr("CONTENT-TYPE: " + part.getContentType());
* Using isMimeType to determine the content type
avoids
* fetching the actual content data until we need it.
if (part.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
if (!showStructure)
System.out.println((String) part.getContent());
} else if (part.isMimeType("multipart/*")) {
pr("This is a Multipart");
pr("---------------------------");
Multipart mp = (Multipart) part.getContent();
level++;
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
level--;
} else if (part.isMimeType("message/rfc822")) {
pr("This is a Nested Message");
pr("---------------------------");
level++;
dumpPart((Part) part.getContent());
level--;
} else if (!showStructure) {
* If we actually want to see the data, and it?s not a
* MIME type we know, fetch it and check its Java type.
Object o = part.getContent();
if (o instanceof String) {
pr("This is a string");
pr("---------------------------");
System.out.println((String) o);
} else if (o instanceof InputStream) {
System.err.println("HELLO CAU 1111");
pr("This is just an input stream");
pr("---------------------------");
InputStream is2 = (InputStream) o;
int c2;
while ((c2= is2.read()) != -1)
System.out.write(c2);
System.err.println("\nHELLO CAU");
} else {
pr("This is an unknown type");
pr("---------------------------");
pr(o.toString());
} else {
pr("This is an unknown type");
pr("---------------------------");
private static void dumpEnvelope(Message msg) throws
Exception {
pr("This is the message envelope");
pr("---------------------------");
Address[] a;
// FROM
if ((a = msg.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
//TO
if ((a = msg.getRecipients(Message.RecipientType.TO))
!= null) {
for (int j = 0; j < a.length; j++)
pr("TO: " + a[j].toString());
// SUBJECT
pr("SUBJECT: " + msg.getSubject());
// DATE
Date d = msg.getSentDate();
pr("SendDate: " + (d != null ? d.toString() :
"UNKNOWN"));
//FLAGS
Flags flags = msg.getFlags();
StringBuffer sb = new StringBuffer();
Flags.Flag[] sf = flags.getSystemFlags(); // get the
system flags
boolean first = true;
for (int i = 0; i < sf.length; i++) {
String s;
Flags.Flag f = sf;
if (f == Flags.Flag.ANSWERED)
s = "\\Answered";
else if (f == Flags.Flag.DELETED)
s = "\\Deleted";
else if (f == Flags.Flag.DRAFT)
s = "\\Draft";
else if (f == Flags.Flag.FLAGGED)
s = "\\Flagged";
else if (f == Flags.Flag.RECENT)
s = "\\Recent";
else if (f == Flags.Flag.SEEN)
s = "\\Seen";
else
continue; // skip it
if (first)
first = false;
else
sb.append(' ');
sb.append(s);
String[] uf = flags.getUserFlags(); // get user-flag
strings
for (int i = 0; i < uf.length; i++) {
if (first)
first = false;
else
sb.append(' ');
sb.append(uf[i]);
pr("FLAGS: " + sb.toString());
// X-MAILER
String[] hdrs = msg.getHeader("X-Mailer");
if (hdrs != null)
pr("X-Mailer: " + hdrs[0]);
else
pr("X-Mailer NOT available");
static String indentStr = " ";
static int level = 0;
* Print a, possibly indented, string.
public static void pr(String s) {
if (showStructure)
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
Similar Messages
-
I'm getting the following exception:
23:53:05,542 ERROR [BouncedMailJob] Exception javax.mail.internet.MimeMultipart
java.lang.ClassCastException: javax.mail.internet.MimeMultipart
at com.imc.quartz.jobs.BouncedMailJob.dumpPart(BouncedMailJob.java:604)
at com.imc.quartz.jobs.BouncedMailJob.execute(BouncedMailJob.java:287)
at org.quartz.core.JobRunShell.run(JobRunShell.java:195)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:520)in the code chunk:
else if (p.isMimeType("multipart/*"))
logger.debug("This is a Multipart");
logger.debug("---------------------------");
Multipart mp = (Multipart) p.getContent(); // This is the line throwing the exception
level++;It's almost an exact carbon copy of msgshow.java in the demo, we just do some extra stuff with the results.
This code had been in production for a while, and I wanted to make a few minor updates, but now it's throwing the exception above on the line indicated. I've been looking at this all day and just cannot see what I might have introduced. Message is being passed in to dumpPart(), and the debug output does show I have a message.
What would cause this innocent looking line to throw that exception?
Any ideas?
Running on OSX 10.4.2, JBoss 4.0.3, using JAF 1.0.2 and JavaMail 1.3.3_01
Thanks.try this
//get the content of the incoming mail and store as temp object
Object tmpobj = mimemsg.getContent();
if (tmpobj instanceof MimeMultipart) {
//Extract the multipart mail to a variable mp
MimeMultipart mp = (MimeMultipart) mimemsg.getContent();
} -
When using File Upload functionality of Servlet3 specification, other item's value(<input type="text">) was garbage characters.
Need special settings?
WebLgic12c(12.1.2.0)のファイルアップロード機能(Servlet3仕様の機能)にて、アップロードファイル以外の項目の値が文字化けしました。
これは、何か設定が必要なのでしょうか?
【Note】
When normal request(application/x-www-form-urlencoded), submitted value is not garbage characters.
Filename & File content of uploaded file is not garbage characters.
I confirmed by debugger that stored value in temporary file is not garbage characters.
HttpServletRequest#setCharacterEncoding("UTF-8") is used.
enctype="multipart/form-data"を指定しないリクエストでは文字化けは発生していません。
アップロードしたファイルのファイル名及びアップロードファイルの中身自体は文字化けしていない。
アップロード時に出力される一時ファイルの中身をデバッグ実行して確認したところ、この段階では文字化けしていなかった。
HttpServletRequest#setCharacterEncoding("UTF-8")も実行しています。
【Environment Information】
OS : MacOS X 10.8.5
JVM : Oracle Java7
VM Encoding : UTF-8 (-Dfile.encoding=UTF-8)
WebPage Encoding : UTF-8
OS LANG : LANG=ja_JP.UTF-8
IDE : STS(Spring Tool Suite)
Boot Platform : WTP for Weblogic12.1.2.0
Framework : Spring MVC(3.2.4)
I want to know how to solve this behavior.
なにかご存知の方いましたら、解決方法をご教授頂ければと思います。
Message was edited by: user11123661 modified main language.(japanese -> english).The basic problem is not obscure, it has come up countless times since Tiger was released. See this note and try Fix C (dingbat) to see if it will help:
http://homepage.mac.com/thgewecke/woutlook.html -
Correct way to copy Multipart and prevent Missing start boundary Exception
Hi there
I've worked through the FAQ's and forum and based on the info available tried to construct code to deal with the whole "javax.mail.MessagingException: Missing start boundary" problem. I keep on getting a ClassCastException though and was hoping you could scan through the code and let me know if you see anything. I must be missing something ... simplified extract of code below:
Multipart mp = (Multipart)part.getContent();
try {
for (int i = 0; i < mp.getCount(); i++) {
processBodyPart(wrapper, mp.getBodyPart(i), i);
} catch (MessagingException e) {
// Converting Msg to a Copy (to fix boundary)
ByteArrayOutputStream bos = new ByteArrayOutputStream();
part.writeTo(bos);
byte[] bytes = bos.toByteArray();
MimeMessage newMsg = new MimeMessage(emailAccount.getSession(), new ByteArrayInputStream(bytes));
String ct = newMsg.getContentType();
newMsg.removeHeader("Content-Type");
ct = ct.substring(0, ct.indexOf(";")); // Strip out the rest, only retain the content-type
newMsg.setDataHandler(new DataHandler(newMsg.getContent(), ct));
Multipart testMp = (Multipart)newMsg.getContent(); // <<-------- ClassCastException here!!
for (int i = 0; i < testMp.getCount(); i++) {
Part bp = testMp.getBodyPart(i);
processBodyPart(bp);
}Much appreciated.
MariusI took out the truncating part to make the example shorter,
but I did try both keeping it as it was, as well as truncating
it (it is "multipart/mixed") with the same effect.
I was able to save the entire message to file (thanks), attached
below - maybe you can spot something that could be causing it?
Thanks again.
X-Original-To: [email protected]
Delivered-To: [email protected]
Received: from mail.adept.co.za (localhost [127.0.0.1])
by mail.adept.co.za (Postfix) with ESMTP id E3074C03D9
for <[email protected]>; Fri, 18 Jan 2008 14:35:29 +0200 (SAST)
X-Greylist: from auto-whitelisted by SQLgrey-1.7.4
Received: from mail-03.jhb.wbs.co.za (mail-03.jhb.wbs.co.za [196.2.97.2])
by mail.adept.co.za (Postfix) with ESMTP id CA3AEC03D7
for <[email protected]>; Fri, 18 Jan 2008 14:35:28 +0200 (SAST)
Received: from localhost by mail-03.jhb.wbs.co.za;
18 Jan 2008 14:35:28 +0200
Date: 18 Jan 2008 14:35:28 +0200
To: [email protected]
From: "Mail Delivery System" <[email protected]>
Subject: Delivery Status Notification (Failure)
MIME-Version: 1.0
Content-Type: multipart/report; report-type=delivery-status; boundary="9sdJO.4G/vWebcc.bcm9J.Ak/cwPA"
Message-Id: <[email protected]>
X-Virus-Scanned: ClamAV Passed
X-Spam-Scanned: -1.4
X-Scanned-By: proxfilter
--9sdJO.4G/vWebcc.bcm9J.Ak/cwPA
content-type: text/plain;
charset="utf-8"
Content-Transfer-Encoding: quoted-printable
The following message to <[email protected]> was undeliverable.
The reason for the problem:
5.1.2 - Bad destination host 'DNS Hard Error looking up onyxit.co.za (MX): =
NXDomain'
--9sdJO.4G/vWebcc.bcm9J.Ak/cwPA
content-type: message/delivery-status
Reporting-MTA: dns; jnb-mailfw01.wbs.co.za
Final-Recipient: rfc822;[email protected]
Action: failed
Status: 5.0.0 (permanent failure)
Diagnostic-Code: smtp; 5.1.2 - Bad destination host 'DNS Hard Error looking up onyxit.co.za (MX): NXDomain' (delivery attempts: 0)
--9sdJO.4G/vWebcc.bcm9J.Ak/cwPA
content-type: message/rfc822
Received: from wbs-smtp-out-02.jhb.wbs.co.za (HELO wbs-smtp-out-02) ([196.2.97.197])
by mail-03.jhb.wbs.co.za with ESMTP; 18 Jan 2008 14:35:28 +0200
Received: from wbs-smtp-out-02.jhb.wbs.co.za (HELO wbs-smtp-out-02) ([196.2.97.197])
by mail-03.jhb.wbs.co.za with ESMTP; 18 Jan 2008 14:35:28 +0200
Received: from wbs-41-208-227-16.wbs.co.za ([41.208.227.16] helo=jnfsworkpool)
by wbs-smtp-out-02 with esmtp (Exim 4.67)
(envelope-from <[email protected]>)
id 1JFqSK-0000qy-8m; Fri, 18 Jan 2008 14:36:30 +0200
Date: Fri, 18 Jan 2008 14:35:10 +0200 (SAST)
From: Ros Copeling <[email protected]>
To: [email protected]
Cc: [email protected]
Message-ID: <[email protected]>
Subject: FW: Fw: Message from ESKOM
MIME-Version: 1.0
Content-Type: multipart/mixed;
boundary="----=_Part_16_32195616.1200659710788"
X-Priority: 3
Importance: normal
Sensitivity: Normal
workpool_message_id: 6879
X-Original-Subject: FW: Fw: Message from ESKOM
X-Spam-Ignored: [TOO LARGE] Message > 100K
X-Scan-Signature: 66244f1a8ccb48c519852bcb33c1a261
--9sdJO.4G/vWebcc.bcm9J.Ak/cwPA-- -
Unable to read email content of type multipart/mixed....
Hi i have written following code to read text content form the multipart email content type,
but when i say
if (content instanceof Multipart){
System.out.println("############ Content Type is Multipart ############ ");
messagePart = ((Multipart) content).getBodyPart(0);
}the flow is not going into the if condition,
bellow is the detailed code and the output in the console, you can check with the SOPs
Part messagePart = message;
content = messagePart.getContent();
System.out.println("############ : " + content);
System.out.println("############ START MESSAGE BODY ############");
System.out.println(content);
System.out.println("############ END MESSAGE BODY ############");
if (content instanceof Multipart){
System.out.println("############ Content Type is Multipart ############ ");
messagePart = ((Multipart) content).getBodyPart(0);
String contentType = messagePart.getContentType();
System.out.println("############ CONTENT TYPE : " + contentType);
System.out.println("############ CONTENT TYPE : " + contentType);
if (contentType.startsWith("text/plain")) {
System.out.println("############ Content Type is text/plain ############");
InputStream is = messagePart.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String thisLine = reader.readLine();
while (thisLine != null) {
actualMsg = actualMsg + thisLine + ".";
thisLine = reader.readLine();
System.out.println("############ SMS CONTENT :" + actualMsg);
System.out.println("/**********************Passing to E2SConverter********************/");
And the output for the same
Stack Trace*** Check for new mails on Mail Server for Processing ***
########## Unread Msg Count : 1
########## FROM : [email protected]
########## SUBJECT : RE: SMS-5000-9969413222-S1221654991804 [T20080917000CS010Z246]
**************** Checking Subject Line ****************
******* GO AHEAD IS TRUE : EMAIL TO SMS CONVERTER *******
############ : javax.mail.internet.MimeMultipart@1a2760f
############ START MESSAGE BODY ############
javax.mail.internet.MimeMultipart@1a2760f
############ END MESSAGE BODY ############
############ CONTENT TYPE : multipart/mixed; boundary=22902610.1221655198503.JavaMail.javamailuser.localhost
############ SMS CONTENT :
/**********************Passing to E2SConverter********************/
Please help me for the same.. its bit urgent...
Thanks And Regards,
Amie...Yes,
It's going into the if if block, but its giving me ClassCastException
System.out.println("******* GO AHEAD IS TRUE : EMAIL TO SMS CONVERTER ******* ");
Part messagePart = message;
content = messagePart.getContent();
System.out.println("############ : " + content);
System.out.println("############ START MESSAGE BODY ############");
System.out.println(content);
System.out.println("############ END MESSAGE BODY ############");
if (messagePart.isMimeType("multipart/*")) {
System.out.println("############ Content Type is Multipart ############ ");
messagePart = ((Multipart) content).getBodyPart(0); //GIVES EXCEPTION : ClassCastException at this line...
String contentType = messagePart.getContentType();
System.out.println("############ CONTENT TYPE : " + contentType);
See the Stack Trace..TAconnVect.size()25
*** Check for new mails on Mail Server for Processing ***
########## Unread Msg Count : 2
########## FROM : [email protected]
########## SUBJECT : SMS-5000-9969413222-S1221713640885 [T200809180003S070]
########## FROM : [email protected]
########## SUBJECT : SMS-5000-9969413222-S1221713740897 [T200809180004S070]
**************** Checking Subject Line ****************
******* GO AHEAD IS TRUE : EMAIL TO SMS CONVERTER *******
############ : javax.mail.internet.MimeMultipart@1f7be7b
############ START MESSAGE BODY ############
javax.mail.internet.MimeMultipart@1f7be7b
############ END MESSAGE BODY ############
############ Content Type is Multipart ############
java.lang.ClassCastException: javax.mail.internet.MimeMultipart
at com.interactcrm.SMSConverterClass.PollEmail.CheckEmails(PollEmail.java:327)
at com.interactcrm.SMSConverterClass.PollEmail.run(PollEmail.java:98)
at java.util.TimerThread.mainLoop(Unknown Source)
at java.util.TimerThread.run(Unknown Source)
- INFO : readMessage Checking for new messages in inbound table of ta database
TAconnVect.size()25
TAconnVect.size()25
and Bellow is the internet header of the mail which i am trying to read.Received: from grameenphone.com ([10.10.29.153]) by neptune.grameenphone.com with Microsoft SMTPSVC(6.0.3790.3959);
Thu, 18 Sep 2008 10:55:52 +0600
Date: Thu, 18 Sep 2008 04:55:52 GMT
From: [email protected]
Subject: =?us-ascii?B?U01TLTUwMDAtOTk2OTQxMzIyMi1TMTIyMTcxMzc0MDg5NyBbVDIwMDgwOTE4MDAwNFMwNzBd?=
To: [email protected]
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="20238918.1221131600666.JavaMail.SYSTEM.ipcc-test3"
Return-Path: [email protected]
Message-ID: <[email protected]>
X-OriginalArrivalTime: 18 Sep 2008 04:55:52.0114 (UTC) FILETIME=[D35D2120:01C9194A]
Edited by: Amie on Sep 18, 2008 10:29 AM
Edited by: Amie on Sep 18, 2008 10:36 AM -
Junk characters display while using multipart with html content in Javamail
Hi All,
I have used Java mail API to send mail with attachment. To enable to attachment in mail and to do content formatting i have used multipart and html content type together.
My web application runs on apache tomcat 5.5 in MAC server. Java version is 1.5.
The Function which i have used for sending mail with attachment is as follows:
public void sendmailAttached(String to,String from,String host,boolean debug,String mailContent,String mailSubject,String cc,String attachFiles)
String mailarray[]=to.split(";");
Properties props = new Properties();
//props.put("mail.smtp.port","425");
props.setProperty("mail.smtp.host", host);
if (debug) props.setProperty("mail.debug", ""+debug);
Session session = Session.getInstance(props, null);
session.setDebug(debug);
try {
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
javax.mail.internet.InternetAddress[] toAddress=new javax.mail.internet.InternetAddress[mailarray.length];
for (int i=0;i<mailarray.length ;i++ )
toAddress=new javax.mail.internet.InternetAddress(mailarray[i]);
msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(mailSubject);
try{
String ccaray =cc;
String mailarray1[]=ccaray.split(";");
javax.mail.internet.InternetAddress[] CCAddress=new javax.mail.internet.InternetAddress[mailarray1.length];
for (int i=0;i<mailarray1.length ;i++ )
CCAddress[i]=new javax.mail.internet.InternetAddress(mailarray1[i]);
msg.setRecipients(Message.RecipientType.CC,CCAddress);
}catch(Exception ss)
System.out.println("CC mail exception is ====>"+ ss.getMessage());
msg.setSentDate(new java.util.Date());
Multipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailContent, "text/html");
multipart.addBodyPart(messageBodyPart);
String fileName = attachFiles.substring(attachFiles.lastIndexOf("/")+1,attachFiles.length());
if(!fileName.equals(""))
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachFiles);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send( msg );
catch(MessagingException mex)
Exception ex = mex;
if (ex instanceof SendFailedException)
SendFailedException sfex = (SendFailedException)ex;
Address[] invalid = sfex.getInvalidAddresses();
if (invalid != null) {
if (invalid != null) {
for (int i = 0; i < invalid.length; i++)
System.out.println("Invalid Addresss --------> " + invalid[i]);
try
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(from));
Multipart multipart = new MimeMultipart("related");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailContent, "text/html");
multipart.addBodyPart(messageBodyPart);
Address[] validUnsent = sfex.getValidUnsentAddresses();
javax.mail.internet.InternetAddress[] toAddress=new javax.mail.internet.InternetAddress[validUnsent.length];
if (validUnsent != null) {
for (int i = 0; i < validUnsent.length; i++)
System.out.println("Valid Address ------>"+validUnsent[i]);
String test = validUnsent[i]+"";
toAddress[i]=new javax.mail.internet.InternetAddress(test);
msg.setRecipients(Message.RecipientType.TO, toAddress);
msg.setSubject(mailSubject);
String fileName = attachFiles.substring(attachFiles.lastIndexOf("/")+1,attachFiles.length());
if(!fileName.equals(""))
messageBodyPart = new MimeBodyPart();
DataSource source = new FileDataSource(attachFiles);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(fileName);
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Transport.send( msg );
catch(Exception e)
System.out.println("Mail Not Send");
else
System.out.println("Mail Server Not Connectd ");
This code is working properly and i am able to send mail with attachment and html formatted content without any problem. But console of server is filled up with too much junk characters because of which the catalina.out file of tomcat server is becoming fully filled.
Sample cosnole display with junk characters are as follows:
Subject: HBSP - DRUCKER - QC - CH16 - QC R2 Completed
MIME-Version: 1.0
Content-Type: multipart/related;
boundary="----=_Part_34_15681668.1247471518887"
------=_Part_34_15681668.1247471518887
Content-Type: text/html; charset=us-ascii
Content-Transfer-Encoding: 7bit
<b>Hi,</b><br><br> Chapter CH16 in the project DRUCKER is Completed . <br><br> <b>Comments :</b> Qc Accepted.<br><br> <b><i>Thanks,<br>ANTONY.</i></b>
------=_Part_34_15681668.1247471518887
Content-Type: application/octet-stream; name=9420317_CH06_p084-119.pdf.zip
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=9420317_CH06_p084-119.pdf.zip
UEsDBBQAAAAIAMOz6TqHaQ4BUtXhAGzP8QAZAAAAOTQyMDMxN19DSDA2X3AwODQtMTE5LnBkZsQ7
CTxUX9tCUpIWEomxpoWZuTN3FmvW7P9skaUajCXGiCHSYiuKFrIvlWStROSvaBEtiIpkK5WlUipa
ZKl898wYRP/37fve7/e69TjnPuc5z3LOuc95zjP3ym7S1lXAKuL5ZTu7HjTyL8ATiCgMiu6wA6Wi
gjZy86RSvN12U51QWLQRCguT8ESISED/hcITMWgdFJZIgPAwBm2CwhHQFqAdRySRcWg9lC2KBBNQ
WAIRZ6+mxk/1dEI48qNYF7+/N9WZHwiCSPyY8QtLQDFLlCf/AhYGgiHyDBwBIs7EETEzcCR4Bg6H
IZBn4LBE7AwcNBOHJ87EwWQ8aTqOgIWJM3C4mX2JMH6GLiQiHjMDR8bD03BYDBYizcDh8LjpOCyM
xczAETH4mbgZOmNhmDCDHwE7Qz+IhMNO54eHCKTp/GAcboYuBBJMmi6DSIZxU+lYF7KSJnEMb4qb
B9WbH1md5sjCROHJMHqTN9VvfPGRcGgzOp2BwhOQMUKZofU9nenIDYF1o22rgtXU1EWGRgsia2vp
Like this display of junk characters are filling up multiple pages of console file.
Can any one suggest me how to overcome this problem?
Many thanks in advance.There is no "sendmail" method in the JavaMail API.
The debug flag is set using the Session.setDebug method, or by setting the Session property "mail.debug".
If you're using someone else's helper classes with JavaMail, they may provide another way to set it. -
Cast SharedByteArrayInputStream to Multipart
I get this exception java.lang.ClassCastException: javax.mail.util.SharedByteArrayInputStream cannot be cast to javax.mail.Multipart, the error appears when i try this, I already do the conexion to the server POP3. Could anyone help me??
Thanks! Here is the code...
Message [] mensajes = folder.getMessages();
for (int i=0;i<mensajes.length;i++)
System.out.println("---------->From:"+mensajes.getFrom()[0].toString());
System.out.println("Subject:"+mensajes[i].getSubject());
System.out.println("Subject:"+mensajes[i].getSentDate());
// Si es compuesto, su MIME type es multipart
if (mensajes[i].isMimeType("multipart/*"))
// Obtenemos el contenido, que es de tipo MultiPart.
Multipart multi = null;
try{
//Object la = (Object)mensajes[i].getContent();
//Vector la = (Vector)mensajes[i].getContent();
//multi = (Multipart)la;
multi = (Multipart)mensajes[i].getContent();
}catch(ClassCastException cce){
System.out.println("nel" + cce);So then don't cast it to Multipart. Use the instanceof operator to see if it's a Multipart before you try to cast it.
-
Hi, I test the follow Jguru tutorial code for getting atacchements
Multipart multipart = (Multipart)message.getContent();
for (int i=0, n=multipart.getCount(); i<n; i++) {
Part part = multipart.getBodyPart(i));
String disposition = part.getDisposition();
if ((disposition != null) &&
((disposition.equals(Part.ATTACHMENT) ||
(disposition.equals(Part.INLINE))) {
saveFile(part.getFileName(), part.getInputStream());
But i have a problem of cast in this line
Multipart mp = (Multipart)message.getContent();
the error of CastClass is:
java.lang.String cannot be cast to javax.mail.Multipart
why????? Please help me
ThanksMost likely you don't have a multipart message. See the msgshow.java
demo program that comes with JavaMail. -
How to Read a Message with Content Type multipart/alternative
Hi ,
I need to write a POP3 Client to read email message ..but some times the messages comes with content type multipart/alternative
how to parse it and read only one of the content :
for example :
This is a multi-part message in MIME format.
------=_NextPart_000_12C25_01C6B64F.09226B00
Content-Type: text/plain;
charset="iso-8859-1"
Content-Transfer-Encoding: 7bit
Assignment to workgroup Name 1 : L2 SD Service Delivery Apps Spt
Open CI Search Code : HPSD
Description : tesat
General Information :
Is the workgroup owner Aware of the addition to Workgroup : Yes
Workgroup to be added :
L2 SD Service Delivery Apps Spt
------=_NextPart_000_12C25_01C6B64F.09226B00
Content-Type: text/html;
charset="iso-8859-1"
Content-Transfer-Encoding: quoted-printable
<br><P>Assignment to workgroup Name 1 : L2 SD Service Delivery Apps =
Spt</P>
<P>Open CI Search Code : HPSD</P>
<P>Description : tesat</P>
<P>General Information :</P>
<P>Is the workgroup owner Aware of the addition to Workgroup : Yes</P>
<P>Workgroup to be added :</P>
<P>L2 SD Service Delivery Apps Spt</P>
<P> </P>
<P> </P>
<P> </P>
<P> </P>
<P> </P>
------=_NextPart_000_12C25_01C6B64F.09226B00--
The Same message is in text as well as HTML so not sure how to read it .
currently my program is as follows
for (int i = 0; i < found.length; i++) {
Message m = found;
// Get some headers
Date date = m.getSentDate();
Address [] from = m.getFrom();
String subj = m.getSubject();
String mimeType = m.getContentType();
System.out.println(date + "\t" + from[0] + "\t" +
subj + "\t" + mimeType);
Object o = m.getContent();
if (o instanceof String) {
System.out.println("**This is a String Message**");
System.out.println((String)o);
} else if (o instanceof Multipart) {
System.out.print("**This is a Multipart Message. ");
Multipart mp = (Multipart)o;
int count3 = mp.getCount();
System.out.println("It has " + count3 +
" BodyParts in it**");
for (int j = 0; j < count3; j++) {
// Part are numbered starting at 0
BodyPart b = mp.getBodyPart(j);
String mimeType2 = b.getContentType();
System.out.println( "BodyPart " + (j + 1) +
" is of MimeType " + mimeType);
Object o2 = b.getContent();
if (o2 instanceof String) {
System.out.println("**This is a String BodyPart**");
System.out.println((String)o2);
} else if (o2 instanceof Multipart) {
System.out.print(
"**This BodyPart is a nested Multipart. ");
Multipart mp2 = (Multipart)o2;
int count2 = mp2.getCount();
System.out.println("It has " + count2 +
"further BodyParts in it**");
} else if (o2 instanceof InputStream) {
System.out.println(
"**This is an InputStream BodyPart**");
} //End of for
} else if (o instanceof InputStream) {
System.out.println("***********************************This is an InputStream message**");
InputStream is = (InputStream)o;
/* if(m.getContentType().equalsIgnoreCase("multipart/alternative")) {
MimeMultipart mp = new MimeMultipart();
// Assumes character content (not binary images)
} else {*/
BufferedReader reader
=new BufferedReader(new InputStreamReader(is));
String thisLine=reader.readLine();
while (thisLine!=null) {
System.out.println(thisLine);
thisLine=reader.readLine();
So when the Content TYpe is multipart/alternative it goes into InputStream message .
any help and ideas to handel such situations ?
Thanks
San
Message was edited by:
sanrosh_95Try reposting that with tags (replace the {'s with ['s).
Long story short, I think the FAQ and examples would go a long way towards explaining this, but you basically can check the content type, or check if the content contains parts, and parse each part separately. -
Receive multipart message for IMAP protocol
I need receive content of multipart (not plain text) message with IMAP protocol.
this code correct for POP3 and IMAP paintext message only:
Part messagePart=message;
Object content=messagePart.getContent();
if (content instanceof Multipart) {
messagePart=((Multipart)content).getBodyPart(0);
System.out.println("[ Multipart Message ]");
String contentType=messagePart.getContentType();
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);
thisLine=reader.readLine();
any ideas?
Thanks.You will find a better example, which looks at the parts recursively, if you look in the "demo" directory of your JavaMail download. I think it's msgshow.java but there aren't that many to choose from.
-
Error in opening draft email saved with msg extension
I am attempting to create a email and save it on local hard disc. The email is a file having msg extension. So that it can be opened with MS Outlook. Also I want it to be in DRAFT mode. Like we can create draft email with MS Outlook. This message will have multiple attachmets.
Thus when user opens this file, it will get opened with MS Outlook and user will be able to edit the message text, TO/CC list, attachments.
I am using MimeMessage.writeTo(Outstream) API to save the message to a file, say C:\test.msg
But if I double click test.msg in explorer to open it, it gives error:
Can't open file C:\test.msg. The file may not exist, you may not have permissions to open it, or it may be open in another program.
Is it possible to create draft Outlook email message with msg extension?
If yes, how?
My code:
Properties props = new Properties();
props.load(new FileInputStream("C:/email.settings.properties"));
// create some properties and get the default Session
Session session = Session.getDefaultInstance(props);
session.setDebug(debug);
// create a message
msg = new MimeMessage(session);
//Create message from saved email
File savedFile = new File("C:/test.msg");
// set the from and to address
InternetAddress addressFrom = new InternetAddress(from);
msg.setFrom(addressFrom);
InternetAddress[] addressTo = null;
addressTo = new InternetAddress[recipients.length];
for (int i = 0; i < recipients.length; i++) {
addressTo[i] = new InternetAddress(recipients);
msg.setRecipients(Message.RecipientType.TO, addressTo);
// Setting the Subject and Content Type
msg.setSubject(subject);
msg.setContent(message, "text/plain");
MimeBodyPart attachmentBodyPart = new MimeBodyPart();
DataSource ds = new FileDataSource("C:/WhichSQLServer.pdf");
attachmentBodyPart.setDataHandler(new DataHandler(ds));
attachmentBodyPart.setFileName("WhichSQLServer.pdf");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(attachmentBodyPart);
msg.setContent(multipart);
//msg.setFlag(Flags.Flag.DRAFT, true);
msg.getFlags().add(Flags.Flag.DRAFT);
msg.setFileName("test.msg");
msg.saveChanges();
FileOutputStream os = new FileOutputStream("C:/test.msg");
msg.writeTo(os);
os.flush();
os.close();Outlook Msg files aren't as easy to write as you would believe. They are a propretary format that microsoft uses based on the DocFile format that Word and Excel uses.
If you did the MimeMessage.writeTo(out) and saved it to a .eml file Outlook Express will open it, but Outlook doesn't directly read this file type.
I've started on a library to allow the creation of Outlook msg files, right now it only allows you to set text, dates, long, and boolean values on the email message (which means you can set stuff like the recieved date/time, subject, body, to, from, etc), but it does not yet support attachments or extra recipents (CC, BCC, etc). I'll be updating the copy on my site as soon as I get the other stuff working (which isn't as easy as it sounds).
Priasoft has a library available that can do what you want however.
travis (at) overwrittenstack.com -
Save Attachment from exchange server 2010 from oracle using java mail API
Hello,
I want to read email from microsoft exchangeserver 2010 and save attachement into a folder.I created an Java program to import attachments from a exchange server mailbox using "POP3S".It works fine when run as a java application.But when i put this inside Oracle11g R2 using load java and while executing from a procedure it gives an error at parsing message into Multipart
Error at line : Multipart mp = (Multipart)m.getContent();
Error:
Content-Type: multipart/mixed;
boundary="_002_A0C2E09A..................................."
java.lang.ClassCastException
at mailPop3.checkmail(mailPop3:71)
My Java Class is as follows,
import java.io.*;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Date;
The function i used to check for attachments is given below.
public static boolean hasAttachments(Message m) throws java.io.IOException, MessagingException
Boolean hasAttachments = false;
try
// if it is a plain/html text - no attachements
if (m.isMimeType("text/*"))
return hasAttachments;
else if (m.isMimeType("multipart/alternative"))
return hasAttachments;
else if (m.isMimeType("multipart/*"))
Multipart mp = (Multipart)m.getContent();
if (mp.getCount() > 1)
hasAttachments = true;
return hasAttachments;
catch (Exception e) {
e.printStackTrace();
} finally {
return hasAttachments;
My Java Details as follows
java Version :1.5.0_10
java.vm.specification.version:1.0
java.vm.version :1.5.0_01
java.specification.version:1.5
java.class.version:48.0
Java mail API:javamail-1.4.4
Used Jars:mail.jar
Could someone explain why I am getting this error? What can I do to resolve this error?
Is any other Jar need other than mail.jar?
Any help would be much appreciated.
Regards,
NisanthHai EJP,
Thanks for your reply,
My full java class as follows,
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Part;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage;
public class Newmail
public Newmail()
super();
public static int mailPOP3(String phost,
String pusername,
String ppassword)
Folder inbox =null;
Store store =null;
int result = 1;
try
String host=phost;
final String username=pusername;
final String password=ppassword;
System.out.println("Authenticator");
Authenticator auth=new Authenticator()
protected PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(username, password);
System.out.println("Certificate");
String filename="D:\\Certi\\jssecacerts";
String password2 = "changeit";
System.setProperty("javax.net.ssl.trustStore",filename);
System.setProperty("javax.net.ssl.trustStorePassword",password2);
Properties props = System.getProperties();
System.out.println("host-----"+props);
props.setProperty("mail.pop3s.port", "993");
props.setProperty("mail.pop3s.starttls.enable","true");
props.setProperty("mail.pop3s.ssl.trust", "*");
Session session = Session.getInstance(props,auth);
session.setDebug(true);
store = session.getStore("pop3s");
System.out.println("store------"+store);
store.connect(host,username,password);
System.out.println("Connected...");
inbox = store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
System.out.println("msgs.length-----"+msgs.length);
result = 0;
int no_of_messages = msgs.length;
for ( int i=0; i < no_of_messages; i++)
System.out.println("msgs.count-----"+i);
System.out.println("Attachment....>"+msgs.getContentType());
Multipart mp = (Multipart)msgs[i].getContent();
System.out.println("Casting Success" + mp.getContentType());
catch(Exception e)
e.printStackTrace();
finally
try
if(inbox!=null)
inbox.close(false);
if(store!=null)
store.close();
return result;
catch(Exception e)
e.printStackTrace();
return result;
Please check it
Regards,
Nisanth -
Hi,
I created an Java program to import attachments from a exchange server mailbox using POP3S .It works fine when run as a java application.
But when i put this inside Oracle11g using load java and while executing it gives an error at
Multipart mp = (Multipart) message.getContent();
Error:
Content-Type: multipart/mixed;
boundary="_002_A0C2E09A..................................."
java.lang.ClassCastException
at Newmail.mailPOP3(Newmail:71)
Could someone explain why I am getting this error? What can I do to resolve this error?Any help would be much appreciated.
Regards,
JosephHai Matt,
The actual class i am tested as follows,
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Part;
import javax.mail.Multipart;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeMessage;
public class Newmail
public Newmail()
super();
public static int mailPOP3(String phost,
String pusername,
String ppassword)
Folder inbox =null;
Store store =null;
int result = 1;
try
String host=phost;
final String username=pusername;
final String password=ppassword;
System.out.println("Authenticator");
Authenticator auth=new Authenticator()
protected PasswordAuthentication getPasswordAuthentication()
return new PasswordAuthentication(username, password);
System.out.println("Certificate");
String filename="D:\\Certi\\jssecacerts";
String password2 = "changeit";
System.setProperty("javax.net.ssl.trustStore",filename);
System.setProperty("javax.net.ssl.trustStorePassword",password2);
Properties props = System.getProperties();
System.out.println("host-----"+props);
props.setProperty("mail.imaps.port", "993");
props.setProperty("mail.imaps.starttls.enable","true");
props.setProperty("mail.imaps.ssl.trust", "*");
Session session = Session.getInstance(props,auth);
session.setDebug(true);
store = session.getStore("imaps");
System.out.println("store------"+store);
store.connect(host,username,password);
System.out.println("Connected...");
inbox = store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msgs = inbox.getMessages();
System.out.println("msgs.length-----"+msgs.length);
result = 0;
int no_of_messages = msgs.length;
for ( int i=0; i < no_of_messages; i++)
System.out.println("msgs.count-----"+i);
System.out.println("Attachment....>"+msgs.getContentType());
// Casting message to multipart
*Multipart mp = (Multipart)msgs[i].getContent();* System.out.println("Casting Success" + mp.getContentType());
catch(Exception e)
e.printStackTrace();
finally
try
if(inbox!=null)
inbox.close(false);
if(store!=null)
store.close();
return result;
catch(Exception e)
e.printStackTrace();
return result;
In this class when running from oracle using a procedure "Multipart mp = (Multipart)msgs[i].getContent();" throws exception..
Error:
Content-Type: multipart/mixed;
boundary="_002_A0C2E09A..................................."
java.lang.ClassCastException
at Newmail.mailPOP3(Newmail:71)
Thanks & Regards
Joseph -
How do I read a Email from the MS exchange server
could any one tell me as to how i could read the mail from the exchange server and store it in a seperate folder.
I have an application which reads the mail from our mail server and then writes the body of the message into a file and then deletes the email anf those values are then read from that file and stored into the database .
Here is the code which pops the mail from the exchange server and then stores it into a file .
import javax.mail.*;
import com.sun.mail.pop3.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
* Title:
* Description:
* Copyright: Copyright (c) 2001
* Company:
* @author
* @version 1.0
public class SunMailConnection implements Runnable{
boolean suspendFlag;
ErrorLogWriter log = new ErrorLogWriter("SunMail.log");
public SunMailConnection() {
this.start() ;
public void run(){
try {
int start = 1;int end = -1;
String host = "cyde-cehh-exh1";//the local exchange server name AND DOESNT WORK IF U CONNECT TO EXT MAIL SERVER DIRECTLY
//DUE TO SECURED AUTHORISATION
//String host ="http://www.conergy-electronics.de";
String username ="SunReader\\Sun\\saa";
String password = "xxxxx";
// Create empty properties
Properties props = new Properties();
props.put("mail.protocol.store","pop3");
// Get session
Session session = Session.getDefaultInstance(props, null);
Provider[] p = session.getProviders();
//for (int i=0;i<p.length;i++) System.out.println(p.getProtocol());
// Get the store
Store store = session.getStore("pop3");
store.connect(host, username, password);
// Get folder
Folder folder = store.getFolder("INBOX");
if (folder == null || !folder.exists()) {
//System.out.println("Invalid folder: " + folder.getName());
log.write("Invalid folder: " + folder.getName()) ;
System.exit(1);
folder.open(Folder.READ_WRITE);
//Get the number of Unread Messages
int count = folder.getUnreadMessageCount();
if (count == 0) { // No messages in the source folder
//System.out.println(folder.getName() + " is empty");
// Close folder, store and return
folder.close(false);
store.close();
return;
if (end == -1)
end = count;
// Get the message objects to copy
log.write("Test");
Message[] msgs = folder.getMessages(start, end);
//System.out.println("Moving " + msgs.length + " messages");
//log.write("Moving " + msgs.length + " messages") ;
if (msgs.length != 0) {
//If there is any mail
//System.out.println(msgs.length );
//read mail from server into files
MoveMessageTo saveFile = new MoveMessageTo(msgs);
if(saveFile.createdFile=true){
folder.setFlags(msgs,new Flags(Flags.Flag.SEEN),true);
//delete flag set here to remove the email from INBOX
folder.setFlags(msgs, new Flags(Flags.Flag.DELETED), true);
//folder.expunge(); //removes messages marked as deleted
//check for deleting messages
for (int i = 0; i < msgs.length; i++) {
if (!msgs[i].isSet(Flags.Flag.DELETED))
log.write("Message # "+msgs[i]+" not deleted.");
//else System.out.println("Message "+i+"-is deleted") ;
// Close connection
folder.close(true);
// dfolder.close(false);
store.close();
//this.start() ;
}catch (Exception ex) {
ex.printStackTrace() ;
//this.t.start();
public void start(){
try {
while(this!= null){
this.run() ;
Thread.sleep(15000);//every 15 seconds
}catch (Exception ex) {
ex.printStackTrace();
public void exit(){
this.exit();
System.out.println("Exit");
public static void main(String[] args) {
SunMailConnection sunMail = new SunMailConnection();
This is to show the messages
import java.util.*;
import java.io.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class msgshow {
static String protocol;
static String host = null;
static String user = null;
static String password = null;
static String mbox = "INBOX";
static String url = null;
static int port = -1;
static boolean verbose = false;
static boolean debug = false;
static boolean showStructure = false;
static boolean showMessage = false;
public static void main(String argv[]) {
int msgnum = -1;
int optind;
protocol = "pop3";
host="cyde-cehh-exh1";
user="SunReader\\Sun\\saa";
password="xxxxxx";
mbox="INBOX";
/*for (optind = 0; optind < argv.length; optind++) {
if (argv[optind].equals("-T")) {
protocol = argv[++optind];
} else if (argv[optind].equals("-H")) {
host = argv[++optind];
} else if (argv[optind].equals("-U")) {
user = argv[++optind];
} else if (argv[optind].equals("-P")) {
password = argv[++optind];
} else if (argv[optind].equals("-v")) {
verbose = true;
} else if (argv[optind].equals("-D")) {
debug = true;
} else if (argv[optind].equals("-f")) {
mbox = argv[++optind];
} else if (argv[optind].equals("-L")) {
url = argv[++optind];
} else if (argv[optind].equals("-p")) {
port = Integer.parseInt(argv[++optind]);
} else if (argv[optind].equals("-s")) {
showStructure = true;
} else if (argv[optind].equals("-m")) {
showMessage = true;
} else if (argv[optind].equals("--")) {
optind++;
break;
} else if (argv[optind].startsWith("-")) {
System.out.println(
"Usage: msgshow [-L url] [-T protocol] [-H host] [-p port] [-U user]");
System.out.println(
"\t[-P password] [-f mailbox] [msgnum] [-v] [-D] [-s]");
System.out.println(
"or msgshow -m [-v] [-D] [-s] < msg");
System.exit(1);
} else {
break;
try {
// if (optind < argv.length)
// msgnum = Integer.parseInt(argv[optind]);
//msgnum = 5;
// Get a Properties object
Properties props = System.getProperties();
// Get a Session object
Session session = Session.getDefaultInstance(props, null);
session.setDebug(debug);
if (showMessage) {
MimeMessage msg = new MimeMessage(session, System.in);
dumpPart(msg);
System.exit(0);
// Get a Store object
Store store = null;
if (url != null) {
URLName urln = new URLName(url);
store = session.getStore(urln);
store.connect();
} else {
if (protocol != null)
store = session.getStore(protocol);
else
store = session.getStore();
// Connect
if (host != null || user != null || password != null)
store.connect(host, port, user, password);
else
store.connect();
// Open the Folder
Folder folder = store.getDefaultFolder();
if (folder == null) {
System.out.println("No default folder");
System.exit(1);
folder = folder.getFolder(mbox);
if (folder == null) {
System.out.println("Invalid folder");
System.exit(1);
// try to open read/write and if that fails try read-only
try {
folder.open(Folder.READ_WRITE);
} catch (MessagingException ex) {
folder.open(Folder.READ_ONLY);
int totalMessages = folder.getMessageCount();
if (totalMessages == 0) {
System.out.println("Empty folder");
folder.close(false);
store.close();
System.exit(1);
if (verbose) {
int newMessages = folder.getNewMessageCount();
System.out.println("Total messages = " + totalMessages);
System.out.println("New messages = " + newMessages);
System.out.println("-------------------------------");
if (msgnum == -1) {
// Attributes & Flags for all messages ..
Message[] msgs = folder.getMessages();
// Use a suitable FetchProfile
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add("X-Mailer");
folder.fetch(msgs, fp);
for (int i = 0; i < msgs.length; i++) {
System.out.println("--------------------------");
System.out.println("MESSAGE #" + (i + 1) + ":");
dumpEnvelope(msgs[i]);
// dumpPart(msgs[i]);
} else {
System.out.println("Getting message number: " + msgnum);
Message m = null;
try {
m = folder.getMessage(msgnum);
dumpPart(m);
} catch (IndexOutOfBoundsException iex) {
System.out.println("Message number out of range");
folder.close(false);
store.close();
} catch (Exception ex) {
System.out.println("Oops, got exception! " + ex.getMessage());
ex.printStackTrace();
System.exit(1);
System.exit(0);
public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message)p);
/** Dump input stream ..
InputStream is = p.getInputStream();
// If "is" is not already buffered, wrap a BufferedInputStream
// around it.
if (!(is instanceof BufferedInputStream))
is = new BufferedInputStream(is);
int c;
while ((c = is.read()) != -1)
System.out.write(c);
pr("CONTENT-TYPE: " + p.getContentType());
String filename = p.getFileName();
if (filename != null)
pr("FILENAME: " + filename);
* Using isMimeType to determine the content type avoids
* fetching the actual content data until we need it.
if (p.isMimeType("text/plain")) {
pr("This is plain text");
pr("---------------------------");
if (!showStructure)
System.out.println((String)p.getContent());
} else if (p.isMimeType("multipart/*")) {
pr("This is a Multipart");
pr("---------------------------");
Multipart mp = (Multipart)p.getContent();
level++;
int count = mp.getCount();
for (int i = 0; i < count; i++)
dumpPart(mp.getBodyPart(i));
level--;
} else if (p.isMimeType("message/rfc822")) {
pr("This is a Nested Message");
pr("---------------------------");
level++;
dumpPart((Part)p.getContent());
level--;
} else if (!showStructure) {
* If we actually want to see the data, and it's not a
* MIME type we know, fetch it and check its Java type.
Object o = p.getContent();
if (o instanceof String) {
pr("This is a string");
pr("---------------------------");
System.out.println((String)o);
} else if (o instanceof InputStream) {
pr("This is just an input stream");
pr("---------------------------");
InputStream is = (InputStream)o;
int c;
while ((c = is.read()) != -1)
System.out.write(c);
} else {
pr("This is an unknown type");
pr("---------------------------");
pr(o.toString());
} else {
pr("This is an unknown type");
pr("---------------------------");
public static void dumpEnvelope(Message m) throws Exception {
pr("This is the message envelope");
pr("---------------------------");
Address[] a;
// FROM
if ((a = m.getFrom()) != null) {
for (int j = 0; j < a.length; j++)
pr("FROM: " + a[j].toString());
// TO
if ((a = m.getRecipients(Message.RecipientType.TO)) != null) {
for (int j = 0; j < a.length; j++)
pr("TO: " + a[j].toString());
// SUBJECT
pr("SUBJECT: " + m.getSubject());
// DATE
Date d = m.getSentDate();
pr("SendDate: " +
(d != null ? d.toString() : "UNKNOWN"));
// FLAGS
Flags flags = m.getFlags();
StringBuffer sb = new StringBuffer();
Flags.Flag[] sf = flags.getSystemFlags(); // get the system flags
boolean first = true;
for (int i = 0; i < sf.length; i++) {
String s;
Flags.Flag f = sf[i];
if (f == Flags.Flag.ANSWERED)
s = "\\Answered";
else if (f == Flags.Flag.DELETED)
s = "\\Deleted";
else if (f == Flags.Flag.DRAFT)
s = "\\Draft";
else if (f == Flags.Flag.FLAGGED)
s = "\\Flagged";
else if (f == Flags.Flag.RECENT)
s = "\\Recent";
else if (f == Flags.Flag.SEEN)
s = "\\Seen";
else
continue; // skip it
if (first)
first = false;
else
sb.append(' ');
sb.append(s);
String[] uf = flags.getUserFlags(); // get the user flag strings
for (int i = 0; i < uf.length; i++) {
if (first)
first = false;
else
sb.append(' ');
sb.append(uf[i]);
pr("FLAGS: " + sb.toString());
// X-MAILER
String[] hdrs = m.getHeader("X-Mailer");
if (hdrs != null)
pr("X-Mailer: " + hdrs[0]);
else
pr("X-Mailer NOT available");
static String indentStr = " ";
static int level = 0;
* Print a, possibly indented, string.
public static void pr(String s) {
if (showStructure)
System.out.print(indentStr.substring(0, level * 2));
System.out.println(s);
This code is to move the message into a file
import javax.mail.*;
import com.sun.mail.pop3.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.*;
import java.io.*;
//This class copies the content of the received e-mail into files. The file names are given by
//the urgent flag value and the subject
public class MoveMessageTo {
boolean createdFile = true;
static final byte urgentFlagPos=13;
public MoveMessageTo() {
public MoveMessageTo(Message[] msgs) {
if(msgs.length != 0)
try {
for(int i = 0;i<msgs.length ;i++){
//Reads the content of the mail into an Object
Object currMultipart = msgs[i].getContent();
//converts this object into a String and then to a byte array, so we can read the urgnet flag
String content=(String)currMultipart;
byte[] testBytes=content.getBytes();
//The urgent flag is the first digit in the filename
StringBuffer fileName=new StringBuffer();
if (testBytes.length>urgentFlagPos)
fileName.append(new Byte(testBytes[urgentFlagPos]).toString());
//Then comes the subject of the e-mail
String mailSubject=msgs[i].getSubject();
if (mailSubject.length()>0)
fileName.append(mailSubject);
else fileName.append("noSubject");
fileName.append(".dat");
//create a directory to save the files
File baseDir = new File("c:/EMails/New");
baseDir.mkdirs();
//create file for with the subject as name
File eFile = new File(baseDir+"/"+fileName.toString());// creates a file by name of email subject
//Opening an stream for writting to the files
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(eFile));
ObjectOutputStream oos = new ObjectOutputStream(bos);
//Writing the message body to the file
oos.writeObject(currMultipart) ;
//Closing the stream
oos.flush() ;
oos.close() ;
createdFile = true;
}catch (Exception ex) {
createdFile = false;
System.out.println("eFile is not created ");
ex.printStackTrace() ;
public static void main(String[] args) {
MoveMessageTo moveMessageTo1 = new MoveMessageTo();
This code is if there is an error in reading a file it will write those error into the file
import java.io.*;
import javax.swing.*;
import java.awt.Color;
import javax.swing.border.*;
//This class appends an error message to the log file
public class ErrorLogWriter {
//JPanel jPanel2 = new JPanel();
//Border border1;
String logDirectory="c:/EMails/log/";
File errFile; //= new File(errDir+"/"+"errorLog.dat");
//The constructor initializes the errFile given the filename
public ErrorLogWriter(String fileName) {
errFile=new File(logDirectory+fileName);
/*try {
jbInit();
}catch(Exception e) {
e.printStackTrace();
public void write(String writeStr){
try {
//Creates directory if doesn't exist
File errDir = new File(logDirectory);
errDir.mkdirs() ;
//If the directory exists...
if(errDir.isDirectory()){
//File errFile = new File(errDir+"/"+"errorLog.dat");
byte[] lastContent=new byte[0];
//If there is already a file with this name: Read its content so it can be preserved
if (errFile.exists()){
FileInputStream fis=new FileInputStream(errFile);
//Read everything into the byte array
lastContent=new byte[fis.available()];
fis.read(lastContent);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(errFile));
PrintWriter oos = new PrintWriter(bos);
String newWriteString=new String(lastContent);
writeStr.trim() ;
//Appends the new string to the old content
newWriteString+=writeStr;
newWriteString+="\n";
//writes everthing back to the file
oos.write(newWriteString) ;
oos.flush();
oos.close();
}catch (Exception ex) {
ex.printStackTrace() ;
public static void main(String[] args) {
ErrorLogWriter log = new ErrorLogWriter("logerror.log");
log.write("Hello Log!") ;
All these file are in one package called SunMail and i run this in jbuilder in 4.0 ,I get the following error
eFile is not created
java.lang.ClassCastException: javax.mail.internet.MimeMultipart
at MoveMessageTo.<init>(MoveMessageTo.java:26)
at SunMailConnection.run(SunMailConnection.java:86)
at SunMailConnection.start(SunMailConnection.java:118)
at SunMailConnection.<init>(SunMailConnection.java:21)
at SunMailConnection.main(SunMailConnection.java:133)
I know the it would be difficult if anyone could help me out it would be a great favour !!!
pls help me out of this !!!! -
JavaMail application hanged with no error throwed at Transport.send
JavaMail application hanged with no error throwed at Transport.send,even though I set the timeout property
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
public class tt {
static Properties props=null;
static boolean needAuth=true;
static MailAuthenticator authenticator = null;
static String host="host";
static String account="account";
static String password="pwd";
static String sender="sender";
* @param args
* @throws Exception
public static void main(String[] args) throws Exception{
if (props == null) {
props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.timeout ", "1000");
props.put("mail.smtp.connectiontimeout ", "1000");
// props.put("mail.debug", "true");
props.put("mail.smtp.auth", String.valueOf(needAuth));
authenticator = new MailAuthenticator(account, password);
MailData mailData = new MailData();
mailData.setSubject("altireport mail configuration");
mailData.setContent("mail server has been configured successfully.");
mailData.setRecipients(new String[]{"[email protected]"});
final Session session = Session.getInstance(props, authenticator);
final MimeMessage msg = new MimeMessage(session);
InternetAddress from = new InternetAddress(sender);
msg.setFrom(from);
// msg.setSender(from);
final InternetAddress[] addressTo = new InternetAddress[mailData.getRecipients().length];
for (int i = 0; i < mailData.getRecipients().length; i++) {
addressTo[i] = new InternetAddress(mailData.getRecipients());
msg.addRecipients(Message.RecipientType.TO, addressTo);
//msg.setSubject(mailData.getSubject());
msg.setSubject(MimeUtility.encodeText(mailData.getSubject(), "UTF-8", "B"));
MimeBodyPart bodyPart1 = new MimeBodyPart();
bodyPart1.setContent(mailData.getContent(), "text/plain; charset=UTF-8");
MimeMultipart multipart = new MimeMultipart();
multipart.addBodyPart(bodyPart1);
msg.setContent(multipart);
msg.setSentDate(new Date());
// msg.saveChanges();
for(int i=0;i<10;i++){
new Thread(new Runnable(){
public void run() {
try {
System.out.println("send...");
Transport.send(msg);
} catch (Exception e) {
e.printStackTrace(System.out);
System.out.println("end!");
}).start();
class MailData {
private String[] recipients = null;
private String subject = null;
private String content = null;
private String attachment = null;
private String attachmentName = null;
* @return the attachment
public String getAttachment() {
return attachment;
* @param attachment the attachment to set
public void setAttachment(String attachment) {
this.attachment = attachment;
* @return the content
public String getContent() {
return content;
* @param content the content to set
public void setContent(String content) {
this.content = content;
* @return the recipients
public String[] getRecipients() {
return recipients;
* @param recipients the recipients to set
public void setRecipients(String[] recipients) {
this.recipients = recipients;
* @return the subject
public String getSubject() {
return subject;
* @param subject the subject to set
public void setSubject(String subject) {
this.subject = subject;
* @return the attachmentName
public String getAttachmentName()
return attachmentName;
* @param attachmentName the attachmentName to set
public void setAttachmentName(String attachmentName)
this.attachmentName = attachmentName;
class MailAuthenticator extends Authenticator {
private PasswordAuthentication authentication;
public MailAuthenticator(String account, String password) {
authentication = new PasswordAuthentication(account, password);
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
I have tried use session to get a SMTPTransport instance to use sendMessage ,but still have the same problem.No exception ,No error.
This problem doesn't appear always. It appears sometimes.
I hope get help for someone who has the solution for this problem.
Thanks in advanced.Ok, I think I see the problem:
props.put("mail.smtp.timeout ", "1000");
props.put("mail.smtp.connectiontimeout ", "1000");
Why do you have spaces at the end of the property names?
Those spaces are not being ignored, which means you've
set the wrong properties.
Maybe you are looking for
-
2nd Monitor Connected Via DVI to VGA Adapter is Blurry
I have a G4 dual 1.42 GHz (the last G4 model) and have an Apple 20" Cinema Display connected to the ADC port and a 21" CRT monitor connected to the DVI port via the DVI to VGA adapter supplied with the G4. The CRT monitor display is blurry. I have tw
-
Partner Function for STO and relevant inbound delivery
Dear Expert, i did the partner configuration for Vendor and STO with partner VN-vendor DP-delivery plant. When i create the STO vendor UP07, both of VN and DP are UP07, but when i create the STO for UP07, no partner data come out for the PO, the part
-
FRM-40010 when opening custom form in Forms6i
Hello, I'm running an instance of the E-Business Suite 11.5.10.2, which uses Forms Developer 6i. I recently upgrated to patchset 19, and now, I go to my custom apps login URL, and get the following error: http://ppc-oradev.purchasingpwr.com:8000/dev6
-
Exchange 2013 PF. Add mark as reponsed when user change Category
Hello, I have public folders with e-mail enabled adress. When the user open the public folder in his Outlook 2007 & Outlook 2013, and change the Category, Exchange add a mark as this email is responsed. This can be worse if the folder have an autores
-
Archive, Repair Disk Permissions, etc. problems
I have problems trying to archive files/folders. I get an error message: "The archive's list of contents cannot be created." I tried repairing disk permissions and it would still have that error message. Later, I decided to try to use Onyx, however,