class MailUtil {

	public static EMail msgToMail(InputStream is, boolean extractAttachmentContent) throws Exception {

		EMail email = new EMail();
		MsgParser msgp = new MsgParser();
		com.auxilii.msgparser.Message msg = msgp.parseMsg(is);

		String messageClass = msg.getMessageClass();
		if (messageClass.toLowerCase().contains(IPM_NOTE_SMIME.toLowerCase())) {
			FileAttachment p7mAttachment = (FileAttachment) msg.getAttachments().get(0);
			byte[] p7mBytes = p7mAttachment.getData();
			File tmp = File.createTempFile("msg", null);
			try {
				P7M p7m = new P7M(p7mBytes);
				p7m.extractOriginalFile(tmp);
				email = messageToMail(tmp, extractAttachmentContent);
				email.setSigned(1);
				copyMetadata(email, msg);

				return email;
			} finally {
				FileUtils.deleteQuietly(tmp);
			}
		}

		copyMetadata(email, msg);

		if (StringUtils.isNotEmpty(msg.getBodyHTML()) && msg.getBodyHTML().toLowerCase().startsWith("<html")) {
			email.setMessageText(msg.getBodyHTML());
			email.setHtml(1);
		}

		List<Attachment> atts = msg.getAttachments();
		for (Attachment att : atts) {
			if (att instanceof FileAttachment) {
				FileAttachment fatt = (FileAttachment) att;
				if (StringUtils.isNotEmpty(fatt.getFilename()) && fatt.getSize() > 0) {
					EMailAttachment emailAtt = new EMailAttachment();
					emailAtt.setFileName(fatt.getFilename());
					emailAtt.setSize(fatt.getSize());
					if (extractAttachmentContent)
						emailAtt.setData(fatt.getData());
					email.addAttachment(emailAtt);
				}
			}
		}

		return email;
	}

}