javax.mail.internet.MimeBodyPart Java Examples

The following examples show how to use javax.mail.internet.MimeBodyPart. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Add an attachment with the specified content - the attachment will have a
 * content type text\plain and the specified character set
 *
 * @param content
 *            the content of the attachment
 * @param charset
 *            the character set
 * @param fileName
 *            the file name for the content-disposition header
 * @throws PackageException
 *             on error
 */
@PublicAtsApi
public void addAttachment(
                           String content,
                           String charset,
                           String fileName ) throws PackageException {

    try {
        // add attachment to multipart content
        MimeBodyPart attPart = new MimeBodyPart();
        attPart.setText(content, charset, PART_TYPE_TEXT_PLAIN);
        attPart.setDisposition(MimeBodyPart.ATTACHMENT);
        attPart.setFileName(fileName);

        addPart(attPart, PART_POSITION_LAST);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
Example #2
Source File: MailServiceIntTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void testSendMultipartEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
 
Example #3
Source File: BasicEmailService.java    From sakai with Educational Community License v2.0 6 votes vote down vote up
/**
 * Attaches a file as a body part to the multipart message
 *
 * @param attachment
 * @throws MessagingException
 */
private MimeBodyPart createAttachmentPart(Attachment attachment) throws MessagingException
{
	DataSource source = attachment.getDataSource();
	MimeBodyPart attachPart = new MimeBodyPart();

	attachPart.setDataHandler(new DataHandler(source));
	attachPart.setFileName(attachment.getFilename());

	if (attachment.getContentTypeHeader() != null) {
		attachPart.setHeader("Content-Type", attachment.getContentTypeHeader());
	}

	if (attachment.getContentDispositionHeader() != null) {
		attachPart.setHeader("Content-Disposition", attachment.getContentDispositionHeader());
	}

	return attachPart;
}
 
Example #4
Source File: MimeMessageHelper.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Set the given plain text and HTML text as alternatives, offering
 * both options to the email client. Requires multipart mode.
 * <p><b>NOTE:</b> Invoke {@link #addInline} <i>after</i> {@code setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param plainText the plain text for the message
 * @param htmlText the HTML text for the message
 * @throws MessagingException in case of errors
 */
public void setText(String plainText, String htmlText) throws MessagingException {
	Assert.notNull(plainText, "Plain text must not be null");
	Assert.notNull(htmlText, "HTML text must not be null");

	MimeMultipart messageBody = new MimeMultipart(MULTIPART_SUBTYPE_ALTERNATIVE);
	getMainPart().setContent(messageBody, CONTENT_TYPE_ALTERNATIVE);

	// Create the plain text part of the message.
	MimeBodyPart plainTextPart = new MimeBodyPart();
	setPlainTextToMimePart(plainTextPart, plainText);
	messageBody.addBodyPart(plainTextPart);

	// Create the HTML text part of the message.
	MimeBodyPart htmlTextPart = new MimeBodyPart();
	setHtmlTextToMimePart(htmlTextPart, htmlText);
	messageBody.addBodyPart(htmlTextPart);
}
 
Example #5
Source File: Mailer.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 6 votes vote down vote up
private static Multipart getMessagePart() throws MessagingException, IOException {
    Multipart multipart = new MimeMultipart();
    BodyPart messageBodyPart = new MimeBodyPart();
    messageBodyPart.setText(getVal("msg.Body"));
    multipart.addBodyPart(messageBodyPart);
    if (getBoolVal("attach.reports")) {
        LOG.info("Attaching Reports as zip");
        multipart.addBodyPart(getReportsBodyPart());
    } else {
        if (getBoolVal("attach.standaloneHtml")) {
            multipart.addBodyPart(getStandaloneHtmlBodyPart());
        }
        if (getBoolVal("attach.console")) {
            multipart.addBodyPart(getConsoleBodyPart());
        }
        if (getBoolVal("attach.screenshots")) {
            multipart.addBodyPart(getScreenShotsBodyPart());
        }
    }
    messageBodyPart.setContent(getVal("msg.Body")
            .concat("\n\n\n")
            .concat(MailComponent.getHTMLBody()), "text/html");
    return multipart;
}
 
Example #6
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public MimeBodyPart compress(Message msg, MimeBodyPart mbp, String compressionType, String contentTxfrEncoding) throws SMIMEException, OpenAS2Exception {
    OutputCompressor compressor = null;
    if (compressionType != null) {
        if (compressionType.equalsIgnoreCase(ICryptoHelper.COMPRESSION_ZLIB)) {
            compressor = new ZlibCompressor();
        } else {
            throw new OpenAS2Exception("Unsupported compression type: " + compressionType);
        }
    }
    SMIMECompressedGenerator sCompGen = new SMIMECompressedGenerator();
    sCompGen.setContentTransferEncoding(getEncoding(contentTxfrEncoding));
    MimeBodyPart smime = sCompGen.generate(mbp, compressor);
    if (logger.isTraceEnabled()) {
        try {
            logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Type:" + smime.getContentType());
            logger.trace("Compressed MIME msg AFTER COMPRESSION Content-Disposition:" + smime.getDisposition());
        } catch (MessagingException e) {
        }
    }
    return smime;
}
 
Example #7
Source File: MailServiceIntTest.java    From cubeai with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMultipartHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example #8
Source File: ParseBlobUploadFilter.java    From appengine-java-vm-runtime with Apache License 2.0 6 votes vote down vote up
private Map<String, String> getInfoFromBody(String bodyContent, String key)
    throws MessagingException {
  MimeBodyPart part = new MimeBodyPart(new ByteArrayInputStream(bodyContent.getBytes()));
  Map<String, String> info = new HashMap<String, String>(6);
  info.put("key", key);
  info.put("content-type", part.getContentType());
  info.put("creation-date", part.getHeader(UPLOAD_CREATION_HEADER)[0]);
  info.put("filename", part.getFileName());
  info.put("size", part.getHeader(CONTENT_LENGTH_HEADER)[0]); // part.getSize() returns 0
  info.put("md5-hash", part.getContentMD5());

  String[] headers = part.getHeader(CLOUD_STORAGE_OBJECT_HEADER);
  if (headers != null && headers.length == 1) {
    info.put("gs-name", headers[0]);
  }

  return info;
}
 
Example #9
Source File: MailServiceIntTest.java    From 21-points with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMultipartHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example #10
Source File: MailServiceIntTest.java    From Spring-5.0-Projects with MIT License 6 votes vote down vote up
@Test
public void testSendMultipartHtmlEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, true);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/html;charset=UTF-8");
}
 
Example #11
Source File: DSNBounce.java    From james-project with Apache License 2.0 6 votes vote down vote up
private MimeBodyPart createAttachedOriginal(Mail originalMail, TypeCode attachmentType) throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();
    MimeMessage originalMessage = originalMail.getMessage();

    if (attachmentType.equals(TypeCode.HEADS)) {
        part.setContent(new MimeMessageUtils(originalMessage).getMessageHeaders(), "text/plain");
        part.setHeader("Content-Type", "text/rfc822-headers");
    } else {
        part.setContent(originalMessage, "message/rfc822");
    }

    if ((originalMessage.getSubject() != null) && (originalMessage.getSubject().trim().length() > 0)) {
        part.setFileName(originalMessage.getSubject().trim());
    } else {
        part.setFileName("No Subject");
    }
    part.setDisposition("Attachment");
    return part;
}
 
