Example usage for javax.mail.internet MimeMultipart getBodyPart

List of usage examples for javax.mail.internet MimeMultipart getBodyPart

Introduction

In this page you can find the example usage for javax.mail.internet MimeMultipart getBodyPart.

Prototype

public synchronized BodyPart getBodyPart(String CID) throws MessagingException 

Source Link

Document

Get the MimeBodyPart referred to by the given ContentID (CID).

Usage

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

@Test
public void serviceShouldSendMultipartMailContainingDSNPart() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).build();
    dsnBounce.init(mailetConfig);//from  w ww . jav  a  2s  .co  m

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

    dsnBounce.service(mail);

    String expectedContent = "Reporting-MTA: dns; myhost\n" + "Received-From-MTA: dns; 111.222.333.444\n" + "\n"
            + "Final-Recipient: rfc822; recipient@domain.com\n" + "Action: failed\n"
            + "Status: Delivery error\n" + "Diagnostic-Code: X-James; Delivery error\n"
            + "Last-Attempt-Date: Thu, 8 Sep 2016 14:25:52 XXXXX (UTC)\n";

    List<SentMail> sentMails = fakeMailContext.getSentMails();
    assertThat(sentMails).hasSize(1);
    SentMail sentMail = sentMails.get(0);
    MimeMessage sentMessage = sentMail.getMsg();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();
    SharedByteArrayInputStream actualContent = (SharedByteArrayInputStream) content.getBodyPart(1).getContent();
    assertThat(IOUtils.toString(actualContent, StandardCharsets.UTF_8)).isEqualTo(expectedContent);
}

From source file:org.viafirma.util.SendMailUtil.java

/**
 * Crea un nuevo mail firmado. Adjuntandole el pkcs7.
 * /* www  .j a v  a2s .c o m*/
 * @param key
 *            Clave privada con la que se realiza el proceso de firma.
 * @param cert
 *            Certificado utilizado.
 * @param certsAndCRLs
 *            Camino de confianza.
 * @param dataPart
 *            Cuerpo del email.
 * @return Mail firmado.
 * @throws CertStoreException
 * @throws SMIMEException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CertificateParsingException
 */
private MimeMultipart createMultipartWithSignature(PrivateKey key, X509Certificate cert, CertStore certsAndCRLs,
        MimeBodyPart dataPart) throws CertStoreException, SMIMEException, NoSuchAlgorithmException,
        NoSuchProviderException, CertificateParsingException

{
    // Aadimos los tipos soportados
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();

    caps.addCapability(SMIMECapability.aES256_CBC);
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(SMIMEUtil.createIssuerAndSerialNumberFor(cert)));

    // Creamos el generador
    SMIMESignedGenerator generador = new SMIMESignedGenerator();

    // Establecemos la clave privada y el mtodo de firma
    generador.addSigner(key, cert, SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(signedAttrs), null);

    // Aadimos el camino de confianza adjuntado en el mail.
    generador.addCertificatesAndCRLs(certsAndCRLs);

    // Generamos el mail firmado.
    MimeMultipart mensajeFirmado = generador.generate(dataPart, BouncyCastleProvider.PROVIDER_NAME);

    // multipart/mixed; boundary="----=_Part_2_29796765.1208556677256"
    try {

        String contentType = mensajeFirmado.getBodyPart(0).getContentType();
        contentType = contentType.replaceAll("multipart/mixed", "multipart/alternative");
        mensajeFirmado.getBodyPart(0).setHeader("Content-Type", contentType);
        // contentType =mensajeFirmado.getContentType();
        // contentType=contentType.replaceAll("application/pkcs7-signature",
        // "application/x-pkcs7-signature");
        // mensajeFirmado.getContentType();
    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return mensajeFirmado;
}

From source file:com.xebialabs.xlt.ci.server.XLTestServerImplTest.java

