Java Code Examples for javax.mail.internet.MimeBodyPart#setHeader()

The following examples show how to use javax.mail.internet.MimeBodyPart#setHeader() . 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: 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 2
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 6 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldManageItsMimeType() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                            "Disposition: MDN-sent-automatically",
                            "text/plain")
                    ));
    scriptPart.setHeader("Content-Type", "text/plain");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    
    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isFalse();
}
 
Example 3
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 4
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 5
Source File: DSNBounce.java    From james-project with Apache License 2.0 6 votes vote down vote up
private MimeBodyPart createDSN(Mail originalMail) throws MessagingException {
    StringBuffer buffer = new StringBuffer();

    appendReportingMTA(buffer);
    buffer.append("Received-From-MTA: dns; " + originalMail.getRemoteHost())
        .append(LINE_BREAK);

    for (MailAddress rec : originalMail.getRecipients()) {
        appendRecipient(buffer, rec, getDeliveryError(originalMail), originalMail.getLastUpdated());
    }

    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setContent(buffer.toString(), "text/plain");
    bodyPart.setHeader("Content-Type", "message/delivery-status");
    bodyPart.setDescription("Delivery Status Notification");
    bodyPart.setFileName("status.dat");
    return bodyPart;
}
 
Example 6
Source File: MessageAlteringUtils.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MimeBodyPart getErrorPart(Mail originalMail) throws MessagingException {
    MimeBodyPart errorPart = new MimeBodyPart();
    errorPart.setContent(originalMail.getErrorMessage(), "text/plain");
    errorPart.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
    errorPart.setFileName("Reasons");
    errorPart.setDisposition(javax.mail.Part.ATTACHMENT);
    return errorPart;
}
 
Example 7
Source File: cfMAIL.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
private void addAttachments( Enumeration<fileAttachment> _attach, Multipart _parent, boolean _isInline ) throws MessagingException{
	while ( _attach.hasMoreElements() ){
		fileAttachment nextFile = _attach.nextElement();
		FileDataSource fds 			= new FileDataSource( nextFile.getFilepath() );
		String mimeType = nextFile.getMimetype();
		if (mimeType == null){
			// if mime type not supplied then auto detect
			mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(nextFile.getFilepath());
     }else{
			// since mime type is not null then it the mime type has been set manually therefore
			// we need to ensure that any call to the underlying FileDataSource.getFileTypeMap()
			// returns a FileTypeMap that will map to this type
			fds.setFileTypeMap(new CustomFileTypeMap(mimeType));
		}
		
		String filename = cleanName(fds.getName());
		try {
			// encode the filename to ensure that it contains US-ASCII characters only
			filename = MimeUtility.encodeText( filename, "utf-8", "b" );
		} catch (UnsupportedEncodingException e5) {
			// shouldn't occur
		}
	  MimeBodyPart mimeAttach	= new MimeBodyPart();
	  mimeAttach.setDataHandler( new DataHandler(fds) );
		mimeAttach.setFileName( filename );

		ContentType ct = new ContentType(mimeType);
		ct.setParameter("name", filename );
		
		mimeAttach.setHeader("Content-Type", ct.toString() );

		if ( _isInline ){
       mimeAttach.setDisposition( "inline" );
       mimeAttach.addHeader( "Content-id", "<" + nextFile.getContentid() + ">" );
		}
     
		_parent.addBodyPart(mimeAttach);
	}
}
 
Example 8
Source File: TextCalendarBodyToAttachment.java    From james-project with Apache License 2.0 5 votes vote down vote up
private MimeBodyPart createMimeBodyPartWithContentHeadersFromMimeMessage(MimeMessage mimeMessage, List<Header> contentHeaders) throws MessagingException {
    MimeBodyPart fileBody = new MimeBodyPart(mimeMessage.getRawInputStream());
    for (Header header : contentHeaders) {
        fileBody.setHeader(header.getName(), header.getValue());
    }

    fileBody.setDisposition(Part.ATTACHMENT);
    return fileBody;
}
 
