Example usage for javax.mail.internet MimeMessage getContentType

List of usage examples for javax.mail.internet MimeMessage getContentType

Introduction

In this page you can find the example usage for javax.mail.internet MimeMessage getContentType.

Prototype

@Override
public String getContentType() throws MessagingException 

Source Link

Document

Returns the value of the RFC 822 "Content-Type" header field.

Usage

From source file:org.apache.axis2.transport.mail.SimpleMailListener.java

private MessageContext createMessageContextToMailWorker(MimeMessage msg) throws Exception {
    Object content = msg.getContent();
    if (!(content instanceof Multipart)) {
        return null;
    }/* w  w w .j  a  va 2 s .  c  om*/
    MessageContext msgContext = null;
    TransportInDescription transportIn = configurationContext.getAxisConfiguration()
            .getTransportIn(org.apache.axis2.Constants.TRANSPORT_MAIL);
    TransportOutDescription transportOut = configurationContext.getAxisConfiguration()
            .getTransportOut(org.apache.axis2.Constants.TRANSPORT_MAIL);
    if ((transportIn != null) && (transportOut != null)) {
        // create Message Context
        msgContext = configurationContext.createMessageContext();
        msgContext.setTransportIn(transportIn);
        msgContext.setTransportOut(transportOut);
        msgContext.setServerSide(true);
        msgContext.setProperty(org.apache.axis2.transport.mail.Constants.CONTENT_TYPE, msg.getContentType());
        msgContext.setIncomingTransportName(org.apache.axis2.Constants.TRANSPORT_MAIL);

        MailBasedOutTransportInfo transportInfo = new MailBasedOutTransportInfo();
        Address[] mimefroms = msg.getFrom();
        if (mimefroms != null && mimefroms.length > 0) {
            EndpointReference fromEPR = new EndpointReference(
                    org.apache.axis2.transport.mail.Constants.MAILTO + ":" + msg.getFrom()[0].toString());
            transportInfo.setFrom(fromEPR);
        } else {
            String returnPath = getMailHeader(msg, org.apache.axis2.transport.mail.Constants.RETURN_PATH);
            returnPath = parseHeaderForLessThan(returnPath);
            if (returnPath != null) {
                EndpointReference fromEPR = new EndpointReference(
                        org.apache.axis2.transport.mail.Constants.MAILTO + ":" + returnPath);
                transportInfo.setFrom(fromEPR);
            }
        }

        // Save Message-Id to set as In-Reply-To on reply
        String smtpMessageId = msg.getMessageID();
        if (smtpMessageId != null) {
            transportInfo.setInReplyTo(smtpMessageId);
        }
        String inReplyTo = getMailHeader(msg, org.apache.axis2.transport.mail.Constants.IN_REPLY_TO);
        if (inReplyTo != null) {
            transportInfo.setInReplyTo(inReplyTo);
        }
        msgContext.setProperty(org.apache.axis2.Constants.OUT_TRANSPORT_INFO, transportInfo);

        buildSOAPEnvelope(msg, msgContext);
        if (!fillMessageContextFromAvaiableData(msgContext, inReplyTo)) {
            return null;
        }
    }
    return msgContext;
}

From source file:org.apache.hupa.server.handler.GetMessageDetailsHandler.java

/**
 * Handle the parts of the given message. The method will call itself recursively to handle all nested parts
 * @param message the MimeMessage //from  w  w  w .  j  a  v a 2  s . c  o  m
 * @param con the current processing Content
 * @param sbPlain the StringBuffer to fill with text
 * @param attachmentList ArrayList with attachments
 * @throws UnsupportedEncodingException
 * @throws MessagingException
 * @throws IOException
 */
