use of javax.mail.BodyPart in project opennms by OpenNMS.
the class JavaMailer method buildMessage.
/**
* Build a complete message ready for sending.
*
* @return completed message, ready to be passed to Transport.sendMessage
* @throws org.opennms.javamail.JavaMailerException if any of the underlying operations fail
*/
public Message buildMessage() throws JavaMailerException {
try {
checkEnvelopeAndContents();
MimeMessage message = initializeMessage();
// The next line has been commented, because it prevents the usage of internationalized characters and makes the email unreadable.
// String encodedText = MimeUtility.encodeText(getMessageText(), m_charSet, m_encoding);
String encodedText = getMessageText();
if ((getFileName() == null) && (getInputStream() == null)) {
message.setContent(encodedText, m_contentType + "; charset=" + m_charSet);
} else if (getFileName() == null) {
BodyPart streamBodyPart = new MimeBodyPart();
streamBodyPart.setDataHandler(new DataHandler(new InputStreamDataSource(m_inputStreamName, m_inputStreamContentType, m_inputStream)));
streamBodyPart.setFileName(m_inputStreamName);
streamBodyPart.setHeader("Content-Transfer-Encoding", "base64");
streamBodyPart.setDisposition(Part.ATTACHMENT);
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(streamBodyPart);
message.setContent(mp);
} else {
BodyPart bp = new MimeBodyPart();
bp.setContent(encodedText, m_contentType + "; charset=" + m_charSet);
MimeMultipart mp = new MimeMultipart();
mp.addBodyPart(bp);
mp.addBodyPart(createFileAttachment(new File(getFileName())));
message.setContent(mp);
}
message.setHeader("X-Mailer", getMailer());
message.setSentDate(new Date());
message.saveChanges();
return message;
} catch (AddressException e) {
LOG.error("Java Mailer Addressing exception: ", e);
throw new JavaMailerException("Java Mailer Addressing exception: ", e);
} catch (MessagingException e) {
LOG.error("Java Mailer messaging exception: ", e);
throw new JavaMailerException("Java Mailer messaging exception: ", e);
// } catch (UnsupportedEncodingException e) {
// log().error("Java Mailer messaging exception: ", e);
// throw new JavaMailerException("Java Mailer encoding exception: ", e);
}
}
use of javax.mail.BodyPart in project nhin-d by DirectProject.
the class Notification method getNotificationFieldsAsHeaders.
/**
* Parses the notification part fields of the MimeMultipart body of a MDN message. The multipart is expected to conform to the MDN specification
* as described in RFC3798.
* @return The notification part fields as a set of Internet headers.
*/
public static InternetHeaders getNotificationFieldsAsHeaders(MimeMultipart mm) {
InternetHeaders retVal = null;
if (mm == null)
throw new IllegalArgumentException("Multipart can not be null");
try {
if (mm.getCount() < 2)
throw new IllegalArgumentException("Multipart can not be null");
// the second part should be the notification
BodyPart part = mm.getBodyPart(1);
try {
Object contecntObj = part.getContent();
if (dsnClass != null && dsnClass.getCanonicalName().equals(contecntObj.getClass().getCanonicalName())) {
retVal = (InternetHeaders) getHeaders.invoke(contecntObj);
return retVal;
}
} catch (Exception e) {
/* no-op */
}
if (!part.getContentType().equalsIgnoreCase(MDNStandard.MediaType.DispositionNotification))
throw new IllegalArgumentException("Notification part content type is not " + MDNStandard.MediaType.DispositionNotification);
// parse fields
retVal = new InternetHeaders();
String[] fields = getPartContentBodyAsString(part).split("\r\n");
for (String field : fields) {
int idx = field.indexOf(":");
if (idx > -1) {
String name = field.substring(0, idx);
String value = field.substring(idx + 1).trim();
retVal.setHeader(name, value);
}
}
} catch (MessagingException e) {
throw new NHINDException("Failed to parse notification fields.", e);
}
return retVal;
}
use of javax.mail.BodyPart in project nhin-d by DirectProject.
the class DefaultMimeXdsTransformer method transform.
/*
* (non-Javadoc)
*
* @see org.nhindirect.transform.MimeXdsTransformer#transform(javax.mail.internet.MimeMessage)
*/
@Override
public ProvideAndRegisterDocumentSetRequestType transform(MimeMessage mimeMessage) throws TransformationException {
ProvideAndRegisterDocumentSetRequestType request;
DirectDocuments documents = new DirectDocuments();
byte[] xdsDocument = null;
String xdsMimeType = null;
FormatCodeEnum xdsFormatCode = null;
DirectDocumentType documentType = null;
try {
Date sentDate = mimeMessage.getSentDate();
String subject = mimeMessage.getSubject();
String from = mimeMessage.getFrom()[0].toString();
Address[] recipients = mimeMessage.getAllRecipients();
// Plain mail (no attachments)
if (MimeType.TEXT_PLAIN.matches(mimeMessage.getContentType())) {
LOGGER.info("Handling plain mail (no attachments) - " + mimeMessage.getContentType());
// Get the document type
documentType = DirectDocumentType.lookup(mimeMessage);
// Get the format code and MIME type
xdsFormatCode = documentType.getFormatCode();
xdsMimeType = documentType.getMimeType().getType();
// Get the contents
xdsDocument = ((String) mimeMessage.getContent()).getBytes();
// Add document to the collection of documents
documents.getDocuments().add(getDocument(sentDate, from, xdsMimeType, xdsFormatCode, xdsDocument, documentType));
documents.setSubmissionSet(getSubmissionSet(subject, sentDate, from, recipients, xdsDocument, documentType));
} else // Multipart/mixed (attachments)
if (MimeType.MULTIPART.matches(mimeMessage.getContentType())) {
LOGGER.info("Handling multipart/mixed - " + mimeMessage.getContentType());
MimeMultipart mimeMultipart = (MimeMultipart) mimeMessage.getContent();
BodyPart xdmBodyPart = null;
for (int i = 0; i < mimeMultipart.getCount(); i++) {
//check for XDM
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
documentType = DirectDocumentType.lookup(bodyPart);
if (DirectDocumentType.XDM.equals(documentType)) {
xdmBodyPart = bodyPart;
}
}
// For each BodyPart
for (int i = 0; i < mimeMultipart.getCount(); i++) {
/*
* Special handling for XDM attachments.
*
* Spec says if XDM package is present, this will be the
* only attachment.
*
* Overwrite all documents with XDM content and then break
*/
if (xdmBodyPart != null) {
XdmPackage xdmPackage = XdmPackage.fromXdmZipDataHandler(xdmBodyPart.getDataHandler());
// Spec says if XDM package is present, this will be the only attachment
// Overwrite all documents with XDM content and then break
System.out.println("XDM FILE FOUND");
documents = xdmPackage.getDocuments();
break;
}
BodyPart bodyPart = mimeMultipart.getBodyPart(i);
// Skip empty BodyParts
if (bodyPart.getSize() <= 0) {
LOGGER.warn("Empty body, skipping");
continue;
}
// Get the document type
documentType = DirectDocumentType.lookup(bodyPart);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("File name: " + bodyPart.getFileName());
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Content type: " + bodyPart.getContentType());
}
if (LOGGER.isInfoEnabled()) {
LOGGER.info("DocumentType: " + documentType.toString());
}
// Get the format code and MIME type
xdsFormatCode = documentType.getFormatCode();
xdsMimeType = documentType.getMimeType().getType();
// Best guess for UNKNOWN MIME type
if (DirectDocumentType.UNKNOWN.equals(documentType)) {
xdsMimeType = bodyPart.getContentType();
}
// Get the contents
xdsDocument = read(bodyPart);
// Add the document to the collection of documents
documents.getDocuments().add(getDocument(sentDate, from, xdsMimeType, xdsFormatCode, xdsDocument, documentType));
documents.setSubmissionSet(getSubmissionSet(subject, sentDate, from, recipients, xdsDocument, documentType));
}
} else {
if (LOGGER.isWarnEnabled()) {
LOGGER.warn("Message content type (" + mimeMessage.getContentType() + ") is not supported, skipping");
}
}
} catch (MessagingException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Unexpected MessagingException occured while handling MimeMessage", e);
}
throw new TransformationException("Unable to complete transformation.", e);
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Unexpected IOException occured while handling MimeMessage", e);
}
throw new TransformationException("Unable to complete transformation.", e);
} catch (Exception e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Unexpected Exception occured while handling MimeMessage", e);
}
throw new TransformationException("Unable to complete transformation", e);
}
try {
request = documents.toProvideAndRegisterDocumentSetRequestType();
} catch (IOException e) {
if (LOGGER.isErrorEnabled()) {
LOGGER.error("Unexpected IOException occured while transforming to ProvideAndRegisterDocumentSetRequestType", e);
}
throw new TransformationException("Unable to complete transformation", e);
}
return request;
}
use of javax.mail.BodyPart in project uPortal by Jasig.
the class EmailPasswordResetNotificationImplTest method getBodyHtml.
private String getBodyHtml(Multipart msg) throws Exception {
for (int i = 0; i < msg.getCount(); i++) {
BodyPart part = msg.getBodyPart(i);
String type = part.getContentType();
if ("text/plain".equals(type) || "text/html".equals(type)) {
DataHandler handler = part.getDataHandler();
String val = IOUtils.toString(handler.getInputStream());
return val;
}
}
return null;
}
use of javax.mail.BodyPart in project nhin-d by DirectProject.
the class NotificationTest method testCreateNotification_AssertMultipart.
public void testCreateNotification_AssertMultipart() throws Exception {
Notification noti = new Notification(NotificationType.Processed);
MimeMultipart mm = noti.getAsMultipart();
assertNotNull(mm);
assertEquals(2, mm.getCount());
BodyPart part = mm.getBodyPart(0);
assertTrue(part.getContentType().startsWith("text/plain"));
assertEquals("Your message was successfully processed.", part.getContent().toString());
part = mm.getBodyPart(1);
assertTrue(part.getContentType().startsWith("message/disposition-notification"));
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
part.writeTo(outStream);
String content = new String(outStream.toByteArray());
assertTrue(content.contains("automatic-action/MDN-sent-automatically;processed"));
}
Aggregations