private void verifyUploadRequest(final RecordedRequest request) throws IOException, MessagingException {
    assertEquals(request.getRequestLine(), "POST /api/internal/import/testspecid HTTP/1.1");
    assertEquals(request.getHeader("accept"), "application/json; charset=utf-8");
    assertEquals(request.getHeader("authorization"), "Basic YWRtaW46YWRtaW4=");
    assertThat(request.getHeader("Content-Length"), is(nullValue()));
    assertThat(request.getHeader("Transfer-Encoding"), is("chunked"));
    assertThat(request.getChunkSizes().get(0), greaterThan(0));
    assertThat(request.getChunkSizes().size(), greaterThan(0));

    assertTrue(request.getBodySize() > 0);

    ByteArrayDataSource bads = new ByteArrayDataSource(request.getBody().inputStream(), "multipart/mixed");
    MimeMultipart mp = new MimeMultipart(bads);
    assertTrue(request.getBodySize() > 0);

    assertEquals(mp.getCount(), 2);// w w w. j  ava 2s  . c o  m
    assertEquals(mp.getContentType(), "multipart/mixed");

    // TODO could do additional checks on metadata content
    BodyPart bodyPart1 = mp.getBodyPart(0);
    assertEquals(bodyPart1.getContentType(), "application/json; charset=utf-8");

    BodyPart bodyPart2 = mp.getBodyPart(1);
    assertEquals(bodyPart2.getContentType(), "application/zip");
}

From source file:org.apache.james.transport.mailets.managesieve.ManageSieveMailetTestCase.java

private void ensureResponseContains(String subject, String... contents) throws MessagingException, IOException {
    MimeMessage result = verifyHeaders(subject);
    MimeMultipart multipart = (MimeMultipart) result.getContent();
    assertThat(((String) multipart.getBodyPart(0).getContent()).split("\r\n")).containsOnly(contents);
}

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

@Test
public void serviceShouldAttachTheOriginalMailWhenAttachmentIsEqualToAll() throws Exception {
    FakeMailetConfig mailetConfig = FakeMailetConfig.builder().mailetName(MAILET_NAME)
            .mailetContext(fakeMailContext).setProperty("attachment", "all").build();
    dsnBounce.init(mailetConfig);//  w  w  w  .  ja va 2  s  . co m

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

    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();
    MimeMultipart content = (MimeMultipart) sentMessage.getContent();

    assertThat(sentMail.getMsg().getContentType()).startsWith("multipart/report;");
    assertThat(MimeMessageUtil.asString((MimeMessage) content.getBodyPart(2).getContent()))
            .isEqualTo(MimeMessageUtil.asString(mimeMessageCopy));
}

From source file:org.apache.james.smtpserver.fastfail.URIRBLHandler.java

/**
 * Recursively scans all MimeParts of an email for domain strings. Domain
 * strings that are found are added to the supplied HashSet.
 * //from w w  w.  ja va2s.  c om
 * @param part
 *            MimePart to scan
 * @param session
 *            not null
 * @return domains The HashSet that contains the domains which were
 *         extracted
 */
private HashSet<String> scanMailForDomains(MimePart part, SMTPSession session)
        throws MessagingException, IOException {
    HashSet<String> domains = new HashSet<String>();
    session.getLogger().debug("mime type is: \"" + part.getContentType() + "\"");

    if (part.isMimeType("text/plain") || part.isMimeType("text/html")) {
        session.getLogger().debug("scanning: \"" + part.getContent().toString() + "\"");
        HashSet<String> newDom = URIScanner.scanContentForDomains(domains, part.getContent().toString());

        // Check if new domains are found and add the domains
        if (newDom != null && newDom.size() > 0) {
            domains.addAll(newDom);
        }
    } else if (part.isMimeType("multipart/*")) {
        MimeMultipart multipart = (MimeMultipart) part.getContent();
        int count = multipart.getCount();
        session.getLogger().debug("multipart count is: " + count);

        for (int index = 0; index < count; index++) {
            session.getLogger().debug("recursing index: " + index);
            MimeBodyPart mimeBodyPart = (MimeBodyPart) multipart.getBodyPart(index);
            HashSet<String> newDomains = scanMailForDomains(mimeBodyPart, session);

            // Check if new domains are found and add the domains
            if (newDomains != null && newDomains.size() > 0) {
                domains.addAll(newDomains);
            }
        }
    }
    return domains;
}

From source file:voldemort.coordinator.CoordinatorRestAPITest.java