protected boolean handleParts(MimeMessage message, Object con, StringBuffer sbPlain,
        ArrayList<MessageAttachment> attachmentList)
        throws UnsupportedEncodingException, MessagingException, IOException {
    boolean isHTML = false;
    if (con instanceof String) {
        if (message.getContentType().toLowerCase().startsWith("text/html")) {
            isHTML = true;
        } else {
            isHTML = false;
        }
        sbPlain.append((String) con);

    } else if (con instanceof Multipart) {

        Multipart mp = (Multipart) con;
        String multipartContentType = mp.getContentType().toLowerCase();

        String text = null;

        if (multipartContentType.startsWith("multipart/alternative")) {
            isHTML = handleMultiPartAlternative(mp, sbPlain);
        } else {
            for (int i = 0; i < mp.getCount(); i++) {
                Part part = mp.getBodyPart(i);

                String contentType = part.getContentType().toLowerCase();

                Boolean bodyRead = sbPlain.length() > 0;

                if (!bodyRead && contentType.startsWith("text/plain")) {
                    isHTML = false;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("text/html")) {
                    isHTML = true;
                    text = (String) part.getContent();
                } else if (!bodyRead && contentType.startsWith("message/rfc822")) {
                    // Extract the message and pass it
                    MimeMessage msg = (MimeMessage) part.getDataHandler().getContent();
                    isHTML = handleParts(msg, msg.getContent(), sbPlain, attachmentList);
                } else {
                    if (part.getFileName() != null) {
                        // Inline images are not added to the attachment list
                        // TODO: improve the in-line images detection 
                        if (part.getHeader("Content-ID") == null) {
                            MessageAttachment attachment = new MessageAttachment();
                            attachment.setName(MimeUtility.decodeText(part.getFileName()));
                            attachment.setContentType(part.getContentType());
                            attachment.setSize(part.getSize());
                            attachmentList.add(attachment);
                        }
                    } else {
                        isHTML = handleParts(message, part.getContent(), sbPlain, attachmentList);
                    }
                }

            }
            if (text != null)
                sbPlain.append(text);
        }

    }
    return isHTML;
}

From source file:org.apache.hupa.server.utils.TestUtils.java

public static ArrayList<String> summaryzeContent(Object content, String contentType, final int spaces)
        throws IOException, MessagingException {

    ContenTypeArrayList ret = new ContenTypeArrayList();

    ret.add(contentType, spaces);/*from   w w w  .ja v  a 2s .  co m*/
    if (content instanceof Multipart) {
        Multipart mp = (Multipart) content;
        contentType = mp.getContentType();
        for (int i = 0; i < mp.getCount(); i++) {
            Part part = mp.getBodyPart(i);
            contentType = part.getContentType();
            if (contentType.startsWith("text")) {
                ret.add(contentType, spaces + 1);
            } else if (contentType.startsWith("message/rfc822")) {
                MimeMessage msg = (MimeMessage) part.getDataHandler().getContent();
                ret.addAll(summaryzeContent(msg.getContent(), msg.getContentType(), spaces + 1));
            } else {
                if (part.getFileName() != null) {
                    ret.add(part.getContentType(), part.getFileName(), spaces + 1);
                } else {
                    ret.addAll(summaryzeContent(part.getContent(), contentType, spaces + 1));
                }
            }
        }
    }
    return ret;
}

From source file:org.apache.james.transport.mailets.DSNBounceTest.java

@Test
public void serviceShouldSendMultipartMailToTheSender() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).build();
    dsnBounce.init(mailetConfig);//  w  w w. j  a va  2s.c  o  m

    MailAddress senderMailAddress = new MailAddress("sender@domain.com");
    FakeMail mail = FakeMail.builder().sender(senderMailAddress)
            .mimeMessage(MimeMessageBuilder.mimeMessageBuilder().setText("My content")).name(MAILET_NAME)
            .recipient("recipient@domain.com").lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
            .build();

    dsnBounce.service(mail);

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    assertThat(sentMail.getSender()).isNull();
    assertThat(sentMail.getRecipients()).containsOnly(senderMailAddress);
    MimeMessage sentMessage = sentMail.getMsg();
    assertThat(sentMessage.getContentType()).contains("multipart/report;");
    assertThat(sentMessage.getContentType()).contains("report-type=delivery-status");
}

From source file:org.apache.james.transport.matchers.HasMimeTypeParameter.java

private Optional<MimeType> getMimeTypeFromMessage(MimeMessage message) throws MessagingException {
    try {/* ww  w .j a  va 2s.  c  o m*/
        return Optional.of(new MimeType(message.getContentType()));
    } catch (MimeTypeParseException e) {
        LOGGER.warn("Error while parsing message's mimeType {}", message.getContentType(), e);
        return Optional.empty();
    }
}

From source file:org.apache.jmeter.assertions.SMIMEAssertion.java

