I've made an E- Mail Client for my Android- Phone using the JavaMail API. I dont knoq how to get the E- Mail Content if it's a html- Mail. I'm using the following Code to get the Content:
public void printMessage(int messageNo) throws Exception {
Log.i("MsgNo", "Getting message number: " + messageNo);
Message m = null;
try {
m = folder.getMessage(messageNo);
dumpPart(m);
} catch (IndexOutOfBoundsException iex) {
Log.i("Out of Range","Message number out of range");
}
}
public static void dumpPart(Part p) throws Exception {
if (p instanceof Message)
dumpEnvelope((Message)p);
Object content = p.getContent();
Log.i("dumpPart",(String) content);
String ct = p.getContentType();
try {
pr("CONTENT-TYPE: " + (new ContentType(ct)).toString());
Log.i("MsgNo", "Content Type");
} catch (ParseException pex) {
pr("BAD CONTENT-TYPE: " + ct);
Log.i("MsgNo", "Bad Content Type");
}
//* 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("---------------------------");
Log.i("Text", (String)p.getContent());
} else {
Log.i("MsgNo", "Just a Separator");
// just a separator
pr("---------------------------");
}
}
In the Logcat, i get the return value of dumpenvelope((Message)p); , but after that nothing.
Does anybody know what to do?
Is any exception thrown?
Did you enable debugging and examine the protocol trace to see what might have failed?
Are you using IMAP?
It looks like your program was created out of pieces of the JavaMail sample program called msgshow.java, did you find the complete original sample program?
This JavaMail FAQ entry might help as well.
Related
I have a problem with CRM Dynamics Online 2016 Azure SDK for Java.
I can connect to Azure Service Bus, I can see queues and message count in queues, but cannot receive messages. Message Id is null and message body contain 500 error
500The server was unable to process the
request; please retry the operation. If the problem persists, please
contact your Service Bus administrator and provide the tracking id.
TrackingId:acf8a543-33c9-486d-b13b-443823e6c394_G9,TimeStamp:4/13/2016
7:26:22 AM. If the problem persists, please contact
your Service Bus administrator and provide the tracking id.
TrackingId:acf8a543-33
Is there any working sample on the Internet to solve the problem?
Test code:
#Test
public void readAllExistedMessagesFromAllQueue() {
try {
ServiceBusContract serviceBusContract = ServiceBusConfiguration.configureWithConnectionString(null, Configuration.load(), ASB_CONNECTION_STRING).create(ServiceBusContract.class);
ReceiveMessageOptions opts = ReceiveMessageOptions.DEFAULT;
opts.setReceiveMode(ReceiveMode.PEEK_LOCK);
ListQueuesResult result = serviceBusContract.listQueues();
if (result != null && result.getItems().size() > 0) {
for (QueueInfo queueInfo : result.getItems()) {
logger.debug("queu: " + queueInfo.getPath() + " MessageCount: " + queueInfo.getMessageCount());
for (int i = 0; i < result.getItems().size(); i++) {
BrokeredMessage message = serviceBusContract.receiveQueueMessage(queueInfo.getPath(),
opts).getValue();
if (message == null) {
continue;
}
System.out.print("__________________________________________");
System.out.println("MessageID: " + message.getMessageId());
System.out.print("From queue: ");
byte[] b = new byte[200];
String s = null;
int numRead = message.getBody().read(b);
while (-1 != numRead) {
s = new String(b);
s = s.trim();
System.out.print(s);
numRead = message.getBody().read(b);
}
System.out.println();
}
}
}
} catch (IOException e) {
logger.error(e);
} catch (ServiceException e) {
logger.error(e);
}
}
Per my experience, according to the source code and javadocs of Service Bus, the ServiceBusContract is a Java interface, that you can't directly create an instance of the interface ServiceBusContract.
So please try to use the code below from the section Create a queue of the document "How to use Service Bus queues".
Configuration config =
ServiceBusConfiguration.configureWithSASAuthentication(
"<your-servicebus-namespace>",
"RootManageSharedAccessKey",
"<SAS-key-value>",
".servicebus.windows.net"
);
ServiceBusContract serviceBusContract = ServiceBusService.create(config);
Update
You can find the SharedAccessKeyName & SharedAccessKey in the connection string via click the button below at the bottom of your service bus page.
Then, show the view below and copy the CONNECTION STRING.
The connection string like this below.
Endpoint=sb://<your-servicebus-namespace>.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=<SAS-key-value>
Please copy the correct part of connection string instead of the related part of the code.
I am trying to create an HL7 message in Java and then print the resulting message. I am faking basic patient information and then adding the Drug Prescription information. Then, I want to print the complete message but I wasn't able to use the API correctly. I am new at using HL7, so I know I'm probably missing some required segments and even using the wrong ones, can you please help? This is my current code:
public RXO runDrugPrescriptionEvent(CMSGeneric cmsgen) {
CMSDrugPrescriptionEvent cmsic = (CMSDrugPrescriptionEvent) cmsgen;
ADT_A28 adt23 = new ADT_A28();
try {
adt23.initQuickstart("ADT", "A08", cmsic.getPDE_EVENT_ID());
// We set the sex identity (male or female)
if (cmsic.getBENE_SEX_IDENT_CD() == 1) {
adt23.getPID().getSex().setValue("Male");
}
else {
adt23.getPID().getSex().setValue("Female");
}
// We set a fake name and family name
adt23.getPID().insertPatientName(0).getGivenName().setValue("CMS Name " + MainTest.NEXT_PATIENT_ID);
adt23.getPID().insertPatientName(0).getFamilyName().setValue("CMS Family name " + MainTest.NEXT_PATIENT_ID);
MainTest.NEXT_PATIENT_ID++;
RXO rxo = new RXO(adt23, new DefaultModelClassFactory());
rxo.getRxo1_RequestedGiveCode().getCe1_Identifier().setValue("" + cmsic.getPDE_DRUG_CD());
rxo.getRxo18_RequestedGiveStrength().setValue("" + cmsic.getPDE_DRUG_STR_CD());
rxo.getRxo19_RequestedGiveStrengthUnits().getCe1_Identifier().setValue("" + cmsic.getPDE_DRUG_STR_UNITS());
rxo.getRxo5_RequestedDosageForm().getCe1_Identifier().setValue("" + cmsic.getPDE_DRUG_DOSE_CD());
rxo.getRxo11_RequestedDispenseAmount().setValue("" + cmsic.getPDE_DRUG_QTY_DIS());
HapiContext context = new DefaultHapiContext();
Parser parser = context.getPipeParser();
String encodedMessage = adt23.getParser().encode(rxo.getMessage());
logger.debug("Printing Message:");
logger.debug(encodedMessage);
return rxo;
} catch (IOException e) {
System.out.println("IOException creating HL7 message. " + e.getMessage());
e.printStackTrace();
} catch (HL7Exception e) {
System.out.println("HL7Exception creating HL7 message. " + e.getMessage());
e.printStackTrace();
}
return null;
}
With this code, the logger prints the following message:
MSH|^~\&|||||20160331101349.8+0100||ADT^A08|110001|PDE-00001E6FADAD3F57|2.3
PID|||||CMS Family name 100~^CMS Name 100|||Female
But I was expecting to see the RXO segment as well. How can I achieve that?
I found that changing the message type from ADT_A28 to ORP_O10 would let me have all the fields I need, as ADT_A28 wasn't the appropriate message for the kind of information I needed. There's a complete example on how to set a great amount of segments in this type of message here. Then, I was able to print the complete message using the PipeParser:
HapiContext context = new DefaultHapiContext();
Parser parser = context.getPipeParser();
String encodedMessage = parser.encode(msg);
logger.debug("Printing EREncoded Message:");
logger.debug(encodedMessage);
I want to pass an object using xmlrpc as this is the only possible way it seems that I can pass an Integer and a String to a method on the server. Is it possible to do this using an object? If not is there some other way of doing it?
I have attempted to do it but am getting this error:
JavaClient: XML-RPC Consumer Fault #java.io.IOException: unsupported
Java type: class Client.Article
This is the code on the client side:
public void addHash()
{
try {
addAuthorName = txtAddAuthorName.getText();
int addArticleNumber = Integer.parseInt(txtAddArticleNumber.getText());
newArticle = new Article(addAuthorName, addArticleNumber);
Vector<Object> addArticleArglist = new Vector<Object>();
addArticleArglist.addElement(newArticle);
System.out.println(newArticle);
// make the call
String callit = ("GetSize.addHash");
articleID = (Integer) client.execute(callit, addArticleArglist);
} // Use XmlRpcException errors
catch (XmlRpcException exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #"
+ Integer.toString(exception.code) + ": "
+ exception.getCause() + "" + exception.toString());
} catch (Exception exception) {
System.err.println("JavaClient: XML-RPC Consumer Fault #" + exception.toString());
}
}
This is the code on the server side however by using System.out.println I have discovered that for whatever reason none of the code within this method is being executed:
public void addHash(Article newArticle)
{
theHashtable.addHash(newArticle.getArticleName(), newArticle.getAuthorID());
}
Assuming you are using ws-xmlrpc the documentation states the following:
DOM nodes, or JAXB objects, can be transmitted. So are objects implementing the java.io.Serializable interface.
So by declaring your object serializable you would be able to transmit it. Depending what you want to do it might be a good idea to take a good look at jaxb.
See http://ws.apache.org/xmlrpc/ for more info.
I wrote an application which gets all emails from an inbox, filters the emails which contain a specific string and then puts those emails in an ArrayList.
After the emails are put in the List, I am doing some stuff with the subject and content of said emails. This works all fine for e-mails without an attachment. But when I started to use e-mails with attachments it all didn't work as expected anymore.
This is my code:
public void getInhoud(Message msg) throws IOException {
try {
cont = msg.getContent();
} catch (MessagingException ex) {
Logger.getLogger(ReadMailNew.class.getName()).log(Level.SEVERE, null, ex);
}
if (cont instanceof String) {
String body = (String) cont;
} else if (cont instanceof Multipart) {
try {
Multipart mp = (Multipart) msg.getContent();
int mp_count = mp.getCount();
for (int b = 0; b < 1; b++) {
dumpPart(mp.getBodyPart(b));
}
} catch (Exception ex) {
System.out.println("Exception arise at get Content");
ex.printStackTrace();
}
}
}
public void dumpPart(Part p) throws Exception {
email = null;
String contentType = p.getContentType();
System.out.println("dumpPart" + contentType);
InputStream is = p.getInputStream();
if (!(is instanceof BufferedInputStream)) {
is = new BufferedInputStream(is);
}
int c;
final StringWriter sw = new StringWriter();
while ((c = is.read()) != -1) {
sw.write(c);
}
if (!sw.toString().contains("<div>")) {
mpMessage = sw.toString();
getReferentie(mpMessage);
}
}
The content from the e-mail is stored in a String.
This code works all fine when I try to read mails without attachment. But if I use an e-mail with attachment the String also contains HTML code and even the attachment coding. Eventually I want to store the attachment and the content of an e-mail, but my first priority is to get just the text without any HTML or attachment coding.
Now I tried an different approach to handle the different parts:
public void getInhoud(Message msg) throws IOException {
try {
Object contt = msg.getContent();
if (contt instanceof Multipart) {
System.out.println("Met attachment");
handleMultipart((Multipart) contt);
} else {
handlePart(msg);
System.out.println("Zonder attachment");
}
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
public static void handleMultipart(Multipart multipart)
throws MessagingException, IOException {
for (int i = 0, n = multipart.getCount(); i < n; i++) {
handlePart(multipart.getBodyPart(i));
System.out.println("Count "+n);
}
}
public static void handlePart(Part part)
throws MessagingException, IOException {
String disposition = part.getDisposition();
String contentType = part.getContentType();
if (disposition == null) { // When just body
System.out.println("Null: " + contentType);
// Check if plain
if ((contentType.length() >= 10)
&& (contentType.toLowerCase().substring(
0, 10).equals("text/plain"))) {
part.writeTo(System.out);
} else if ((contentType.length() >= 9)
&& (contentType.toLowerCase().substring(
0, 9).equals("text/html"))) {
part.writeTo(System.out);
} else if ((contentType.length() >= 9)
&& (contentType.toLowerCase().substring(
0, 9).equals("text/html"))) {
System.out.println("Ook html gevonden");
part.writeTo(System.out);
}else{
System.out.println("Other body: " + contentType);
part.writeTo(System.out);
}
} else if (disposition.equalsIgnoreCase(Part.ATTACHMENT)) {
System.out.println("Attachment: " + part.getFileName()
+ " : " + contentType);
} else if (disposition.equalsIgnoreCase(Part.INLINE)) {
System.out.println("Inline: "
+ part.getFileName()
+ " : " + contentType);
} else {
System.out.println("Other: " + disposition);
}
}
This is what is returned from the System.out.printlns
Null: multipart/alternative; boundary=047d7b6220720b499504ce3786d7
Other body: multipart/alternative; boundary=047d7b6220720b499504ce3786d7
Content-Type: multipart/alternative; boundary="047d7b6220720b499504ce3786d7"
--047d7b6220720b499504ce3786d7
Content-Type: text/plain; charset="ISO-8859-1"
'Text of the message here in normal text'
--047d7b6220720b499504ce3786d7
Content-Type: text/html; charset="ISO-8859-1"
Content-Transfer-Encoding: quoted-printable
'HTML code of the message'
This approach returns the normal text of the e-mail but also the HTML coding of the mail. I really don't understand why this happens, I've googled it but it seems like there is no one else with this problem.
Any help is appreciated,
Thanks!
I found reading e-mail with the JavaMail library much more difficult than expected. I don't blame the JavaMail API, rather I blame my poor understanding of RFC-5322 -- the official definition of Internet e-mail.
As a thought experiment: Consider how complicated an e-mail message can become in the real world. It is possible to "infinitely" embed messages within messages. Each message itself may have multiple attachments (binary or human-readable text). Now imagine how complicated this structure becomes in the JavaMail API after parsing.
A few tips that may help when traversing e-mail with JavaMail:
Message and BodyPart both implement Part.
MimeMessage and MimeBodyPart both implement MimePart.
Where possible, treat everything as a Part or MimePart. This will allow generic traversal methods to be built more easily.
These Part methods will help to traverse:
String getContentType(): Starts with the MIME type. You may be tempted to treat this as a MIME type (with some hacking/cutting/matching), but don't. Better to only use this method inside the debugger for inspection.
Oddly, MIME type cannot be extracted directly. Instead use boolean isMimeType(String) to match. Read docs carefully to learn about powerful wildcards, such as "multipart/*".
Object getContent(): Might be instanceof:
Multipart -- container for more Parts
Cast to Multipart, then iterate as zero-based index with int getCount() and BodyPart getBodyPart(int)
Note: BodyPart implements Part
In my experience, Microsoft Exchange servers regularly provide two copies of the body text: plain text and HTML.
To match plain text, try: Part.isMimeType("text/plain")
To match HTML, try: Part.isMimeType("text/html")
Message (implements Part) -- embedded or attached e-mail
String (just the body text -- plain text or HTML)
See note above about Microsoft Exchange servers.
InputStream (probably a BASE64-encoded attachment)
String getDisposition(): Value may be null
if Part.ATTACHMENT.equalsIgnoreCase(getDisposition()), then call getInputStream() to get raw bytes of the attachment.
Finally, I found the official Javadocs exclude everything in the com.sun.mail package (and possibly more). If you need these, read the code directly, or generate the unfiltered Javadocs by downloading the source and running mvn javadoc:javadoc in the mail project module of the project.
Did you find these JavaMail FAQ entries?
How do I read a message with an attachment and save the attachment?
How do I tell if a message has attachments?
How do I find the main message body in a message that has attachments?
Following up on Kevin's helpful advice, analyzing your email content Java object types with respect to their canonical names (or simple names) can be helpful too. For example, looking at one inbox I've got right now, of 486 messages 399 are Strings, and 87 are MimeMultipart. This suggests that - for my typical email - a strategy that uses instanceof to first peel off Strings is best.
Of the Strings, 394 are text/plain, and 5 are text/html. This will not be the case for most; it's reflective of my email feeds into this particular inbox.
But wait - there's more!!! :-) The HTML sneaks in there nevertheless: of the 87 Multipart's, 70 are multipart/alternative. No guarantees, but most (if not all of these) are TEXT + HTML.
Of the other 17 multipart, incidentally, 15 are multipart/mixed, and 2 are multipart/signed.
My use case with this inbox (and one other) is primarily to aggregate and analyze known mailing list content. I can't ignore any of the messages, but an analysis of this sort helps me make my processing more efficient.
I had a piece of code to read ofx file to retrieve several tags (such as acct number, balance etc.) I am using net.sf.ofx4j
Piece of code:
public void parse(String filename) throws OFXParseException, IOException, SQLException {
AggregateUnmarshaller<ResponseEnvelope> unmarshaller = new AggregateUnmarshaller<ResponseEnvelope>(
ResponseEnvelope.class);
FileInputStream file = null;
try {
file = new FileInputStream(filename);
ResponseEnvelope envelope = unmarshaller.unmarshal(file);
BankingResponseMessageSet messageSet = (BankingResponseMessageSet) envelope.getMessageSet(MessageSetType.banking);
List<BankStatementResponseTransaction> responses = messageSet.getStatementResponses();
for (BankStatementResponseTransaction response : responses) {
BankStatementResponse message = response.getMessage();
String currencyCode = message.getCurrencyCode();
String acct_number = message.getAccount().getAccountNumber();
double av = message.getAvailableBalance().getAmount();
double cur = message.getLedgerBalance().getAmount();
AccountType acct_type = message.getAccount().getAccountType();
}
} catch (OFXParseException e) {
System.out.println("Error: " + e.getMessage());
}
return null;
}
It was working fine until one day it started throwing the following exception:
net.sf.ofx4j.io.AggregateStackContentHandler onElement
INFO: Element INTU.BID is not supported on aggregate SONRS (class net.sf.ofx4j.domain.data.signon.SignonResponse) at index 70.
net.sf.ofx4j.io.AggregateStackContentHandler onElement
INFO: Element INTU.USERID is not supported on aggregate SONRS (class net.sf.ofx4j.domain.data.signon.SignonResponse) at index 70.
Exception in thread "main" java.lang.IllegalStateException: java.io.IOException: Unexpected EOF
Thanks
Hope ofx file format should be changed. because you are requesting (MessageSetType.*banking*). But in your ofx file may be have credit card details.
In early, transaction data is include in .ofx file inside the <BANKMSGSRSV1> tag.
But now transaction data is include in <CREDITCARDMSGSRSV> tag. you need to change the data receiving code.
Hope you can get some help from this. Thank you