private TestVersionedValue doGet(String key, Map<String, Object> options) {
    HttpURLConnection conn = null;
    String response = null;/*from ww w  .ja v a 2 s.c  om*/
    TestVersionedValue responseObj = null;
    int expectedResponseCode = 200;
    try {

        // Create the right URL and Http connection
        String base64Key = new String(Base64.encodeBase64(key.getBytes()));
        URL url = new URL(this.coordinatorURL + "/" + STORE_NAME + "/" + base64Key);
        conn = (HttpURLConnection) url.openConnection();

        // Set the right headers
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS, "1000");
        conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS,
                Long.toString(System.currentTimeMillis()));

        // options
        if (options != null) {
            if (options.get("timeout") != null && options.get("timeout") instanceof String) {
                conn.setRequestProperty(RestMessageHeaders.X_VOLD_REQUEST_TIMEOUT_MS,
                        (String) options.get("timeout"));
            }
            if (options.get("responseCode") != null && options.get("responseCode") instanceof Integer) {
                expectedResponseCode = (Integer) options.get("responseCode");
            }
        }

        // Check for the right response code
        if (conn.getResponseCode() != expectedResponseCode) {
            System.err.println("Illegal response during GET : " + conn.getResponseMessage());
            fail("Incorrect response received for a HTTP GET request :" + conn.getResponseCode());
        }

        if (conn.getResponseCode() == 404 || conn.getResponseCode() == 408) {
            return null;
        }

        // Buffer the result into a string
        ByteArrayDataSource ds = new ByteArrayDataSource(conn.getInputStream(), "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        assertEquals("The number of body parts expected is not 1", 1, mp.getCount());

        MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(0);
        VectorClock vc = RestUtils
                .deserializeVectorClock(part.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0]);
        response = (String) part.getContent();

        responseObj = new TestVersionedValue(response, vc);

    } catch (Exception e) {
        e.printStackTrace();
        fail("Error in sending the REST request");
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return responseObj;
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public ShsMessage unmarshal(InputStream stream) throws IllegalMessageStructureException {
    log.trace("unmarshal(InputStream)");

    try {/*  w  ww .  j a  v  a2  s . c  o m*/
        stream = SharedDeferredStream.toSharedInputStream(stream);
        MimeMessage mimeMessage = new MimeMessage(session, stream);
        Object msgContent = mimeMessage.getContent();

        if (!(msgContent instanceof MimeMultipart)) {
            throw new IllegalMessageStructureException(
                    "Expected a multipart mime message, got " + msgContent.getClass());
        }

        MimeMultipart multipart = (MimeMultipart) msgContent;

        if (multipart.getCount() < 2) {
            throw new IllegalMessageStructureException("SHS message must contain at least two mime bodyparts");
        }

        ShsMessage shsMessage = new ShsMessage();

        BodyPart labelPart = multipart.getBodyPart(0);
        if (!labelPart.isMimeType("text/xml") && !labelPart.isMimeType("text/plain")) {
            throw new IllegalMessageStructureException(
                    "First bodypart is not text/xml nor text/plain but was " + labelPart.getContentType());
        }

        ShsLabel label = shsLabelMarshaller.unmarshal((String) labelPart.getContent());

        shsMessage.setLabel(label);

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("Label contains no content elements");
        }

        // this reads only as many mime body parts as there are content/data elements in the label
        int i = 1;
        for (Object o : content.getDataOrCompound()) {
            MimeBodyPart dp = (MimeBodyPart) multipart.getBodyPart(i);
            DataHandler dh = dp.getDataHandler();
            DataPart dataPart = new DataPart();
            dataPart.setDataHandler(new DataHandler(
                    new InputStreamDataSource(dh.getDataSource().getInputStream(), dh.getContentType())));

            dataPart.setContentType(dh.getContentType());

            String encoding = dp.getEncoding();
            if (encoding != null) {
                dataPart.setTransferEncoding(encoding);
            }

            dataPart.setFileName(dp.getFileName());

            if (o instanceof Data) {
                Data data = (Data) o;
                dataPart.setDataPartType(data.getDatapartType());
            } else if (o instanceof Compound) {
                continue;
            }
            shsMessage.addDataPart(dataPart);
            i++;
        }

        return shsMessage;

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }

        throw new IllegalMessageStructureException(e);
    }
}

From source file:org.pentaho.platform.util.Emailer.java

