public static String getBody(Message message) throws Exception { try { message.getContent(); // This might throw an exception... } catch (Throwable ex) { try { // Content could not be resolved for some reason - just get the raw stuff return ConvertUtil.inputStreamToString(message.getInputStream()); } catch (Throwable ex2) { // bodystructure is corrupt - get the really raw stuff ByteArrayOutputStream out = new ByteArrayOutputStream(); message.writeTo(out); return out.toString(); } } // check if message is a normal message or a Multipart message if (message.getContent() instanceof MimeMultipart) { MultipartResult res = new MailUtils.MultipartResult(); MailUtils.readMultiPart(res, (MimeMultipart) message.getContent()); return res.body.isEmpty() ? res.bodyHtml : res.body; } else { if (message.getContent().toString() != null) { return message.getContent().toString(); } } return null; }
public static void writeMessage(Message message, OutputStream out) { try { Enumeration<Header> enu = message.getAllHeaders(); while (enu.hasMoreElements()) { Header header = enu.nextElement(); IO.writeText(out, header.getName() + ": " + header.getValue() + "\n", charset); } IO.writeText(out, "\n", charset); IO.copyData(message.getInputStream(), out); } catch (IOException ex) { throw new RuntimeException(ex); } catch (MessagingException ex) { throw new RuntimeException(ex); } }