Example usage for javax.mail.internet MimeMultipart MimeMultipart

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

Introduction

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

Prototype

public MimeMultipart(DataSource ds) throws MessagingException 

Source Link

Document

Constructs a MimeMultipart object and its bodyparts from the given DataSource.

Usage

From source file:org.jresponder.message.MessageRefImpl.java

/**
 * Render a message in the context of a particular subscriber
 * and subscription.//  w  w  w . j  a va  2 s  .c  o  m
 */
@Override
public boolean populateMessage(MimeMessage aMimeMessage, SendConfig aSendConfig, Subscriber aSubscriber,
        Subscription aSubscription) {

    try {

        // prepare context
        Map<String, Object> myRenderContext = new HashMap<String, Object>();
        myRenderContext.put("subscriber", aSubscriber);
        myRenderContext.put("subscription", aSubscription);
        myRenderContext.put("config", aSendConfig);
        myRenderContext.put("message", this);

        // render the whole file
        String myRenderedFileContents = TextRenderUtil.getInstance().render(fileContents, myRenderContext);

        // now parse again with Jsoup
        Document myDocument = Jsoup.parse(myRenderedFileContents);

        String myHtmlBody = "";
        String myTextBody = "";

        // html body
        Elements myBodyElements = myDocument.select("#htmlbody");
        if (!myBodyElements.isEmpty()) {
            myHtmlBody = myBodyElements.html();
        }

        // text body
        Elements myJrTextBodyElements = myDocument.select("#textbody");
        if (!myJrTextBodyElements.isEmpty()) {
            myTextBody = TextUtil.getInstance().getWholeText(myJrTextBodyElements.first());
        }

        // now build the actual message
        MimeMessage myMimeMessage = aMimeMessage;
        // wrap it in a MimeMessageHelper - since some things are easier with that
        MimeMessageHelper myMimeMessageHelper = new MimeMessageHelper(myMimeMessage);

        // set headers

        // subject
        myMimeMessageHelper.setSubject(TextRenderUtil.getInstance()
                .render((String) propMap.get(MessageRefProp.JR_SUBJECT.toString()), myRenderContext));

        // TODO: implement DKIM, figure out subetha

        String mySenderEmailPattern = aSendConfig.getSenderEmailPattern();
        String mySenderEmail = TextRenderUtil.getInstance().render(mySenderEmailPattern, myRenderContext);
        myMimeMessage.setSender(new InternetAddress(mySenderEmail));

        myMimeMessageHelper.setTo(aSubscriber.getEmail());

        // from
        myMimeMessageHelper.setFrom(
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_EMAIL.toString()), myRenderContext),
                TextRenderUtil.getInstance()
                        .render((String) propMap.get(MessageRefProp.JR_FROM_NAME.toString()), myRenderContext));

        // see how to set body

        // if we have both text and html, then do multipart
        if (myTextBody.trim().length() > 0 && myHtmlBody.trim().length() > 0) {

            // create wrapper multipart/alternative part
            MimeMultipart ma = new MimeMultipart("alternative");
            myMimeMessage.setContent(ma);
            // create the plain text
            BodyPart plainText = new MimeBodyPart();
            plainText.setText(myTextBody);
            ma.addBodyPart(plainText);
            // create the html part
            BodyPart html = new MimeBodyPart();
            html.setContent(myHtmlBody, "text/html");
            ma.addBodyPart(html);
        }

        // if only HTML, then just use that
        else if (myHtmlBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myHtmlBody, true);
        }

        // if only text, then just use that
        else if (myTextBody.trim().length() > 0) {
            myMimeMessageHelper.setText(myTextBody, false);
        }

        // if neither text nor HTML, then the message is being skipped,
        // so we just return null
        else {
            return false;
        }

        return true;

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }

}

From source file:sk.lazyman.gizmo.web.app.PageEmail.java

private Message buildMail(Session session) throws MessagingException, IOException {
    String subject = createSubject();
    Message mimeMessage = createMimeMessage(session, subject);
    mimeMessage.setDisposition(MimeMessage.INLINE);
    Multipart mp = new MimeMultipart("alternative");

    MimeBodyPart textBp = new MimeBodyPart();
    textBp.setDisposition(MimeMessage.INLINE);
    textBp.setContent("Please use mail client with HTML support.", "text/plain; charset=utf-8");
    mp.addBodyPart(textBp);//ww w . ja v  a  2  s .  co m

    Multipart commentMultipart = null;
    EmailDto dto = model.getObject();
    if (StringUtils.isNotEmpty(dto.getBody())) {
        BodyPart bodyPart = new MimeBodyPart();
        bodyPart.setDisposition(MimeMessage.INLINE);
        DataHandler dataHandler = new DataHandler(
                new ByteArrayDataSource(dto.getBody(), "text/plain; charset=utf-8"));
        bodyPart.setDataHandler(dataHandler);

        commentMultipart = new MimeMultipart("mixed");
        commentMultipart.addBodyPart(bodyPart);
    }

    String html = createHtml();
    Multipart htmlMp = createHtmlPart(html);

    BodyPart htmlBp = new MimeBodyPart();
    htmlBp.setDisposition(BodyPart.INLINE);
    htmlBp.setContent(htmlMp);
    if (commentMultipart == null) {
        mp.addBodyPart(htmlBp);
    } else {
        commentMultipart.addBodyPart(htmlBp);
        BodyPart all = new MimeBodyPart();
        all.setDisposition(BodyPart.INLINE);
        all.setContent(commentMultipart);
        mp.addBodyPart(all);
    }
    mimeMessage.setContent(mp);

    return mimeMessage;
}

