on ‎2021 Sep 17 8:00 AM
Hi All,
I have a requirement to check content is present in the Body of an incoming email , if content(HTML or Plain) is there in the Body of an email then capture the entire body content into a string and map to a Filed in Target IDoc in SAP CPI. It is Mail to IDoc flow.
Please help me with Groovy script for the same.
Thanks in Advance,
Venn
Request clarification before answering.
I know this question is out-dated, but maybe this answer could help someone out in the future.
After struggling with this scenario I was able to solve this problem with a few lines of code in Groovy. To start with, the email sender if generating a message with two body parts, one in plain text and the other one in HTML.

CPI by default is returning the plain text content if you call the message.getBody(java.lang.String). The secret is calling the getBody method without a class parameter and treat it as a MultiPart.
With these lines of code you can fetch both bodies and use them as needed:
//gets log
def messageLog = messageLogFactory.getMessageLog(message);
def emailBody = "";
//get multipart from body
def mimeMultiPart = message.getBody();
//loops body parts
int numberOfParts = mimeMultiPart.getCount();
for (int partIndex = 0; partIndex < numberOfParts; ++partIndex) {
MimeBodyPart mimeBodyPart = (MimeBodyPart) mimeMultiPart.getBodyPart(partIndex);
//gets body part content type
def bodyPartContentType = mimeBodyPart.getContentType();
bodyPartContentType = bodyPartContentType.toUpperCase();
//checks if body part is plain text
if (bodyPartContentType.indexOf("TEXT/PLAIN") == 0) {
//text mail
emailBody = mimeBodyPart.getContent().toString();
//saves log
if (messageLog != null) {
messageLog.addAttachmentAsString("Email Body TEXT", emailBody, "text/plain");
}
}
//checks if body part is HTML
if (bodyPartContentType.indexOf("TEXT/HTML") == 0) {
//HTML mail
emailBody = mimeBodyPart.getContent().toString();
//saves log
if (messageLog != null) {
messageLog.addAttachmentAsString("Email Body HTML", emailBody, "text/plain");
}
break;
}
}
Each body has been saved in the log:


You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
| User | Count |
|---|---|
| 4 | |
| 2 | |
| 1 | |
| 1 | |
| 1 |
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.