public static AssertionResult getResult(SMIMEAssertionTestElement testElement, SampleResult response,
        String name) {/*from w  w w . j  a  v  a 2s  .  c o  m*/
    checkForBouncycastle();
    AssertionResult res = new AssertionResult(name);
    try {
        MimeMessage msg = null;
        final int msgPos = testElement.getSpecificMessagePositionAsInt();
        if (msgPos < 0) { // means counting from end
            SampleResult[] subResults = response.getSubResults();
            final int pos = subResults.length + msgPos;
            if (log.isDebugEnabled()) {
                log.debug("Getting message number: " + pos + " of " + subResults.length);
            }
            msg = getMessageFromResponse(response, pos);
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Getting message number: " + msgPos);
            }
            msg = getMessageFromResponse(response, msgPos);
        }

        SMIMESignedParser s = null;
        if (log.isDebugEnabled()) {
            log.debug("Content-type: " + msg.getContentType());
        }
        if (msg.isMimeType("multipart/signed")) { // $NON-NLS-1$
            MimeMultipart multipart = (MimeMultipart) msg.getContent();
            s = new SMIMESignedParser(new BcDigestCalculatorProvider(), multipart);
        } else if (msg.isMimeType("application/pkcs7-mime") // $NON-NLS-1$
                || msg.isMimeType("application/x-pkcs7-mime")) { // $NON-NLS-1$
            s = new SMIMESignedParser(new BcDigestCalculatorProvider(), msg);
        }

        if (null != s) {
            log.debug("Found signature");

            if (testElement.isNotSigned()) {
                res.setFailure(true);
                res.setFailureMessage("Mime message is signed");
            } else if (testElement.isVerifySignature() || !testElement.isSignerNoCheck()) {
                res = verifySignature(testElement, s, name);
            }

        } else {
            log.debug("Did not find signature");
            if (!testElement.isNotSigned()) {
                res.setFailure(true);
                res.setFailureMessage("Mime message is not signed");
            }
        }

    } catch (MessagingException e) {
        String msg = "Cannot parse mime msg: " + e.getMessage();
        log.warn(msg, e);
        res.setFailure(true);
        res.setFailureMessage(msg);
    } catch (CMSException e) {
        res.setFailure(true);
        res.setFailureMessage("Error reading the signature: " + e.getMessage());
    } catch (SMIMEException e) {
        res.setFailure(true);
        res.setFailureMessage("Cannot extract signed body part from signature: " + e.getMessage());
    } catch (IOException e) { // should never happen
        log.error("Cannot read mime message content: " + e.getMessage(), e);
        res.setError(true);
        res.setFailureMessage(e.getMessage());
    }

    return res;
}

From source file:org.apache.oozie.action.email.TestEmailActionExecutor.java

public void testHDFSFileAttachment() throws Exception {
    String file1 = "file1";
    Path path1 = new Path(getFsTestCaseDir(), file1);
    String content1 = "this is attachment content in file1";
    String file2 = "file2";
    Path path2 = new Path(getFsTestCaseDir(), file2);
    String content2 = "this is attachment content in file2";
    FileSystem fs = getFileSystem();
    Writer writer = new OutputStreamWriter(fs.create(path1, true));
    writer.write(content1);//from  w w w .j a va2 s  . co m
    writer.close();
    writer = new OutputStreamWriter(fs.create(path2, true));
    writer.write(content2);
    writer.close();
    StringBuilder tag = new StringBuilder();
    tag.append(path1.toString()).append(",").append(path2.toString());
    assertAttachment(tag.toString(), 2, content1, content2);

    //test case when email attachment support set to false
    ConfigurationService.setBoolean(EmailActionExecutor.EMAIL_ATTACHMENT_ENABLED, false);
    sendAndReceiveEmail(tag.toString());
    MimeMessage retMeg = server.getReceivedMessages()[1];
    String msgBody = GreenMailUtil.getBody(retMeg);
    assertEquals(msgBody.indexOf("This is a test mail"), 0);
    assertNotSame(msgBody.indexOf(EmailActionExecutor.EMAIL_ATTACHMENT_ERROR_MSG), -1);
    // email content is not multi-part since not attaching files
    assertFalse(retMeg.getContent() instanceof Multipart);
    assertTrue(retMeg.getContentType().contains("text/plain"));
}