From source file:org.xwiki.mail.integration.JavaIntegrationTest.java

@Test
public void sendHTMLAndCalendarInvitationMail() throws Exception {
    // Step 1: Create a JavaMail Session
    Session session = Session.getInstance(this.configuration.getAllProperties());

    // Step 2: Create the Message to send
    MimeMessage message = new MimeMessage(session);
    message.setSubject("subject");
    message.setRecipient(RecipientType.TO, new InternetAddress("john@doe.com"));

    // Step 3: Add the Message Body
    Multipart multipart = new MimeMultipart("alternative");
    // Add an HTML body part
    multipart.addBodyPart(/*from ww w.j ava 2 s.  co  m*/
            this.htmlBodyPartFactory.create("<font size=\"\\\"2\\\"\">simple meeting invitation</font>",
                    Collections.<String, Object>emptyMap()));
    // Add the Calendar invitation body part
    String calendarContent = "BEGIN:VCALENDAR\r\n" + "METHOD:REQUEST\r\n" + "PRODID: Meeting\r\n"
            + "VERSION:2.0\r\n" + "BEGIN:VEVENT\r\n" + "DTSTAMP:20140616T164100\r\n"
            + "DTSTART:20140616T164100\r\n" + "DTEND:20140616T194100\r\n" + "SUMMARY:test request\r\n"
            + "UID:324\r\n"
            + "ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:MAILTO:john@doe.com\r\n"
            + "ORGANIZER:MAILTO:john@doe.com\r\n" + "LOCATION:on the net\r\n"
            + "DESCRIPTION:learn some stuff\r\n" + "SEQUENCE:0\r\n" + "PRIORITY:5\r\n" + "CLASS:PUBLIC\r\n"
            + "STATUS:CONFIRMED\r\n" + "TRANSP:OPAQUE\r\n" + "BEGIN:VALARM\r\n" + "ACTION:DISPLAY\r\n"
            + "DESCRIPTION:REMINDER\r\n" + "TRIGGER;RELATED=START:-PT00H15M00S\r\n" + "END:VALARM\r\n"
            + "END:VEVENT\r\n" + "END:VCALENDAR";
    Map<String, Object> parameters = new HashMap<>();
    parameters.put("mimetype", "text/calendar;method=CANCEL");
    parameters.put("headers", Collections.singletonMap("Content-Class", "urn:content-classes:calendarmessage"));
    multipart.addBodyPart(this.defaultBodyPartFactory.create(calendarContent, parameters));

    message.setContent(multipart);

    // Step 4: Send the mail and wait for it to be sent
    this.sender.sendAsynchronously(Arrays.asList(message), session, null);

    // Verify that the mail has been received (wait maximum 30 seconds).
    this.mail.waitForIncomingEmail(30000L, 1);
    MimeMessage[] messages = this.mail.getReceivedMessages();

    assertEquals("subject", messages[0].getHeader("Subject", null));
    assertEquals("john@doe.com", messages[0].getHeader("To", null));

    assertEquals(2, ((MimeMultipart) messages[0].getContent()).getCount());

    BodyPart htmlBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0);
    assertEquals("text/html; charset=UTF-8", htmlBodyPart.getHeader("Content-Type")[0]);
    assertEquals("<font size=\"\\\"2\\\"\">simple meeting invitation</font>", htmlBodyPart.getContent());

    BodyPart calendarBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(1);
    assertEquals("text/calendar;method=CANCEL", calendarBodyPart.getHeader("Content-Type")[0]);
    InputStream is = (InputStream) calendarBodyPart.getContent();
    assertEquals(calendarContent, IOUtils.toString(is));
}

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. jav  a 2 s .com*/
    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:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java

private void createChildNodeForPart(Session session, int index, BodyPart part, Content message)
        throws MessagingException, AccessDeniedException, StorageClientException, IOException {
    ContentManager contentManager = session.getContentManager();
    String childName = String.format("part%1$03d", index);
    String childPath = message.getPath() + "/" + childName;
    // multipart message
    if (part.getContentType().toLowerCase().startsWith("multipart/")) {
        contentManager.update(new Content(childPath, EMPTY_MAP));
        Content childNode = contentManager.get(childPath);
        writePartPropertiesToNode(part, childNode);
        contentManager.update(childNode);
        MimeMultipart multi = new MimeMultipart(
                new SMTPDataSource(part.getContentType(), part.getInputStream()));
        writeMultipartToNode(session, childNode, multi);
        return;/* w ww. jav a  2s  .com*/
    }

    // text
    if (!isTextType(part)) {
        writePartAsFile(session, part, childName, message);
        return;
    }

    // not multipart; not text
    contentManager.update(new Content(childPath, EMPTY_MAP));
    Content childNode = contentManager.get(childPath);
    writePartPropertiesToNode(part, childNode);
    contentManager.update(childNode);
    // childNode.setProperty(MessageConstants.PROP_SAKAI_BODY, part.getInputStream());
    contentManager.writeBody(childNode.getPath(), part.getInputStream());
}