Example 9
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldDetectBigMDN() throws Exception {

    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
        new DataHandler(
            new ByteArrayDataSource(
                Joiner.on("\r\n").join(
                    "Final-Recipient: rfc822;[email protected]",
                    "Disposition: automatic-action/MDN-sent-automatically; displayed",
                    ""),
                "message/disposition-notification;")
        ));
    scriptPart.setHeader("Content-Type", "message/disposition-notification");
    BodyPart bigBody = MimeMessageBuilder.bodyPartBuilder() // ~3MB
        .data("12345678\r\n".repeat(300 * 1024))
        .build();
    multipart.addBodyPart(bigBody);
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();

    FakeMail fakeMail = FakeMail.builder()
        .name("mail")
        .sender(MailAddressFixture.ANY_AT_JAMES)
        .mimeMessage(message)
        .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isTrue();
}
 
Example 10
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldNotFilterManuallySentMdn() throws Exception {
    MimeMessage message = MimeMessageUtil.defaultMimeMessage();
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                        Joiner.on("\r\n").join(
                            "Final-Recipient: rfc822;[email protected]",
                            "Disposition: manual-action/MDN-sent-manually; displayed",
                            ""),
                            "message/disposition-notification; charset=UTF-8")
                    ));
    scriptPart.setHeader("Content-Type", "message/disposition-notification");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();
    
    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isFalse();
}
 
Example 11
Source File: AutomaticallySentMailDetectorImplTest.java    From james-project with Apache License 2.0 5 votes vote down vote up
@Test
public void isMdnSentAutomaticallyShouldBeDetected() throws Exception {
    MimeMessage message = new MimeMessage(Session.getDefaultInstance(new Properties()));
    MimeMultipart multipart = new MimeMultipart();
    MimeBodyPart scriptPart = new MimeBodyPart();
    scriptPart.setDataHandler(
            new DataHandler(
                    new ByteArrayDataSource(
                        Joiner.on("\r\n").join(
                            "Final-Recipient: rfc822;[email protected]",
                            "Disposition: automatic-action/MDN-sent-automatically; displayed",
                            ""),
                            "message/disposition-notification;")
                    ));
    scriptPart.setHeader("Content-Type", "message/disposition-notification");
    multipart.addBodyPart(scriptPart);
    message.setContent(multipart);
    message.saveChanges();

    FakeMail fakeMail = FakeMail.builder()
            .name("mail")
            .sender("[email protected]")
            .mimeMessage(message)
            .build();

    assertThat(new AutomaticallySentMailDetectorImpl().isMdnSentAutomatically(fakeMail)).isTrue();
}
 
Example 12
Source File: MimeUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static MimeBodyPart createMimeBodyPart(MimeMultipart multipart) throws MessagingException {
    MimeBodyPart part = new MimeBodyPart();
    part.setContent(multipart);
    part.setHeader("Content-Type", multipart.getContentType());

    return part;
}
 
Example 13
Source File: MimeUtil.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static MimeBodyPart createMimeBodyPart(byte[] data, String contentType, String contentTransferEncoding) throws MessagingException {
    // create a MimeBodyPart and set up it's content and content headers
    MimeBodyPart part = new MimeBodyPart();
    part.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType, null)));
    part.setHeader("Content-Type", contentType);
    part.setHeader("Content-Transfer-Encoding", contentTransferEncoding);

    return part;
}
 
Example 14
Source File: MailSender.java    From BlitzMail with GNU Affero General Public License v3.0 5 votes vote down vote up
private MimeBodyPart getMimeBodyPart(JSONObject attachment) throws IOException, MessagingException {
	MimeBodyPart mbp = new MimeBodyPart();

	try {
		mbp.attachFile(attachment.getString("path"));
		mbp.setFileName(attachment.getString("filename"));
		mbp.setHeader("Content-Type", attachment.getString("mimeType") + "; name=" + mbp.getFileName());
	} catch(JSONException e) {
		e.printStackTrace();
	}

	return mbp;
}
 
