List of usage examples for javax.mail BodyPart getContent
public Object getContent() throws IOException, MessagingException;
From source file:org.obm.sync.server.mailer.EventChangeMailerTest.java
private InvitationParts checkInvitationStructure(MimeMessage mimeMessage) throws UnsupportedEncodingException, IOException, MessagingException { InvitationParts parts = new InvitationParts(); parts.rawMessage = getRawMessage(mimeMessage); assertThat(mimeMessage.getContentType()).startsWith("multipart/mixed"); assertThat(mimeMessage.getContent()).isInstanceOf(Multipart.class); Multipart mixed = (Multipart) mimeMessage.getContent(); assertThat(mixed.getCount()).isEqualTo(2); BodyPart firstPart = mixed.getBodyPart(0); assertThat(firstPart.getContentType()).startsWith("multipart/alternative"); assertThat(firstPart.getContent()).isInstanceOf(Multipart.class); Multipart alternative = (Multipart) firstPart.getContent(); assertThat(alternative.getCount()).isEqualTo(3); parts.plainText = alternative.getBodyPart(0); assertThat(parts.plainText.getContentType()).startsWith("text/plain; charset=UTF-8"); parts.htmlText = alternative.getBodyPart(1); assertThat(parts.htmlText.getContentType()).startsWith("text/html; charset=UTF-8"); parts.textCalendar = alternative.getBodyPart(2); parts.applicationIcs = mixed.getBodyPart(1); assertThat(parts.applicationIcs.getContentType()).isEqualTo("application/ics; name=meeting.ics"); return parts; }
From source file:org.openhim.mediator.normalization.XDSbMimeProcessorActor.java
private String getValue(BodyPart part) throws IOException, MessagingException, UnprocessableContentFound { Object value = part.getContent(); if (value instanceof String) { return (String) value; } else if (value instanceof InputStream) { return IOUtils.toString((InputStream) value); }//from w w w .java2 s. c om throw new UnprocessableContentFound(); }
From source file:org.opennms.javamail.JavaReadMailer.java
/** * Attempts to reteive the string portion of a message... tries to handle * multipart messages as well. This seems to be working so far with my tests * but could use some tweaking later as more types of mail servers are used * with this feature./*from w w w . j a v a 2 s . c o m*/ * * @param msg a {@link javax.mail.Message} object. * @return The text portion of an email with each line being an element of the list. * @throws javax.mail.MessagingException if any. * @throws java.io.IOException if any. */ public static List<String> getText(Message msg) throws MessagingException, IOException { Object content = null; String text = null; LOG.debug("getText: getting text of message from MimeType: text/*"); try { text = (String) msg.getContent(); } catch (ClassCastException cce) { content = msg.getContent(); if (content instanceof MimeMultipart) { LOG.debug("getText: content is MimeMultipart, checking for text from each part..."); for (int cnt = 0; cnt < ((MimeMultipart) content).getCount(); cnt++) { BodyPart bp = ((MimeMultipart) content).getBodyPart(cnt); if (bp.isMimeType("text/*")) { text = (String) bp.getContent(); LOG.debug("getText: found text MIME type: {}", text); break; } } LOG.debug("getText: did not find text within MimeMultipart message."); } } return string2Lines(text); }
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 ww w .j a v a2 s . 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:org.webguitoolkit.messagebox.mail.MailChannel.java
/** * Drag the content from the message into a String * //from w ww .j a va 2s . com * @param m * @return */ private String getContent(Message m) { try { Object content = m.getContent(); if (content instanceof String) { return (String) content; } else if (content instanceof Multipart) { Multipart multipart = (Multipart) content; int partCount = multipart.getCount(); StringBuffer result = new StringBuffer(); for (int j = 0; j < partCount; j++) { BodyPart bodyPart = multipart.getBodyPart(j); String mimeType = bodyPart.getContentType(); Object partContent = bodyPart.getContent(); if (partContent instanceof String) { result.append((String) partContent); } else if (partContent instanceof Multipart) { Multipart innerMultiPartContent = (Multipart) partContent; int innerPartCount = innerMultiPartContent.getCount(); result.append("*** It has " + innerPartCount + "further BodyParts in it ***"); } else if (partContent instanceof InputStream) { result.append(IOUtils.toString((InputStream) partContent)); } } // End of for return result.toString(); } else if (content instanceof InputStream) return IOUtils.toString((InputStream) content); } catch (Exception e) { return "ERROR reading mail content " + e.getMessage(); } return "ERROR reading mail content - unknown format"; }
From source file:org.xwiki.administration.test.ui.ResetPasswordIT.java
protected BodyPart getPart(Multipart messageContent, String mimeType) throws Exception { for (int i = 0; i < messageContent.getCount(); i++) { BodyPart part = messageContent.getBodyPart(i); if (part.isMimeType(mimeType)) { return part; }/* w w w .j a va2s . c o m*/ if (part.isMimeType("multipart/related") || part.isMimeType("multipart/alternative") || part.isMimeType("multipart/mixed")) { BodyPart out = getPart((Multipart) part.getContent(), mimeType); if (out != null) { return out; } } } return null; }
From source file:org.xwiki.mail.integration.JavaIntegrationTest.java
@Test public void sendTextMail() 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("mixed"); // Add text in the body multipart.addBodyPart(this.defaultBodyPartFactory.create("some text here", Collections.<String, Object>singletonMap("mimetype", "text/plain"))); message.setContent(multipart);/*from w w w. j a va2s. c o m*/ // We also test using some default BCC addresses from configuration in this test this.configuration.setBCCAddresses(Arrays.asList("bcc1@doe.com", "bcc2@doe.com")); // Ensure we do not reuse the same message identifier for multiple similar messages in this test MimeMessage message2 = new MimeMessage(message); message2.saveChanges(); MimeMessage message3 = new MimeMessage(message); message3.saveChanges(); // Step 4: Send the mail and wait for it to be sent // Send 3 mails (3 times the same mail) to verify we can send several emails at once. MailListener memoryMailListener = this.componentManager.getInstance(MailListener.class, "memory"); this.sender.sendAsynchronously(Arrays.asList(message, message2, message3), session, memoryMailListener); // Note: we don't test status reporting from the listener since this is already tested in the // ScriptingIntegrationTest test class. // Verify that the mails have been received (wait maximum 30 seconds). this.mail.waitForIncomingEmail(30000L, 3); MimeMessage[] messages = this.mail.getReceivedMessages(); // Note: we're receiving 9 messages since we sent 3 with 3 recipients (2 BCC and 1 to)! assertEquals(9, messages.length); // Assert the email parts that are the same for all mails assertEquals("subject", messages[0].getHeader("Subject", null)); assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount()); BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0); assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]); assertEquals("some text here", textBodyPart.getContent()); assertEquals("john@doe.com", messages[0].getHeader("To", null)); // Note: We cannot assert that the BCC worked since by definition BCC information are not visible in received // messages ;) But we checked that we received 9 emails above so that's good enough. }
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(// w w w .j a va 2 s .c o 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:org.xwiki.mail.integration.ScriptingIntegrationTest.java
@Test public void sendTextMail() throws Exception { ScriptMimeMessage message1 = this.scriptService.createMessage("john@doe.com", "subject"); message1.addPart("text/plain", "some text here"); ScriptMimeMessage message2 = this.scriptService.createMessage("john@doe.com", "subject"); message2.addPart("text/plain", "some text here"); ScriptMimeMessage message3 = this.scriptService.createMessage("john@doe.com", "subject"); message3.addPart("text/plain", "some text here"); // Send 3 mails (3 times the same mail) to verify we can send several emails at once. List<ScriptMimeMessage> messagesList = Arrays.asList(message1, message2, message3); ScriptMailResult result = this.scriptService.sendAsynchronously(messagesList, "memory"); // Verify that there are no errors assertNull(this.scriptService.getLastError()); // Wait for all mails to be sent result.getStatusResult().waitTillProcessed(30000L); assertTrue(result.getStatusResult().isProcessed()); // Verify that all mails have been sent properly assertFalse("There should not be any failed result!", result.getStatusResult().getByState(MailState.SEND_ERROR).hasNext()); assertFalse("There should not be any failed result!", result.getStatusResult().getByState(MailState.PREPARE_ERROR).hasNext()); assertFalse("There should not be any mails in the ready state!", result.getStatusResult().getByState(MailState.PREPARE_SUCCESS).hasNext()); // Verify that the mails have been received (wait maximum 30 seconds). this.mail.waitForIncomingEmail(30000L, 3); MimeMessage[] messages = this.mail.getReceivedMessages(); assertEquals(3, messages.length);// w w w. ja va 2s .c o m assertEquals("subject", messages[0].getHeader("Subject", null)); assertEquals("john@doe.com", messages[0].getHeader("To", null)); assertEquals(1, ((MimeMultipart) messages[0].getContent()).getCount()); BodyPart textBodyPart = ((MimeMultipart) messages[0].getContent()).getBodyPart(0); assertEquals("text/plain", textBodyPart.getHeader("Content-Type")[0]); assertEquals("some text here", textBodyPart.getContent()); }
From source file:org.xwiki.mail.integration.ScriptingIntegrationTest.java
@Test public void sendHTMLAndCalendarInvitationMail() throws Exception { ScriptMimeMessage message = this.scriptService.createMessage("john@doe.com", "subject"); message.addPart("text/html", "<font size=\"\\\"2\\\"\">simple meeting invitation</font>"); // @formatter:off 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"; // @formatter:on message.addPart("text/calendar;method=CANCEL", calendarContent, Collections.<String, Object>singletonMap( "headers", Collections.singletonMap("Content-Class", "urn:content-classes:calendarmessage"))); ScriptMailResult result = this.scriptService.send(Arrays.asList(message)); // Verify that there are no errors and that 1 mail was sent assertNull(this.scriptService.getLastError()); assertTrue(result.getStatusResult().isProcessed()); assertEquals(1, result.getStatusResult().getProcessedMailCount()); // Verify that all mails have been sent properly assertFalse("There should not be any failed result!", result.getStatusResult().getByState(MailState.SEND_ERROR).hasNext()); assertFalse("There should not be any failed result!", result.getStatusResult().getByState(MailState.PREPARE_ERROR).hasNext()); assertFalse("There should not be any mails in the ready state!", result.getStatusResult().getByState(MailState.PREPARE_SUCCESS).hasNext()); // Verify that the mail has been received (wait maximum 30 seconds). this.mail.waitForIncomingEmail(30000L, 1); MimeMessage[] messages = this.mail.getReceivedMessages(); assertEquals(1, messages.length);// w w w . j av a 2 s . c o m 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", 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)); }