From source file:org.bonitasoft.connectors.email.test.EmailConnectorTest.java

@Test
public void sendEmailWithPlainMessage() throws Exception {
    final Map<String, Object> parameters = getBasicSettings();
    parameters.put("message", PLAINMESSAGE);
    parameters.put("from", ADDRESSMARK);
    executeConnector(parameters);/* ww w  . ja  v  a2  s  .  co m*/

    final List<WiserMessage> messages = server.getMessages();
    assertEquals(1, messages.size());
    final WiserMessage message = messages.get(0);
    assertEquals(ADDRESSMARK, message.getEnvelopeSender());
    assertEquals(ADDRESSJOHN, message.getEnvelopeReceiver());
    final MimeMessage mime = message.getMimeMessage();
    assertEquals(SUBJECT, mime.getSubject());
    assertTrue(mime.getContentType().contains(TEXT_PLAIN));
    assertEquals(PLAINMESSAGE, mime.getContent());
}

From source file:org.bonitasoft.connectors.email.test.EmailConnectorTest.java

@Test
public void sendEmailWithHtmlMessage() throws Exception {
    final Map<String, Object> parameters = getBasicSettings();
    parameters.put("html", true);
    parameters.put("message", HTMLMESSAGE);
    parameters.put("from", ADDRESSMARK);
    executeConnector(parameters);/*from   ww  w .  java  2 s.c om*/

    final List<WiserMessage> messages = server.getMessages();
    assertEquals(1, messages.size());
    final WiserMessage message = messages.get(0);
    assertEquals(ADDRESSMARK, message.getEnvelopeSender());
    assertEquals(ADDRESSJOHN, message.getEnvelopeReceiver());
    final MimeMessage mime = message.getMimeMessage();
    assertEquals(SUBJECT, mime.getSubject());
    assertTrue(mime.getContentType().contains(TEXT_HTML));
    assertEquals(HTMLMESSAGE, mime.getContent());
}

From source file:org.bonitasoft.connectors.email.test.EmailConnectorTest.java

@Test
public void sendEmailWithExtraHeaders() throws Exception {
    final List<List<String>> headers = new ArrayList<List<String>>();
    List<String> row1 = new ArrayList<String>();
    row1.add("X-Mailer");
    row1.add("Bonita Mailer");
    headers.add(row1);//from   w  w w  . ja  v  a  2 s.co m

    List<String> row2 = new ArrayList<String>();
    row2.add("Message-ID");
    row2.add("IWantToHackTheServer");
    headers.add(row2);

    List<String> row3 = new ArrayList<String>();
    row3.add("X-Priority");
    row3.add("2 (High)");
    headers.add(row3);

    List<String> row4 = new ArrayList<String>();
    row4.add("Content-Type");
    row4.add("video/mpeg");
    headers.add(row4);

    List<String> row5 = new ArrayList<String>();
    row5.add("WhatIWant");
    row5.add("anyValue");
    headers.add(row5);

    List<String> row6 = new ArrayList<String>();
    row6.add("From");
    row6.add("alice@bob.charly");
    headers.add(row6);

    List<String> row7 = new ArrayList<String>();
    row7.add(null);
    row7.add(null);
    headers.add(row7);

    final Map<String, Object> parameters = getBasicSettings();

    parameters.put("headers", headers);

    executeConnector(parameters);

    final List<WiserMessage> messages = server.getMessages();
    assertEquals(1, messages.size());
    final WiserMessage message = messages.get(0);
    assertEquals("alice@bob.charly", message.getEnvelopeSender());
    assertEquals(ADDRESSJOHN, message.getEnvelopeReceiver());
    final MimeMessage mime = message.getMimeMessage();
    assertEquals(SUBJECT, mime.getSubject());
    assertEquals(0, mime.getSize());
    assertEquals("Bonita Mailer", mime.getHeader("X-Mailer", ""));
    assertEquals("2 (High)", mime.getHeader("X-Priority", ""));
    assertEquals("anyValue", mime.getHeader("WhatIWant", ""));
    assertNotSame("alice@bob.charly", mime.getHeader("From"));
    assertFalse(mime.getContentType().contains("video/mpeg"));
    assertNotSame("IWantToHackTheServer", mime.getHeader("Message-ID"));
}