Example 15
Source File: WhiteListManager.java    From james-project with Apache License 2.0 4 votes vote down vote up
private void sendReplyFromPostmaster(Mail mail, String stringContent) {
    try {
        MailAddress notifier = getMailetContext().getPostmaster();

        MailAddress senderMailAddress = mail.getMaybeSender().get();

        MimeMessage message = mail.getMessage();
        // Create the reply message
        MimeMessage reply = new MimeMessage(Session.getDefaultInstance(System.getProperties(), null));

        // Create the list of recipients in the Address[] format
        InternetAddress[] rcptAddr = new InternetAddress[1];
        rcptAddr[0] = senderMailAddress.toInternetAddress();
        reply.setRecipients(Message.RecipientType.TO, rcptAddr);

        // Set the sender...
        reply.setFrom(notifier.toInternetAddress());

        // Create the message body
        MimeMultipart multipart = new MimeMultipart();
        // Add message as the first mime body part
        MimeBodyPart part = new MimeBodyPart();
        part.setContent(stringContent, "text/plain");
        part.setHeader(RFC2822Headers.CONTENT_TYPE, "text/plain");
        multipart.addBodyPart(part);

        reply.setContent(multipart);
        reply.setHeader(RFC2822Headers.CONTENT_TYPE, multipart.getContentType());

        // Create the list of recipients in our MailAddress format
        Set<MailAddress> recipients = new HashSet<>();
        recipients.add(senderMailAddress);

        // Set additional headers
        if (reply.getHeader(RFC2822Headers.DATE) == null) {
            reply.setHeader(RFC2822Headers.DATE, DateFormats.RFC822_DATE_FORMAT.format(LocalDateTime.now()));
        }
        String subject = message.getSubject();
        if (subject == null) {
            subject = "";
        }
        if (subject.indexOf("Re:") == 0) {
            reply.setSubject(subject);
        } else {
            reply.setSubject("Re:" + subject);
        }
        reply.setHeader(RFC2822Headers.IN_REPLY_TO, message.getMessageID());

        // Send it off...
        getMailetContext().sendMail(notifier, recipients, reply);
    } catch (Exception e) {
        LOGGER.error("Exception found sending reply", e);
    }
}
 
Example 16
Source File: AS2ReceiverHandler.java    From OpenAs2App with BSD 2-Clause "Simplified" License 4 votes vote down vote up
public void createMDNData(Session session, MessageMDN mdn, String micAlg, String signatureProtocol) throws Exception {
    // Create the report and sub-body parts
    MimeMultipart reportParts = new MimeMultipart();

    // Create the text part
    MimeBodyPart textPart = new MimeBodyPart();
    String text = mdn.getText() + "\r\n";
    textPart.setContent(text, "text/plain");
    textPart.setHeader("Content-Type", "text/plain");
    reportParts.addBodyPart(textPart);

    // Create the report part
    MimeBodyPart reportPart = new MimeBodyPart();
    InternetHeaders reportValues = new InternetHeaders();
    reportValues.setHeader("Reporting-UA", mdn.getAttribute(AS2MessageMDN.MDNA_REPORTING_UA));
    reportValues.setHeader("Original-Recipient", mdn.getAttribute(AS2MessageMDN.MDNA_ORIG_RECIPIENT));
    reportValues.setHeader("Final-Recipient", mdn.getAttribute(AS2MessageMDN.MDNA_FINAL_RECIPIENT));
    reportValues.setHeader("Original-Message-ID", mdn.getAttribute(AS2MessageMDN.MDNA_ORIG_MESSAGEID));
    reportValues.setHeader("Disposition", mdn.getAttribute(AS2MessageMDN.MDNA_DISPOSITION));
    reportValues.setHeader("Received-Content-MIC", mdn.getAttribute(AS2MessageMDN.MDNA_MIC));

    Enumeration<String> reportEn = reportValues.getAllHeaderLines();
    StringBuffer reportData = new StringBuffer();

    while (reportEn.hasMoreElements()) {
        reportData.append(reportEn.nextElement()).append("\r\n");
    }

    reportData.append("\r\n");

    String reportText = reportData.toString();
    reportPart.setContent(reportText, AS2Standards.DISPOSITION_TYPE);
    reportPart.setHeader("Content-Type", AS2Standards.DISPOSITION_TYPE);
    reportParts.addBodyPart(reportPart);

    // Convert report parts to MimeBodyPart
    MimeBodyPart report = new MimeBodyPart();
    reportParts.setSubType(AS2Standards.REPORT_SUBTYPE);
    report.setContent(reportParts);
    String contentType = reportParts.getContentType();
    if ("true".equalsIgnoreCase(Properties.getProperty("remove_multipart_content_type_header_folding", "false"))) {
        contentType = contentType.replaceAll("\r\n[ \t]*", " ");
    }
    report.setHeader("Content-Type", contentType);

    // Sign the data if needed
    if (signatureProtocol != null) {
        CertificateFactory certFx = session.getCertificateFactory();

        try {
            // The receiver of the original message is the sender of the MDN....
            X509Certificate senderCert = certFx.getCertificate(mdn, Partnership.PTYPE_RECEIVER);
            PrivateKey senderKey = certFx.getPrivateKey(mdn, senderCert);
            Partnership p = mdn.getPartnership();
            String contentTxfrEncoding = p.getAttribute(Partnership.PA_CONTENT_TRANSFER_ENCODING);
            boolean isRemoveCmsAlgorithmProtectionAttr = "true".equalsIgnoreCase(p.getAttribute(Partnership.PA_REMOVE_PROTECTION_ATTRIB));
            if (contentTxfrEncoding == null) {
                contentTxfrEncoding = Session.DEFAULT_CONTENT_TRANSFER_ENCODING;
            }
            // sign the data using CryptoHelper
            MimeBodyPart signedReport = AS2Util.getCryptoHelper().sign(report, senderCert, senderKey, micAlg, contentTxfrEncoding, false, isRemoveCmsAlgorithmProtectionAttr);
            mdn.setData(signedReport);
        } catch (CertificateNotFoundException cnfe) {
            cnfe.terminate();
            mdn.setData(report);
        } catch (KeyNotFoundException knfe) {
            knfe.terminate();
            mdn.setData(report);
        }
    } else {
        mdn.setData(report);
    }

    // Update the MDN headers with content information
    MimeBodyPart data = mdn.getData();
    String headerContentType = data.getContentType();
    if ("true".equalsIgnoreCase(Properties.getProperty("remove_http_header_folding", "true"))) {
        headerContentType = headerContentType.replaceAll("\r\n[ \t]*", " ");
    }
    mdn.setHeader("Content-Type", headerContentType);

    // int size = getSize(data);
    // mdn.setHeader("Content-Length", Integer.toString(size));
}
 