public boolean send() {
    String from = props.getProperty("mail.from.default");
    String fromName = props.getProperty("mail.from.name");
    String to = props.getProperty("to");
    String cc = props.getProperty("cc");
    String bcc = props.getProperty("bcc");
    boolean authenticate = "true".equalsIgnoreCase(props.getProperty("mail.smtp.auth"));
    String subject = props.getProperty("subject");
    String body = props.getProperty("body");

    logger.info("Going to send an email to " + to + " from " + from + " with the subject '" + subject
            + "' and the body " + body);

    try {//from   w  w  w. j ava  2s . co m
        // Get a Session object
        Session session;

        if (authenticate) {
            session = Session.getInstance(props, authenticator);
        } else {
            session = Session.getInstance(props);
        }

        // if debugging is not set in the email config file, then default to false
        if (!props.containsKey("mail.debug")) { //$NON-NLS-1$
            session.setDebug(false);
        }

        final MimeMessage msg;

        if (EMBEDDED_HTML.equals(attachmentMimeType)) {

            //Message is ready
            msg = new MimeMessage(session, attachment);

            if (body != null) {
                //We need to add message to the top of the email body
                final MimeMultipart oldMultipart = (MimeMultipart) msg.getContent();
                final MimeMultipart newMultipart = new MimeMultipart("related");

                for (int i = 0; i < oldMultipart.getCount(); i++) {
                    BodyPart bodyPart = oldMultipart.getBodyPart(i);

                    final Object content = bodyPart.getContent();
                    //Main HTML body
                    if (content instanceof String) {
                        final String newContent = body + "<br/><br/>" + content;
                        final MimeBodyPart part = new MimeBodyPart();
                        part.setText(newContent, "UTF-8", "html");
                        newMultipart.addBodyPart(part);
                    } else {
                        //CID attachments
                        newMultipart.addBodyPart(bodyPart);
                    }
                }

                msg.setContent(newMultipart);
            }
        } else {

            // construct the message
            msg = new MimeMessage(session);
            Multipart multipart = new MimeMultipart();

            if (attachment == null) {
                logger.error("Email.ERROR_0015_ATTACHMENT_FAILED"); //$NON-NLS-1$
                return false;
            }

            ByteArrayDataSource dataSource = new ByteArrayDataSource(attachment, attachmentMimeType);

            if (body != null) {
                MimeBodyPart bodyMessagePart = new MimeBodyPart();
                bodyMessagePart.setText(body, LocaleHelper.getSystemEncoding());
                multipart.addBodyPart(bodyMessagePart);
            }

            // attach the file to the message
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            attachmentBodyPart.setDataHandler(new DataHandler(dataSource));
            attachmentBodyPart.setFileName(MimeUtility.encodeText(attachmentName, "UTF-8", null));
            multipart.addBodyPart(attachmentBodyPart);

            // add the Multipart to the message
            msg.setContent(multipart);
        }

        if (from != null) {
            msg.setFrom(new InternetAddress(from, fromName));
        } else {
            // There should be no way to get here
            logger.error("Email.ERROR_0012_FROM_NOT_DEFINED"); //$NON-NLS-1$
        }

        if ((to != null) && (to.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
        }
        if ((cc != null) && (cc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc, false));
        }
        if ((bcc != null) && (bcc.trim().length() > 0)) {
            msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc, false));
        }

        if (subject != null) {
            msg.setSubject(subject, LocaleHelper.getSystemEncoding());
        }

        msg.setHeader("X-Mailer", Emailer.MAILER); //$NON-NLS-1$
        msg.setSentDate(new Date());

        Transport.send(msg);

        return true;
    } catch (SendFailedException e) {
        logger.error("Email.ERROR_0011_SEND_FAILED -" + to, e); //$NON-NLS-1$
    } catch (AuthenticationFailedException e) {
        logger.error("Email.ERROR_0014_AUTHENTICATION_FAILED - " + to, e); //$NON-NLS-1$
    } catch (Throwable e) {
        logger.error("Email.ERROR_0011_SEND_FAILED - " + to, e); //$NON-NLS-1$
    }
    return false;
}

From source file:com.haulmont.cuba.core.app.EmailerTest.java

private MimeBodyPart getFirstAttachment(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();
    return (MimeBodyPart) mimeMultipart.getBodyPart(1);
}