From source file:com.adaptris.util.text.mime.MultiPartInput.java

private void initialise() throws MessagingException, IOException {
    multipart = new MimeMultipart(dataSource);
    for (int i = 0; i < multipart.getCount(); i++) {
        MimeBodyPart part = (MimeBodyPart) multipart.getBodyPart(i);
        PartHolder ph = wrap(part);//from   ww  w  .j a v a2 s  . c o  m
        if (bodyParts.contains(ph)) {
            logR.warn(ph.contentId + " already exists as a part");
        }
        bodyParts.add(ph);
    }
    bodyPartIterator = bodyParts.iterator();
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeMultipart????mulpart/alternative//from  ww w  . ja v  a 2 s  . c o  m
 *
 * @return MimeMultipartmulpart/alternative?
 */
private MimeMultipart createAlternativeMimeMultipart() {
    return new MimeMultipart("alternative");
}

From source file:org.agnitas.util.AgnUtils.java

/**
 * Sends an email in the correspondent type.
 *///from w  ww .j  a va  2 s  .com
public static boolean sendEmail(String from_adr, String to_adrList, String cc_adrList, String subject,
        String body_text, String body_html, int mailtype, String charset) {
    try {
        // create some properties and get the default Session
        Properties props = new Properties();
        props.put("system.mail.host", getSmtpMailRelayHostname());
        Session session = Session.getDefaultInstance(props, null);
        // session.setDebug(debug);

        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from_adr));
        msg.setSubject(subject, charset);
        msg.setSentDate(new Date());

        // Set to-recipient email addresses
        InternetAddress[] toAddresses = getEmailAddressesFromList(to_adrList);
        if (toAddresses != null && toAddresses.length > 0) {
            msg.setRecipients(Message.RecipientType.TO, toAddresses);
        }

        // Set cc-recipient email addresses
        InternetAddress[] ccAddresses = getEmailAddressesFromList(cc_adrList);
        if (ccAddresses != null && ccAddresses.length > 0) {
            msg.setRecipients(Message.RecipientType.CC, ccAddresses);
        }

        switch (mailtype) {
        case 0:
            msg.setText(body_text, charset);
            break;

        case 1:
            Multipart mp = new MimeMultipart("alternative");
            MimeBodyPart mbp = new MimeBodyPart();
            mbp.setText(body_text, charset);
            mp.addBodyPart(mbp);
            mbp = new MimeBodyPart();
            mbp.setContent(body_html, "text/html; charset=" + charset);
            mp.addBodyPart(mbp);
            msg.setContent(mp);
            break;
        }

        Transport.send(msg);
    } catch (Exception e) {
        logger.error("sendEmail: " + e);
        logger.error(AgnUtils.getStackTrace(e));
        return false;
    }
    return true;
}

From source file:com.szmslab.quickjavamail.send.MailSender.java

/**
 * MimeMultipart????mulpart/related/*  w  w  w . ja v  a  2  s  .  co  m*/
 *
 * @return MimeMultipartmulpart/related?
 */
private MimeMultipart createRelatedMimeMultipart() {
    return new MimeMultipart("related");
}

From source file:com.linkedin.r2.message.rest.QueryTunnelUtil.java

/**
 * Helper function to create multi-part MIME
 *
 * @param entity         the body of a request
 * @param entityContentType content type of the body
 * @param query          a query part of a request
 *
 * @return a ByteString that represents a multi-part encoded entity that contains both
 *///  w w w.  jav a  2s . c om
private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType,
        String query) throws MessagingException {
    MimeMultipart multi = new MimeMultipart(MIXED);

    // Create current entity with the associated type
    MimeBodyPart dataPart = new MimeBodyPart();

    ContentType contentType = new ContentType(entityContentType);
    if (MULTIPART.equals(contentType.getBaseType())) {
        MimeMultipart nested = new MimeMultipart(new DataSource() {
            @Override
            public InputStream getInputStream() throws IOException {
                return entity.asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return entityContentType;
            }

            @Override
            public String getName() {
                return null;
            }
        });
        dataPart.setContent(nested, contentType.getBaseType());

    } else {
        dataPart.setContent(entity.copyBytes(), contentType.getBaseType());
    }
    dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType);

    // Encode query params as form-urlencoded
    MimeBodyPart argPart = new MimeBodyPart();
    argPart.setContent(query, FORM_URL_ENCODED);
    argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);

    multi.addBodyPart(argPart);
    multi.addBodyPart(dataPart);
    return multi;
}