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:servlets.mailPDF_Bronze_Yougov.java

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

    try {/*from w  ww .  j  a va 2 s .  co  m*/
        System.out.println("Reached @ mailPDF_Bronze_Yougov.");

        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("Yougov 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("YougovTracker_" + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

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

}

From source file:servlets.mailPDF_Demo.java

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

    try {//  w  w w  . j  a v a  2s . co  m
        System.out.println("Reached @ mailPDF_Demo.");

        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("Yougov 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("HCL_DemoTracker_" + reportdate + ".pdf");
        part2.addBodyPart(messageBodyPart2);
        email.addPart(part2);

        email.send();

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

}

From source file:servlets.mailPDF_Gold_CitrixChina.java

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

    try {//  ww w.j  av a2 s  .com
        System.out.println("Reached @ mailPDF_Gold_CitrixChina.");

        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("pdfBase64 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(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_Gold_CitrixChina.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:servlets.mailPDF_Gold_LexisNexis.java

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

    try {//from w  w  w. j a v  a2  s  . co m
        System.out.println("Reached @ mailPDF_Gold_LexisNexis.");

        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("pdfBase64 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(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_Gold_LexisNexis.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:servlets.mail_ResetPassword.java

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

    try {//from   ww  w . java2  s  . c  om
        System.out.println("Reached @ mail_ResetPassword.");
        String emailid = request.getParameter("email");

        Random r = new Random();
        int Low = 1000;
        int High = 9999;
        int R = r.nextInt(High - Low) + Low;

        String ResetCode = "RC" + String.valueOf(R);

        Connection co = null;
        String OSflag = getServletContext().getInitParameter("OSflag");
        String host = null, driver = null, userName = null, password = null;
        switch (OSflag) {
        case "0": {
            host = getServletContext().getInitParameter("host");
            driver = getServletContext().getInitParameter("driver");
            userName = getServletContext().getInitParameter("userName");
            password = getServletContext().getInitParameter("password");
            break;
        }
        case "1": {
            host = "jdbc:mysql://" + System.getenv("OPENSHIFT_MYSQL_DB_HOST") + ":"
                    + System.getenv("OPENSHIFT_MYSQL_DB_PORT") + "/npreportingsuite";
            userName = System.getenv("OPENSHIFT_MYSQL_DB_USERNAME");
            password = System.getenv("OPENSHIFT_MYSQL_DB_PASSWORD");
            driver = getServletContext().getInitParameter("driver");
            break;
        }
        }

        Class.forName(driver);
        co = DriverManager.getConnection(host, userName, password);
        Statement st = co.createStatement();

        st.executeUpdate("UPDATE user_accounts SET passwordresetcode ='" + ResetCode + "' WHERE emailid = '"
                + emailid + "'");

        String emailMessage = "Hi!" + "<br>"
                + "Follow this <a href=\"https://npreportingsuite.com/NPReportDeck/resetPassword.jsp\">link</a> and enter the following Reset Code to reset your password."
                + "<br><br>" + "Reset Code : <b>" + ResetCode + "</b>" + "<br><br>" + "Warm Regards," + "<br>"
                + "NPReportingSuite Team" + "<br><br>";

        MultiPartEmail email = new MultiPartEmail();
        email.setSmtpPort(587);
        email.setDebug(false);
        email.setHostName("smtp.gmail.com");
        email.setAuthentication("reporting@groupnp.com", "D3sign2015");
        email.setTLS(true);

        email.addTo(emailid);

        email.setFrom("reporting@groupnp.com");
        email.setSubject("NPReportingSuite : Reset Password Request Follow-up");

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

        email.send();

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

}

From source file:ste.xtest.mail.BugFreeFileTransport.java

@Test
public void send_multipart_message() throws Exception {
    Session session = Session.getInstance(config);

    Message message = new MimeMessage(Session.getInstance(config));
    message.setFrom(new InternetAddress("from@domain.com"));
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("to@domain.com"));
    message.setSubject("the subject");
    MimeMultipart multipart = new MimeMultipart("related");

    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<H1>hello world</H1><img src=\"cid:image\">";
    messageBodyPart.setContent(htmlText, "text/html");
    multipart.addBodyPart(messageBodyPart);
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("src/test/resources/images/6096.png");

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");

    multipart.addBodyPart(messageBodyPart);
    message.setContent(multipart);// www.j  a  v a2s. c o m

    session.getTransport().sendMessage(message, message.getAllRecipients());

    then(FileUtils.readFileToString(new File(TMP.getRoot(), "message"))).contains("From: from@domain.com\r")
            .contains("To: to@domain.com\r").contains("Subject: the subject\r").contains("hello world")
            .contains("Content-ID: <image>");
}

From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java

public void writeResponse(Map<ByteArray, List<Versioned<byte[]>>> versionedResponses) throws Exception {
    // multiPartKeys is the outer multipart
    MimeMultipart multiPartKeys = new MimeMultipart();
    ByteArrayOutputStream keysOutputStream = new ByteArrayOutputStream();

    for (Entry<ByteArray, List<Versioned<byte[]>>> entry : versionedResponses.entrySet()) {
        ByteArray key = entry.getKey();/*from  www.j  a  v a 2s.  co m*/
        String contentLocationKey = "/" + this.storeName + "/" + new String(Base64.encodeBase64(key.get()));

        // Create the individual body part - for each key requested
        MimeBodyPart keyBody = new MimeBodyPart();
        try {
            // Add the right headers
            keyBody.addHeader(CONTENT_TYPE, "multipart/binary");
            keyBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
            keyBody.addHeader(CONTENT_LOCATION, contentLocationKey);
        } catch (MessagingException me) {
            logger.error("Exception while constructing key body headers", me);
            keysOutputStream.close();
            throw me;
        }
        // multiPartValues is the inner multipart
        MimeMultipart multiPartValues = new MimeMultipart();
        for (Versioned<byte[]> versionedValue : entry.getValue()) {

            byte[] responseValue = versionedValue.getValue();

            VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
            String serializedVC = CoordinatorUtils.getSerializedVectorClock(vectorClock);

            // Create the individual body part - for each versioned value of
            // a key
            MimeBodyPart valueBody = new MimeBodyPart();
            try {
                // Add the right headers
                valueBody.addHeader(CONTENT_TYPE, "application/octet-stream");
                valueBody.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
                valueBody.addHeader(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVC);
                valueBody.setContent(responseValue, "application/octet-stream");

                multiPartValues.addBodyPart(valueBody);
            } catch (MessagingException me) {
                logger.error("Exception while constructing value body part", me);
                keysOutputStream.close();
                throw me;
            }

        }
        try {
            // Add the inner multipart as the content of the outer body part
            keyBody.setContent(multiPartValues);
            multiPartKeys.addBodyPart(keyBody);
        } catch (MessagingException me) {
            logger.error("Exception while constructing key body part", me);
            keysOutputStream.close();
            throw me;
        }

    }
    try {
        multiPartKeys.writeTo(keysOutputStream);
    } catch (Exception e) {
        logger.error("Exception while writing mutipart to output stream", e);
        throw e;
    }

    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(keysOutputStream.toByteArray());

    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    // Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");

    // Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

    // Update the stats
    if (this.coordinatorPerfStats != null) {
        long durationInNs = System.nanoTime() - startTimestampInNs;
        this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs);
    }

    // Write the response to the Netty Channel
    this.getRequestMessageEvent.getChannel().write(response);

    keysOutputStream.close();
}

From source file:voldemort.coordinator.HttpGetAllRequestExecutor.java

public void writeResponseOld(Map<ByteArray, Versioned<byte[]>> responseVersioned) {

    // Multipart response
    MimeMultipart mp = new MimeMultipart();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    try {//from  w ww  .  j a v a 2 s  .c  o  m

        for (Entry<ByteArray, Versioned<byte[]>> entry : responseVersioned.entrySet()) {
            Versioned<byte[]> value = entry.getValue();
            ByteArray keyByteArray = entry.getKey();
            String base64Key = new String(Base64.encodeBase64(keyByteArray.get()));
            String contentLocationKey = "/" + this.storeName + "/" + base64Key;

            byte[] responseValue = value.getValue();

            VectorClock vc = (VectorClock) value.getVersion();
            VectorClockWrapper vcWrapper = new VectorClockWrapper(vc);
            ObjectMapper mapper = new ObjectMapper();
            String eTag = "";
            try {
                eTag = mapper.writeValueAsString(vcWrapper);
            } catch (JsonGenerationException e) {
                e.printStackTrace();
            } catch (JsonMappingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (logger.isDebugEnabled()) {
                logger.debug("ETAG : " + eTag);
            }

            // Create the individual body part
            MimeBodyPart body = new MimeBodyPart();
            body.addHeader(CONTENT_TYPE, "application/octet-stream");
            body.addHeader(CONTENT_LOCATION, contentLocationKey);
            body.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
            body.addHeader(CONTENT_LENGTH, "" + responseValue.length);
            body.addHeader(ETAG, eTag);
            body.setContent(responseValue, "application/octet-stream");
            mp.addBodyPart(body);
        }

        // At this point we have a complete multi-part response
        mp.writeTo(outputStream);

    } catch (MessagingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(outputStream.toByteArray());

    // 1. Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    // 2. Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");

    // 3. Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

    // Update the stats
    if (this.coordinatorPerfStats != null) {
        long durationInNs = System.nanoTime() - startTimestampInNs;
        this.coordinatorPerfStats.recordTime(Tracked.GET_ALL, durationInNs);
    }

    // Write the response to the Netty Channel
    this.getRequestMessageEvent.getChannel().write(response);
}

From source file:voldemort.coordinator.HttpGetRequestExecutor.java

public void writeResponse(List<Versioned<byte[]>> versionedValues) throws Exception {

    MimeMultipart multiPart = new MimeMultipart();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    for (Versioned<byte[]> versionedValue : versionedValues) {

        byte[] responseValue = versionedValue.getValue();

        VectorClock vectorClock = (VectorClock) versionedValue.getVersion();
        String serializedVectorClock = CoordinatorUtils.getSerializedVectorClock(vectorClock);

        // Create the individual body part for each versioned value of the
        // requested key
        MimeBodyPart body = new MimeBodyPart();
        try {//from www .j  a  v a  2  s .com
            // Add the right headers
            body.addHeader(CONTENT_TYPE, "application/octet-stream");
            body.addHeader(CONTENT_TRANSFER_ENCODING, "binary");
            body.addHeader(VoldemortHttpRequestHandler.X_VOLD_VECTOR_CLOCK, serializedVectorClock);
            body.setContent(responseValue, "application/octet-stream");
            body.addHeader(CONTENT_LENGTH, "" + responseValue.length);

            multiPart.addBodyPart(body);
        } catch (MessagingException me) {
            logger.error("Exception while constructing body part", me);
            outputStream.close();
            throw me;
        }
    }
    try {
        multiPart.writeTo(outputStream);
    } catch (Exception e) {
        logger.error("Exception while writing multipart to output stream", e);
        outputStream.close();
        throw e;
    }
    ChannelBuffer responseContent = ChannelBuffers.dynamicBuffer();
    responseContent.writeBytes(outputStream.toByteArray());

    // Create the Response object
    HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);

    // Set the right headers
    response.setHeader(CONTENT_TYPE, "multipart/binary");
    response.setHeader(CONTENT_TRANSFER_ENCODING, "binary");

    // Copy the data into the payload
    response.setContent(responseContent);
    response.setHeader(CONTENT_LENGTH, response.getContent().readableBytes());

    if (logger.isDebugEnabled()) {
        logger.debug("Response = " + response);
    }

    // Update the stats
    if (this.coordinatorPerfStats != null) {
        long durationInNs = System.nanoTime() - startTimestampInNs;
        this.coordinatorPerfStats.recordTime(Tracked.GET, durationInNs);
    }

    // Write the response to the Netty Channel
    this.getRequestMessageEvent.getChannel().write(response);
}