Example usage for javax.mail.internet MimeMultipart addBodyPart

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

Introduction

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

Prototype

@Override
public synchronized void addBodyPart(BodyPart part) throws MessagingException 

Source Link

Document

Adds a Part to the multipart.

Usage

From source file:org.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

@Override
public MimeBodyPart create(String content, Map<String, Object> parameters) throws MessagingException {
    MimeBodyPart resultBodyPart;//from w w w.j av a  2  s  .c o  m

    // Separate normal attachment from embedded image attachments
    List<Attachment> allAttachments = (List<Attachment>) parameters.get("attachments");
    Pair<List<Attachment>, List<Attachment>> attachmentPairs = separateAttachments(content, allAttachments);
    List<Attachment> embeddedImageAttachments = attachmentPairs.getLeft();
    List<Attachment> normalAttachments = attachmentPairs.getRight();

    // Step 1: Handle the HTML section of the mail.
    MimeBodyPart htmlBodyPart;
    if (!embeddedImageAttachments.isEmpty()) {
        htmlBodyPart = new MimeBodyPart();
        htmlBodyPart.setContent(createHTMLMultipart(content, embeddedImageAttachments));
    } else {
        // Create the HTML body part of the email
        htmlBodyPart = createHTMLBodyPart(content, false);
    }

    // Step 2: Handle the optional alternative text
    String alternativeText = (String) parameters.get("alternate");
    if (alternativeText != null) {
        resultBodyPart = createAlternativePart(htmlBodyPart,
                this.defaultPartFactory.create(alternativeText, Collections.<String, Object>emptyMap()));
    } else {
        // No alternative text, just add the HTML body part to the Multipart
        resultBodyPart = htmlBodyPart;
    }

    // Step 3 Add the normal attachments (if any). Any embedded images have already been handled in the HTML body
    // part. Note: If there are attachments we need to wrap our body part inside a "mixed" Multipart.
    if (!normalAttachments.isEmpty()) {
        MimeMultipart multipart = new MimeMultipart("mixed");
        multipart.addBodyPart(resultBodyPart);
        handleAttachments(multipart, normalAttachments);
        resultBodyPart = new MimeBodyPart();
        resultBodyPart.setContent(multipart);
    }

    // Handle headers passed as parameter
    addHeaders(resultBodyPart, parameters);

    return resultBodyPart;
}

From source file:org.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

private void handleAttachments(MimeMultipart multipart, List<Attachment> attachments)
        throws MessagingException {
    for (Attachment attachment : attachments) {
        multipart.addBodyPart(
                this.attachmentPartFactory.create(attachment, Collections.<String, Object>emptyMap()));
    }// w  w  w.  j a v  a  2s.c o m
}

From source file:org.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

/**
 * @return Multipart part of the email, define the HTML as a multipart/alternative
 *///from w  ww  .j  a  v a  2 s .  c o m
private MimeBodyPart createAlternativePart(MimeBodyPart htmlBodyPart, MimeBodyPart textBodyPart)
        throws MessagingException {
    MimeMultipart alternativeMultiPart = new MimeMultipart("alternative");

    // Note: it's important to have the text before the HTML, from low fidelity to high fidelity according to the
    // MIME specification. Otherwise some readers will display text even though there's HTML in your mail message.
    alternativeMultiPart.addBodyPart(textBodyPart);
    alternativeMultiPart.addBodyPart(htmlBodyPart);

    MimeBodyPart alternativePartWrapper = new MimeBodyPart();
    alternativePartWrapper.setContent(alternativeMultiPart);
    return alternativePartWrapper;
}

From source file:org.xwiki.mail.internal.factory.html.HTMLMimeBodyPartFactory.java

private MimeMultipart createHTMLMultipart(String content, List<Attachment> embeddedImages)
        throws MessagingException {
    MimeMultipart htmlMultipart = new MimeMultipart("related");
    htmlMultipart.addBodyPart(createHTMLBodyPart(content, true));
    handleAttachments(htmlMultipart, embeddedImages);
    return htmlMultipart;
}

From source file:pt.webdetails.cdv.notifications.EmailOutlet.java