Example 17
Source File: BigAttachmentTest.java    From subethasmtp with Apache License 2.0 4 votes vote down vote up
/** */
public void testAttachments() throws Exception
{
	if (BIGFILE_PATH.equals(TO_CHANGE))
	{
		log.error("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !");
	}
	assertNotSame("BigAttachmentTest: To complete this test you must change the BIGFILE_PATH var to point out a file on your disk !", TO_CHANGE, BIGFILE_PATH);
	Properties props = System.getProperties();
	props.setProperty("mail.smtp.host", "localhost");
	props.setProperty("mail.smtp.port", SMTP_PORT+"");
	Session session = Session.getInstance(props);

	MimeMessage baseMsg = new MimeMessage(session);
	MimeBodyPart bp1 = new MimeBodyPart();
	bp1.setHeader("Content-Type", "text/plain");
	bp1.setContent("Hello World!!!", "text/plain; charset=\"ISO-8859-1\"");

	// Attach the file
	MimeBodyPart bp2 = new MimeBodyPart();
	FileDataSource fileAttachment = new FileDataSource(BIGFILE_PATH);
	DataHandler dh = new DataHandler(fileAttachment);
	bp2.setDataHandler(dh);
	bp2.setFileName(fileAttachment.getName());

	Multipart multipart = new MimeMultipart();
	multipart.addBodyPart(bp1);
	multipart.addBodyPart(bp2);

	baseMsg.setFrom(new InternetAddress("Ted <[email protected]>"));
	baseMsg.setRecipient(Message.RecipientType.TO, new InternetAddress(
			"[email protected]"));
	baseMsg.setSubject("Test Big attached file message");
	baseMsg.setContent(multipart);
	baseMsg.saveChanges();

	log.debug("Send started");
	Transport t = new SMTPTransport(session, new URLName("smtp://localhost:"+SMTP_PORT));
	long started = System.currentTimeMillis();
	t.connect();
	t.sendMessage(baseMsg, new Address[] {new InternetAddress(
			"[email protected]")});
	t.close();
	started = System.currentTimeMillis() - started;
	log.info("Elapsed ms = "+started);

	WiserMessage msg = this.server.getMessages().get(0);

	assertEquals(1, this.server.getMessages().size());
	assertEquals("[email protected]", msg.getEnvelopeReceiver());

	File compareFile = File.createTempFile("attached", ".tmp");
	log.debug("Writing received attachment ...");

	FileOutputStream fos = new FileOutputStream(compareFile);
	((MimeMultipart) msg.getMimeMessage().getContent()).getBodyPart(1).getDataHandler().writeTo(fos);
	fos.close();
	log.debug("Checking integrity ...");
	assertTrue(this.checkIntegrity(new File(BIGFILE_PATH), compareFile));
	log.debug("Checking integrity DONE");
	compareFile.delete();
}
 
