uk.ac.cam.automation.seleniumframework.email.MimeMessageToStringConverter Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of seleniumframework Show documentation
Show all versions of seleniumframework Show documentation
A framework to enable test automation engineers to focus on writing tests rather than maintaining a testing
framework
package uk.ac.cam.automation.seleniumframework.email;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMultipart;
import java.io.IOException;
public class MimeMessageToStringConverter {
/**
* Attempts to extract the text from a mail message.
*
* @param message The raw email message
* @return Body text of the email
* @throws MessagingException for failures with checking MIME Type
* @throws IOException for general failures within the DataHandler.
*/
public static String getBodyTextFromMessage(Message message) throws MessagingException, IOException {
String result = "";
if (message.isMimeType("text/plain")) {
result = message.getContent().toString();
} else if (message.isMimeType("text/html")) {
result = (String) message.getContent();
} else if (message.isMimeType("multipart/*")) {
MimeMultipart mimeMultipart = (MimeMultipart) message.getContent();
result = getTextFromMimeMultipart(mimeMultipart);
}
return result;
}
private static String getTextFromMimeMultipart(MimeMultipart mimeMultipart) throws MessagingException, IOException {
StringBuilder result = new StringBuilder();
int count = mimeMultipart.getCount();
for (int i = 0; i < count; i++) {
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
if (bodyPart.isMimeType("text/plain")) {
result.append("\n").append(bodyPart.getContent());
break; // without break same text appears twice in my tests
} else if (bodyPart.isMimeType("text/html")) {
result = new StringBuilder((String) bodyPart.getContent());
} else if (bodyPart.getContent() instanceof MimeMultipart) {
result.append(getTextFromMimeMultipart((MimeMultipart) bodyPart.getContent()));
}
}
return result.toString();
}
}