private Multipart getMultipartBody(final Session session, final Alert alert)
        throws MessagingException, IOException {

    // if we have a mimeMessage, use it. Otherwise, build one with what we have
    // We can have both a messageHtml and messageText. Build according to it

    MimeMultipart parentMultipart = new MimeMultipart();
    MimeBodyPart htmlBodyPart = null, textBodyPart = null;

    final String content = getMessageBody(alert);

    textBodyPart = new MimeBodyPart();
    textBodyPart.setContent(content, "text/plain; charset=" + CharsetHelper.getEncoding());
    final MimeMultipart textMultipart = new MimeMultipart();
    textMultipart.addBodyPart(textBodyPart);

    parentMultipart = textMultipart;// w  w w  .ja  va  2 s.  co  m

    // We have both text and html? Encapsulate it in a multipart/alternative

    if (htmlBodyPart != null && textBodyPart != null) {

        final MimeMultipart alternative = new MimeMultipart("alternative");
        alternative.addBodyPart(textBodyPart);
        alternative.addBodyPart(htmlBodyPart);

        parentMultipart = alternative;

    }

    return parentMultipart;
}

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

public void marshal(ShsMessage shsMessage, OutputStream outputStream) throws IllegalMessageStructureException {
    log.trace("marshal(ShsMessage, OutputStream)");

    MimeMultipart multipart = new MimeMultipart();
    BodyPart bodyPart = new MimeBodyPart();

    try {/*from w w  w.j  av  a  2 s .  c o m*/

        ShsLabel label = shsMessage.getLabel();
        if (label == null) {
            throw new IllegalMessageStructureException("label not found in shs message");
        }

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("label/content not found in shs label");
        } else {
            // we will update this according to our data parts below.
            content.getDataOrCompound().clear();

            String contentId = content.getContentId();
            content.setContentId(contentId.substring(0, Math.min(contentId.length(), MAX_LENGTH_CONTENT_ID)));
        }

        List<DataPart> dataParts = shsMessage.getDataParts();

        if (dataParts.isEmpty()) {
            throw new IllegalMessageStructureException("dataparts not found in message");
        }

        for (DataPart dp : dataParts) {
            Data data = new Data();

            data.setDatapartType(dp.getDataPartType());
            data.setFilename(dp.getFileName());
            if (dp.getContentLength() != null && dp.getContentLength() > 0)
                data.setNoOfBytes("" + dp.getContentLength());
            content.getDataOrCompound().add(data);
        }

        bodyPart.setContent(shsLabelMarshaller.marshal(label), "text/xml; charset=ISO-8859-1");
        bodyPart.setHeader("Content-Transfer-Encoding", "binary");

        multipart.addBodyPart(bodyPart);

        for (DataPart dataPart : dataParts) {

            bodyPart = new MimeBodyPart();

            bodyPart.setDisposition(Part.ATTACHMENT);
            if (StringUtils.isNotBlank(dataPart.getFileName())) {
                bodyPart.setFileName(dataPart.getFileName());
            }

            bodyPart.setDataHandler(dataPart.getDataHandler());

            if (dataPart.getTransferEncoding() != null) {
                bodyPart.addHeader("Content-Transfer-Encoding", dataPart.getTransferEncoding().toLowerCase());
            }
            multipart.addBodyPart(bodyPart);
        }

        MimeMessage mimeMessage = new MimeMessage(session);
        mimeMessage.setSubject("SHS Message");
        mimeMessage.addHeader("Content-Transfer-Encoding", "binary");

        mimeMessage.setContent(multipart);
        mimeMessage.saveChanges();

        String ignoreList[] = { "Message-ID" };

        mimeMessage.writeTo(outputStream, ignoreList);
        outputStream.flush();

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

}

