cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Groovy script for Email body into a string

Venn_G
Participant
0 Likes
2,830

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

Accepted Solutions (0)

Answers (1)

Answers (1)

john_knight00
Explorer

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:

markangelo_dihiansan
Active Contributor
0 Likes

Hi Juan,

Thank you! Can you please make a blog about this? It might be difficult to search for this thread unless the keywords are correct.

Regards,

Mark