Example #12
Source File: MailServiceIntTest.java    From jhipster-microservices-example with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMultipartEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject","testContent", true, false);
    verify(javaMailSender).send((MimeMessage) messageCaptor.capture());
    MimeMessage message = (MimeMessage) messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart)((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
 
Example #13
Source File: AS2SenderModule.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected void calcAndStoreMic(Message msg, MimeBodyPart mbp, boolean includeHeaders) throws Exception {
    // Calculate and get the original mic
    // includeHeaders = (msg.getHistory().getItems().size() > 1);

    String mdnOptions = msg.getPartnership().getAttributeOrProperty(Partnership.PA_AS2_MDN_OPTIONS, null);
    if (mdnOptions == null || mdnOptions.length() < 1) {
        throw new OpenAS2Exception("Partner attribute " + Partnership.PA_AS2_MDN_OPTIONS + "is required but can be set to \"none\"");
    }
    if ("none".equalsIgnoreCase(mdnOptions)) {
        return;
    }
    DispositionOptions dispOptions = new DispositionOptions(mdnOptions);
    msg.setCalculatedMIC(AS2Util.getCryptoHelper().calculateMIC(mbp, dispOptions.getMicalg(), includeHeaders, msg.getPartnership().isPreventCanonicalization()));
    if (logger.isTraceEnabled()) {
        // Generate some alternative MIC's to see if the partner is somehow using a
        // different default
        String tmic = AS2Util.getCryptoHelper().calculateMIC(mbp, dispOptions.getMicalg(), includeHeaders, !msg.getPartnership().isPreventCanonicalization());
        logger.trace("MIC outbound with forced reversed prevent canocalization: " + tmic + msg.getLogMsgID());
        tmic = AS2Util.getCryptoHelper().calculateMIC(msg.getData(), dispOptions.getMicalg(), false, msg.getPartnership().isPreventCanonicalization());
        logger.trace("MIC outbound with forced exclude headers flag: " + tmic + msg.getLogMsgID());

    }
}
 
Example #14
Source File: MailServiceIntTest.java    From ehcache3-samples with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMultipartEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("test@localhost");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
 
Example #15
Source File: MailServiceIT.java    From jhipster-online with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendMultipartEmail() throws Exception {
    mailService.sendEmail("[email protected]", "testSubject", "testContent", true, false);
    verify(javaMailSender).send(messageCaptor.capture());
    MimeMessage message = messageCaptor.getValue();
    MimeMultipart mp = (MimeMultipart) message.getContent();
    MimeBodyPart part = (MimeBodyPart) ((MimeMultipart) mp.getBodyPart(0).getContent()).getBodyPart(0);
    ByteArrayOutputStream aos = new ByteArrayOutputStream();
    part.writeTo(aos);
    assertThat(message.getSubject()).isEqualTo("testSubject");
    assertThat(message.getAllRecipients()[0].toString()).isEqualTo("[email protected]");
    assertThat(message.getFrom()[0].toString()).isEqualTo("JHipster Online <test@localhost>");
    assertThat(message.getContent()).isInstanceOf(Multipart.class);
    assertThat(aos.toString()).isEqualTo("\r\ntestContent");
    assertThat(part.getDataHandler().getContentType()).isEqualTo("text/plain; charset=UTF-8");
}
 
Example #16
Source File: CoreEncoders.java    From http-builder-ng with Apache License 2.0 6 votes vote down vote up
private static MimeBodyPart part(final ChainedHttpConfig config, final MultipartContent.MultipartPart multipartPart) throws MessagingException {
    final MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setDisposition("form-data");

    if (multipartPart.getFileName() != null) {
        bodyPart.setFileName(multipartPart.getFileName());
        bodyPart.setHeader("Content-Disposition", format("form-data; name=\"%s\"; filename=\"%s\"", multipartPart.getFieldName(), multipartPart.getFileName()));

    } else {
        bodyPart.setHeader("Content-Disposition", format("form-data; name=\"%s\"", multipartPart.getFieldName()));
    }

    bodyPart.setDataHandler(new DataHandler(new EncodedDataSource(config, multipartPart.getContentType(), multipartPart.getContent())));
    bodyPart.setHeader("Content-Type", multipartPart.getContentType());

    return bodyPart;
}
 
Example #17
Source File: BCCryptoHelper.java    From OpenAs2App with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public boolean isEncrypted(MimeBodyPart part) throws MessagingException {
    ContentType contentType = new ContentType(part.getContentType());
    String baseType = contentType.getBaseType().toLowerCase();

    if (baseType.equalsIgnoreCase("application/pkcs7-mime")) {
        String smimeType = contentType.getParameter("smime-type");
        boolean checkResult = (smimeType != null) && smimeType.equalsIgnoreCase("enveloped-data");
        if (!checkResult && logger.isDebugEnabled()) {
            logger.debug("Check for encrypted data failed on SMIME content type: " + smimeType);
        }
        return (checkResult);
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Check for encrypted data failed on BASE content type: " + baseType);
    }
    return false;
}
 
Example #18
Source File: TransportTest.java    From javamail with Apache License 2.0 6 votes vote down vote up
/**
 * Generate multi part / alternative message
 */
private MimeMessage generateMessage() throws MessagingException {
    MimeMessage msg = new MimeMessage(session);
    msg.setFrom("Test <[email protected]>");
    msg.setSubject("subject");
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setText("Body's text (text)", "UTF-8");
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent("<p>Body's text <strong>(html)</strong></p>", "text/html; charset=UTF-8");
    Multipart multiPart = new MimeMultipart("alternative");
    multiPart.addBodyPart(textPart); // first
    multiPart.addBodyPart(htmlPart); // second
    msg.setContent(multiPart);
    msg.addHeader("X-Custom-Header", "CustomValue");
    return msg;
}
 
Example #19
Source File: Mail.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private void addAttachedFilePart( FileObject file ) throws Exception {
  // create a data source

  MimeBodyPart files = new MimeBodyPart();
  // create a data source
  URLDataSource fds = new URLDataSource( file.getURL() );
  // get a data Handler to manipulate this file type;
  files.setDataHandler( new DataHandler( fds ) );
  // include the file in the data source
  files.setFileName( file.getName().getBaseName() );
  // insist on base64 to preserve line endings
  files.addHeader( "Content-Transfer-Encoding", "base64" );
  // add the part with the file in the BodyPart();
  data.parts.addBodyPart( files );
  if ( isDetailed() ) {
    logDetailed( BaseMessages.getString( PKG, "Mail.Log.AttachedFile", fds.getName() ) );
  }

}
 
Example #20
Source File: ContentModelMessage.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
private MimeBodyPart getTextBodyPart(String bodyText, String subtype, String mimeType) throws MessagingException
{
    MimeBodyPart result = new MimeBodyPart();
    result.setText(bodyText, AlfrescoImapConst.UTF_8, subtype);
    result.addHeader(AlfrescoImapConst.CONTENT_TYPE, mimeType + AlfrescoImapConst.CHARSET_UTF8);
    result.addHeader(AlfrescoImapConst.CONTENT_TRANSFER_ENCODING, AlfrescoImapConst.BASE_64_ENCODING);
    return result;
}
 
Example #21
Source File: SendMailServiceTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Test Execute method with successful scenario,
 * (attachments not empty and readReceipt is true).
 *
 * @throws Exception
 */
@Test
public void testExecuteGoesToSuccessScenario3() throws Exception {
    prepareTransportClassForStaticMock();
    Mockito.doNothing().when(mimeBodyPartMock).setContent(BODY, TEXT_PLAIN + CHARSET_CST + DEFAULT_CHARACTERSET);
    PowerMockito.whenNew(FileDataSource.class).withArguments(anyString()).thenReturn(fileDataSourceMock);
    Mockito.doReturn(fileMock).when(fileDataSourceMock).getFile();
    Mockito.doReturn(true).when(fileMock).exists();
    Mockito.doReturn(mockPath).when(fileMock).toPath();
    PowerMockito.mockStatic(Files.class);
    when(Files.isReadable(mockPath)).thenReturn(true);
    PowerMockito.whenNew(DataHandler.class).withArguments(fileDataSourceMock).thenReturn(dataHandlerMock);
    doNothing().when(mimeBodyPartMock).setDataHandler(dataHandlerMock);
    doNothing().when(mimeBodyPartMock).setFileName(anyString());
    doNothing().when(mimeMultipartMock).addBodyPart(mimeBodyPartMock);

    inputBuilder.hostname(SMTP_HOSTANME)
            .port(PORT)
            .from(FROM)
            .to(TO)
            .cc(CC)
            .bcc(BCC)
            .subject(SUBJECT)
            .body(BODY)
            .attachments(ATTACHMENTS)
            .delimiter(DELIMITER)
            .readReceipt(READ_RECEIPT_TRUE);

    Map<String, String> result = sendMailService.execute(inputBuilder.build());
    assertEquals(MAIL_WAS_SENT, result.get(RETURN_RESULT));
    assertEquals(SUCCESS_RETURN_CODE, result.get(RETURN_CODE));
    // 3 invocations, one for html setting and one for each of the attachments
    PowerMockito.verifyNew(MimeBodyPart.class, times(3)).withNoArguments();
    verify(mimeBodyPartMock, times(3)).setHeader(CONTENT_TRANSFER_ENCODING, DEFAULT_CONTENT_TRANSFER_ENCODING);
    PowerMockito.verifyNew(FileDataSource.class, times(2)).withArguments(anyString());
    verify(mimeBodyPartMock, times(2)).setDataHandler(dataHandlerMock);
    verify(mimeBodyPartMock, times(2)).setFileName(anyString());
    verify(mimeMultipartMock, times(3)).addBodyPart(mimeBodyPartMock);
    verify(smtpMessageMock).setNotifyOptions(NOTIFY_DELAY + NOTIFY_FAILURE + NOTIFY_SUCCESS);
}
 
Example #22
Source File: MimePackage.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Add a multipart/alternative part to message body
 *
 * @param plainContent
 *            the content of the text/plain sub-part
 * @param htmlContent
 *            the content of the text/html sub-part
 * @param charset
 *            the character set for the part
 * @throws PackageException
 */
@PublicAtsApi
public void addAlternativePart(
                                String plainContent,
                                String htmlContent,
                                String charset ) throws PackageException {

    MimeMultipart alternativePart = new MimeMultipart("alternative");

    try {
        // create a new text/plain part
        MimeBodyPart plainPart = new MimeBodyPart();
        plainPart.setText(plainContent, charset, PART_TYPE_TEXT_PLAIN);
        plainPart.setDisposition(MimeBodyPart.INLINE);

        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setText(htmlContent, charset, PART_TYPE_TEXT_HTML);
        htmlPart.setDisposition(MimeBodyPart.INLINE);

        alternativePart.addBodyPart(plainPart, 0);
        alternativePart.addBodyPart(htmlPart, 1);

        MimeBodyPart mimePart = new MimeBodyPart();
        mimePart.setContent(alternativePart);

        addPart(mimePart, PART_POSITION_LAST);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
Example #23
Source File: HtmlEmail.java    From commons-email with Apache License 2.0 5 votes vote down vote up
/**
 * Embeds the specified {@code DataSource} in the HTML using the
 * specified Content-ID. Returns the specified Content-ID string.
 *
 * @param dataSource the {@code DataSource} to embed
 * @param name the name that will be set in the file name header field
 * @param cid the Content-ID to use for this {@code DataSource}
 * @return the URL encoded Content-ID for this {@code DataSource}
 * @throws EmailException if the embedding fails or if {@code name} is
 * null or empty
 * @since 1.1
 */
public String embed(final DataSource dataSource, final String name, final String cid)
    throws EmailException
{
    if (EmailUtils.isEmpty(name))
    {
        throw new EmailException("name cannot be null or empty");
    }

    final MimeBodyPart mbp = new MimeBodyPart();

    try
    {
        // URL encode the cid according to RFC 2392
        final String encodedCid = EmailUtils.encodeUrl(cid);

        mbp.setDataHandler(new DataHandler(dataSource));
        mbp.setFileName(name);
        mbp.setDisposition(EmailAttachment.INLINE);
        mbp.setContentID("<" + encodedCid + ">");

        final InlineImage ii = new InlineImage(encodedCid, dataSource, mbp);
        this.inlineEmbeds.put(name, ii);

        return encodedCid;
    }
    catch (final MessagingException me)
    {
        throw new EmailException(me);
    }
    catch (final UnsupportedEncodingException uee)
    {
        throw new EmailException(uee);
    }
}
 
Example #24
Source File: JavaMailWrapper.java    From unitime with Apache License 2.0 5 votes vote down vote up
@Override
protected void addAttachment(String name, DataHandler data) throws MessagingException {
       BodyPart attachment = new MimeBodyPart();
       attachment.setDataHandler(data);
       attachment.setFileName(name);
       attachment.setHeader("Content-ID", "<" + name + ">");
       iBody.addBodyPart(attachment);
}
 
Example #25
Source File: SendMailServiceTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
/**
 * Verify the stubbed method invocations.
 */
private void verifyCommonMethodInvocations() throws Exception {
    PowerMockito.verifyNew(MimeBodyPart.class).withNoArguments();
    verify(mimeMultipartMock).addBodyPart(mimeBodyPartMock);

    verifyCommons();
}
 
Example #26
Source File: EmailerTest.java    From cuba with Apache License 2.0 5 votes vote down vote up
private MimeBodyPart getInlineAttachment(MimeMessage msg) throws IOException, MessagingException {
    assertTrue(msg.getContent() instanceof MimeMultipart);
    MimeMultipart mimeMultipart = (MimeMultipart) msg.getContent();

    Object content2 = mimeMultipart.getBodyPart(0).getContent();
    assertTrue(content2 instanceof MimeMultipart);
    MimeMultipart textBodyPart = (MimeMultipart) content2;

    return (MimeBodyPart) textBodyPart.getBodyPart(1);
}
 
Example #27
Source File: BaseMessage.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    // read in partnership
    partnership = (Partnership) in.readObject();

    // read in attributes
    attributes = (Map<String, String>) in.readObject();

    // read in data history
    history = (DataHistory) in.readObject();

    try {
        // read in message headers
        headers = new InternetHeaders(in);

        // read in mime body 
        if (in.read() == 1) {
            data = new MimeBodyPart(in);
        }
    } catch (MessagingException me) {
        throw new IOException("Messaging exception: " + me.getMessage());
    }

    // read in MDN
    MDN = (MessageMDN) in.readObject();

    if (MDN != null) {
        MDN.setMessage(this);
    }

    customOuterMimeHeaders = new HashMap<String, String>();
}
 
Example #28
Source File: SendMailConnector.java    From camunda-bpm-mail with Apache License 2.0 5 votes vote down vote up
protected void createMessageContent(Message message, SendMailRequest request) throws MessagingException, IOException {
  if (isTextOnlyMessage(request)) {
    message.setText(request.getText());

  } else {
    Multipart multiPart = new MimeMultipart();

    if (request.getText() != null) {
      MimeBodyPart textPart = new MimeBodyPart();
      textPart.setText(request.getText());
      multiPart.addBodyPart(textPart);
    }

    if (request.getHtml() != null) {
      MimeBodyPart htmlPart = new MimeBodyPart();
      htmlPart.setContent(request.getHtml(), MailContentType.TEXT_HTML.getType());
      multiPart.addBodyPart(htmlPart);
    }

    if (request.getFileNames() != null) {
      for (String fileName : request.getFileNames()) {
        MimeBodyPart part = new MimeBodyPart();
        part.attachFile(fileName);
        multiPart.addBodyPart(part);
      }
    }

    message.setContent(multiPart);
  }
}
 
Example #29
Source File: MailUtil.java    From mail-micro-service with Apache License 2.0 5 votes vote down vote up
/**
 * 追加内嵌图片
 * @author hf-hf
 * @date 2018/12/27 16:53
 * @param images
 * @param multipart
 * @throws MessagingException
 */
private void addImages(File[] images, MimeMultipart multipart) throws MessagingException {
    if (null != images && images.length > 0) {
        for (int i = 0; i < images.length; i++) {
            MimeBodyPart imagePart = new MimeBodyPart();
            DataHandler dataHandler = new DataHandler(new FileDataSource(images[i]));
            imagePart.setDataHandler(dataHandler);
            imagePart.setContentID(images[i].getName());
            multipart.addBodyPart(imagePart);
        }
    }
}
 
Example #30
Source File: MimeMultipartBuilder.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
private void addAttachmentBodyParts(final MimeMultipart email) throws MessagingException {
    for (final String filePath : attachmentFilePaths) {
        final MimeBodyPart attachmentBodyPart = new MimeBodyPart();
        final DataSource source = new FileDataSource(filePath);
        attachmentBodyPart.setDataHandler(new DataHandler(source));
        attachmentBodyPart.setFileName(FilenameUtils.getName(filePath));
        email.addBodyPart(attachmentBodyPart);
    }
}