Example 18
Source File: MimeMessageHelper.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Add an inline element to the MimeMessage, taking the content from a
 * {@code javax.activation.DataSource}.
 * <p>Note that the InputStream returned by the DataSource implementation
 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
 * {@code getInputStream()} multiple times.
 * <p><b>NOTE:</b> Invoke {@code addInline} <i>after</i> {@link #setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param contentId the content ID to use. Will end up as "Content-ID" header
 * in the body part, surrounded by angle brackets: e.g. "myId" -> "&lt;myId&gt;".
 * Can be referenced in HTML source via src="cid:myId" expressions.
 * @param dataSource the {@code javax.activation.DataSource} to take
 * the content from, determining the InputStream and the content type
 * @throws MessagingException in case of errors
 * @see #addInline(String, java.io.File)
 * @see #addInline(String, org.springframework.core.io.Resource)
 */
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
	Assert.notNull(contentId, "Content ID must not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	MimeBodyPart mimeBodyPart = new MimeBodyPart();
	mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
	// We're using setHeader here to remain compatible with JavaMail 1.2,
	// rather than JavaMail 1.3's setContentID.
	mimeBodyPart.setHeader(HEADER_CONTENT_ID, "<" + contentId + ">");
	mimeBodyPart.setDataHandler(new DataHandler(dataSource));
	getMimeMultipart().addBodyPart(mimeBodyPart);
}
 
Example 19
Source File: MimeMessageHelper.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Add an inline element to the MimeMessage, taking the content from a
 * {@code javax.activation.DataSource}.
 * <p>Note that the InputStream returned by the DataSource implementation
 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
 * {@code getInputStream()} multiple times.
 * <p><b>NOTE:</b> Invoke {@code addInline} <i>after</i> {@link #setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param contentId the content ID to use. Will end up as "Content-ID" header
 * in the body part, surrounded by angle brackets: e.g. "myId" -> "&lt;myId&gt;".
 * Can be referenced in HTML source via src="cid:myId" expressions.
 * @param dataSource the {@code javax.activation.DataSource} to take
 * the content from, determining the InputStream and the content type
 * @throws MessagingException in case of errors
 * @see #addInline(String, java.io.File)
 * @see #addInline(String, org.springframework.core.io.Resource)
 */
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
	Assert.notNull(contentId, "Content ID must not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	MimeBodyPart mimeBodyPart = new MimeBodyPart();
	mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
	// We're using setHeader here to remain compatible with JavaMail 1.2,
	// rather than JavaMail 1.3's setContentID.
	mimeBodyPart.setHeader(HEADER_CONTENT_ID, "<" + contentId + ">");
	mimeBodyPart.setDataHandler(new DataHandler(dataSource));
	getMimeMultipart().addBodyPart(mimeBodyPart);
}
 
Example 20
Source File: MimeMessageHelper.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Add an inline element to the MimeMessage, taking the content from a
 * {@code javax.activation.DataSource}.
 * <p>Note that the InputStream returned by the DataSource implementation
 * needs to be a <i>fresh one on each call</i>, as JavaMail will invoke
 * {@code getInputStream()} multiple times.
 * <p><b>NOTE:</b> Invoke {@code addInline} <i>after</i> {@link #setText};
 * else, mail readers might not be able to resolve inline references correctly.
 * @param contentId the content ID to use. Will end up as "Content-ID" header
 * in the body part, surrounded by angle brackets: e.g. "myId" -> "&lt;myId&gt;".
 * Can be referenced in HTML source via src="cid:myId" expressions.
 * @param dataSource the {@code javax.activation.DataSource} to take
 * the content from, determining the InputStream and the content type
 * @throws MessagingException in case of errors
 * @see #addInline(String, java.io.File)
 * @see #addInline(String, org.springframework.core.io.Resource)
 */
public void addInline(String contentId, DataSource dataSource) throws MessagingException {
	Assert.notNull(contentId, "Content ID must not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	MimeBodyPart mimeBodyPart = new MimeBodyPart();
	mimeBodyPart.setDisposition(MimeBodyPart.INLINE);
	// We're using setHeader here to remain compatible with JavaMail 1.2,
	// rather than JavaMail 1.3's setContentID.
	mimeBodyPart.setHeader(HEADER_CONTENT_ID, "<" + contentId + ">");
	mimeBodyPart.setDataHandler(new DataHandler(dataSource));
	getMimeMultipart().addBodyPart(mimeBodyPart);
}