From source file:servlets.mailPDF.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from w  w  w .j  av  a 2 s . c  o m
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");
        String filename = request.getParameter("filename");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }
        if (filename.equals("LNIndia Tracker (Gold - Weekly)")) {

            email.setFrom("reporting@groupnp.com");
            email.setSubject(filename + " (" + reportdate + ")");

            MimeMultipart part1 = new MimeMultipart();
            BodyPart messageBodyPart1 = new MimeBodyPart();
            messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
            part1.addBodyPart(messageBodyPart1);
            email.addPart(part1);

            MimeMultipart part2 = new MimeMultipart();
            BodyPart messageBodyPart2 = new MimeBodyPart();
            messageBodyPart2
                    .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
            messageBodyPart2.removeHeader("Content-Transfer-Encoding");
            messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
            messageBodyPart2.setFileName(filename + " " + reportdate + ".pdf");
            part2.addBodyPart(messageBodyPart2);
            email.addPart(part2);

            email.send();

        } else if (filename.equals("LNIndia Tracker (Gold - Monthly)")) {

            email.setFrom("reporting@groupnp.com");
            email.setSubject(filename + " (" + reportdate + ")");

            MimeMultipart part1 = new MimeMultipart();
            BodyPart messageBodyPart1 = new MimeBodyPart();
            messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
            part1.addBodyPart(messageBodyPart1);
            email.addPart(part1);

            MimeMultipart part2 = new MimeMultipart();
            BodyPart messageBodyPart2 = new MimeBodyPart();
            messageBodyPart2
                    .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
            messageBodyPart2.removeHeader("Content-Transfer-Encoding");
            messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
            messageBodyPart2.setFileName(filename + " " + reportdate + ".pdf");
            part2.addBodyPart(messageBodyPart2);
            email.addPart(part2);

            email.send();

        }

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:servlets.mailPDF_Bronze.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//ww  w .  j a  va 2s . c  o  m
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }

        email.setFrom("reporting@groupnp.com");
        email.setSubject("LexisNexis Risk India Tracker (" + reportdate + ")");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        MimeMultipart part2 = new MimeMultipart();
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2
                .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
        messageBodyPart2.removeHeader("Content-Transfer-Encoding");
        messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
        messageBodyPart2.setFileName("LNIndiaTracker_" + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF_Bronze.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:servlets.mailPDF_Bronze_ACS.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {//from w w  w  . j a v  a  2s  . c om
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }

        email.setFrom("reporting@groupnp.com");
        email.setSubject("ACS Tracker (" + reportdate + ")");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        MimeMultipart part2 = new MimeMultipart();
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2
                .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
        messageBodyPart2.removeHeader("Content-Transfer-Encoding");
        messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
        messageBodyPart2.setFileName("ACSTracker_" + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF_Bronze_ACS.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:servlets.mailPDF_Bronze_Temenos.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from w  ww .j  a v  a  2  s  .  c  o  m*/
        System.out.println("Reached @ mailPDF_Bronze.");

        String pdfBase64 = request.getParameter("pdfBase64");
        String reportdate = request.getParameter("reportdate");
        String emailaddresses = request.getParameter("emailList");
        String emailMessage = request.getParameter("emailMessage");

        List<String> emailList = Arrays.asList(emailaddresses.split("\\s*,\\s*"));

        System.out.println("pdfBase54 is --------------\n" + pdfBase64 + "\n-----------------End");
        System.out.println(reportdate);
        System.out.println(emailaddresses);

        byte[] decodedBytes = decode(pdfBase64.substring(28));
        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        for (String emailAddress : emailList) {

            email.addTo(emailAddress);
        }

        email.setFrom("reporting@groupnp.com");
        email.setSubject("Temenos Tracker (" + reportdate + ")");

        MimeMultipart part1 = new MimeMultipart();
        BodyPart messageBodyPart1 = new MimeBodyPart();
        messageBodyPart1.setContent(emailMessage, "text/html; charset=utf-8");
        part1.addBodyPart(messageBodyPart1);
        email.addPart(part1);

        MimeMultipart part2 = new MimeMultipart();
        BodyPart messageBodyPart2 = new MimeBodyPart();
        messageBodyPart2
                .setDataHandler(new DataHandler(new ByteArrayDataSource(decodedBytes, "application/pdf")));
        messageBodyPart2.removeHeader("Content-Transfer-Encoding");
        messageBodyPart2.addHeader("Content-Transfer-Encoding", "base64");
        messageBodyPart2.setFileName("TemenosTracker_" + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

    } catch (EmailException | MessagingException ex) {
        Logger.getLogger(mailPDF_Bronze_Temenos.class.getName()).log(Level.SEVERE, null, ex);
    }

}