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

The following examples show how to use javax.mail.internet.MimeBodyPart#setDataHandler() . 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: 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 2
Source File: GMailClient.java    From blynk-server with GNU General Public License v3.0 6 votes vote down vote up
private void attachCSV(Multipart multipart, QrHolder[] attachmentData) throws Exception {
    StringBuilder sb = new StringBuilder();
    for (QrHolder qrHolder : attachmentData) {
        sb.append(qrHolder.token)
        .append(",")
        .append(qrHolder.deviceId)
        .append(",")
        .append(qrHolder.dashId)
        .append("\n");
    }
    MimeBodyPart attachmentsPart = new MimeBodyPart();
    ByteArrayDataSource source = new ByteArrayDataSource(sb.toString(), "text/csv");
    attachmentsPart.setDataHandler(new DataHandler(source));
    attachmentsPart.setFileName("tokens.csv");

    multipart.addBodyPart(attachmentsPart);
}
 
Example 3
Source File: MimePackage.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Add the specified file as an attachment
 *
 * @param fileName
 *            name of the file
 * @throws PackageException
 *             on error
 */
@PublicAtsApi
public void addAttachment(
                           String fileName ) throws PackageException {

    try {
        // add attachment to multipart content
        MimeBodyPart attPart = new MimeBodyPart();
        FileDataSource ds = new FileDataSource(fileName);
        attPart.setDataHandler(new DataHandler(ds));
        attPart.setDisposition(MimeBodyPart.ATTACHMENT);
        attPart.setFileName(ds.getName());

        addPart(attPart, PART_POSITION_LAST);
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
 
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: MimeMessageHelper.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Add an attachment 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.
 * @param attachmentFilename the name of the attachment as it will
 * appear in the mail (the content type will be determined by this)
 * @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 #addAttachment(String, org.springframework.core.io.InputStreamSource)
 * @see #addAttachment(String, java.io.File)
 */
public void addAttachment(String attachmentFilename, DataSource dataSource) throws MessagingException {
	Assert.notNull(attachmentFilename, "Attachment filename must not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	try {
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
		mimeBodyPart.setFileName(MimeUtility.encodeText(attachmentFilename));
		mimeBodyPart.setDataHandler(new DataHandler(dataSource));
		getRootMimeMultipart().addBodyPart(mimeBodyPart);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to encode attachment filename", ex);
	}
}
 
Example 6
Source File: MimeMessageHelper.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Add an attachment 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.
 * @param attachmentFilename the name of the attachment as it will
 * appear in the mail (the content type will be determined by this)
 * @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 #addAttachment(String, org.springframework.core.io.InputStreamSource)
 * @see #addAttachment(String, java.io.File)
 */
public void addAttachment(String attachmentFilename, DataSource dataSource) throws MessagingException {
	Assert.notNull(attachmentFilename, "Attachment filename must not be null");
	Assert.notNull(dataSource, "DataSource must not be null");
	try {
		MimeBodyPart mimeBodyPart = new MimeBodyPart();
		mimeBodyPart.setDisposition(MimeBodyPart.ATTACHMENT);
		mimeBodyPart.setFileName(MimeUtility.encodeText(attachmentFilename));
		mimeBodyPart.setDataHandler(new DataHandler(dataSource));
		getRootMimeMultipart().addBodyPart(mimeBodyPart);
	}
	catch (UnsupportedEncodingException ex) {
		throw new MessagingException("Failed to encode attachment filename", ex);
	}
}
 
Example 7
Source File: MimeMessageBuilder.java    From james-project with Apache License 2.0 5 votes vote down vote up
public BodyPart build() throws IOException, MessagingException {
    Preconditions.checkState(!(dataAsString.isPresent() && dataAsBytes.isPresent()), "Can not specify data as bytes and data as string at the same time");
    MimeBodyPart bodyPart = new MimeBodyPart();
    if (dataAsBytes.isPresent()) {
        bodyPart.setDataHandler(
            new DataHandler(
                new ByteArrayDataSource(
                    dataAsBytes.get(),
                    type.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE))
            ));
    } else {
        bodyPart.setDataHandler(
            new DataHandler(
                new ByteArrayDataSource(
                    dataAsString.orElse(DEFAULT_VALUE),
                    type.orElse(DEFAULT_TEXT_PLAIN_UTF8_TYPE))
            ));
    }
    if (filename.isPresent()) {
        bodyPart.setFileName(filename.get());
    }
    if (cid.isPresent()) {
        bodyPart.setContentID(cid.get());
    }
    if (disposition.isPresent()) {
        bodyPart.setDisposition(disposition.get());
    }
    List<Header> headerList = headers.build();
    for (Header header: headerList) {
        bodyPart.addHeader(header.name, header.value);
    }
    return bodyPart;
}
 
Example 8
Source File: CallableQuery.java    From chronos with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@CoverageIgnore
private void sendEmail(MailInfo info, DataSource attachment, String body, JobSpec currJob) {
  Message message = new MimeMessage(session);
  List<Address> to = new ArrayList<>();
  try {
    List<String> resultEmails = currJob.getResultEmail();
    if (resultEmails.size() == 0) {
      return;
    }
    message.setFrom(new InternetAddress(info.from));
    for (String s : resultEmails) {
      for (Address ad : InternetAddress.parse(s)) {
        to.add(ad);
      }
    }
    message.setRecipients(Message.RecipientType.TO,
      to.toArray(new Address[]{}));
    message.setSubject("Chronos " + currJob.getName());
    Multipart multipart = new MimeMultipart();
    {
      BodyPart messageBodyPart = new MimeBodyPart();
      messageBodyPart.setContent(body, "text/html");
      multipart.addBodyPart(messageBodyPart);
    }
    {
      MimeBodyPart attachmentPart = new MimeBodyPart();
      attachmentPart.setDataHandler(new DataHandler(attachment));
      String fileName = String.format("%s-%s.tsv",
          currJob.getName(), DT_FMT.print(plannedJob.getReplaceTime()));
      attachmentPart.setFileName(fileName);
      multipart.addBodyPart(attachmentPart);
    }
    message.setContent(multipart);
    Transport.send(message);
    LOG.info("Sent email to: " + to);
  } catch (MessagingException e) {
    throw new RuntimeException(e);
  }
}
 
Example 9
Source File: MailManager.java    From entando-components with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Add the attachments to the Multipart container.
 * @param attachmentFiles The attachments mapped as fileName/filePath.
 * @param multiPart The Multipart container.
 * @throws MessagingException In case of errors adding the attachments.
 */
protected void addAttachments(Properties attachmentFiles, Multipart multiPart) throws MessagingException {
	Iterator filesIter = attachmentFiles.entrySet().iterator();
	while (filesIter.hasNext()) {
		Entry fileEntry = (Entry) filesIter.next();
		MimeBodyPart fileBodyPart = new MimeBodyPart();
		DataSource dataSource = new FileDataSource((String) fileEntry.getValue());
		fileBodyPart.setDataHandler(new DataHandler(dataSource));
		fileBodyPart.setFileName((String) fileEntry.getKey());
		multiPart.addBodyPart(fileBodyPart);
	}
}
 
Example 10
Source File: AttachmentMailerImpl.java    From kfs with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Construct and a send mime email message from an Attachment Mail Message.
 *
 * @param message the Attachement Mail Message
 * @throws MessagingException
 */
@Override
public void sendEmail(AttachmentMailMessage message) throws MessagingException {
    // Construct a mime message from the Attachment Mail Message

    MimeMessage mimeMessage = mailSender.createMimeMessage();

    MimeBodyPart body = new MimeBodyPart();
    body.setText(message.getMessage());

    MimeBodyPart attachment = new MimeBodyPart();
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(body);
    ByteArrayDataSource ds = new ByteArrayDataSource(message.getContent(), message.getType());
    attachment.setDataHandler(new DataHandler(ds));
    attachment.setFileName(message.getFileName());
    multipart.addBodyPart(attachment);
    mimeMessage.setContent(multipart);

    MimeMailMessage mmm = new MimeMailMessage(mimeMessage);

    mmm.setTo( (String[])message.getToAddresses().toArray(new String[message.getToAddresses().size()]) );
    mmm.setBcc( (String[])message.getBccAddresses().toArray(new String[message.getBccAddresses().size()]) );
    mmm.setCc( (String[])message.getCcAddresses().toArray(new String[message.getCcAddresses().size()]) );
    mmm.setSubject(message.getSubject());
    mmm.setFrom(message.getFromAddress());

    try {
        if ( LOG.isDebugEnabled() ) {
            LOG.debug( "sendEmail() - Sending message: " + mmm.toString() );
        }
        mailSender.send(mmm.getMimeMessage());
    }
    catch (Exception e) {
        LOG.error("sendEmail() - Error sending email.", e);
        throw new RuntimeException(e);
    }
}
 
Example 11
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 12
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 attachments
 * @param wrapPart
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
private void addAttachments(File[] attachments, MimeMultipart wrapPart)
        throws MessagingException, UnsupportedEncodingException {
    if (null != attachments && attachments.length > 0) {
        for (int i = 0; i < attachments.length; i++) {
            MimeBodyPart attachmentBodyPart = new MimeBodyPart();
            DataHandler dataHandler = new DataHandler(new FileDataSource(attachments[i]));
            String fileName = dataHandler.getName();
            attachmentBodyPart.setDataHandler(dataHandler);
            // 显示指定文件名(防止文件名乱码)
            attachmentBodyPart.setFileName(MimeUtility.encodeText(fileName));
            wrapPart.addBodyPart(attachmentBodyPart);
        }
    }
}
 
Example 13
Source File: EmailHelper.java    From frostmourne with MIT License 5 votes vote down vote up
/**
 * 文件对象包装为邮件内容
 *
 * @param file 文件对象
 * @return 邮件内容对象
 * @throws MessagingException
 * @throws UnsupportedEncodingException
 */
public static MimeBodyPart wrapFile2BodyPart(File file) throws MessagingException, UnsupportedEncodingException {
    MimeBodyPart filePartBody = new MimeBodyPart();
    DataSource fileDataSource = new FileDataSource(file);
    DataHandler dataHandler = new DataHandler(fileDataSource);
    filePartBody.setDataHandler(dataHandler);
    filePartBody.setFileName(MimeUtility.encodeText(file.getName()));
    return filePartBody;
}
 
Example 14
Source File: GMailClient.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
private void attachQRs(Multipart multipart, QrHolder[] attachmentData) throws Exception {
    for (QrHolder qrHolder : attachmentData) {
        MimeBodyPart attachmentsPart = new MimeBodyPart();
        ByteArrayDataSource source = new ByteArrayDataSource(qrHolder.data, "image/jpeg");
        attachmentsPart.setDataHandler(new DataHandler(source));
        attachmentsPart.setFileName(qrHolder.makeQRFilename());
        multipart.addBodyPart(attachmentsPart);
    }
}
 
Example 15
Source File: sendHtmlMail.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public static void main(String[] args) throws Exception {
	Properties prop = new Properties();
	prop.setProperty("mail.debug", "true");
	prop.setProperty("mail.host", MAIL_SERVER_HOST);
	prop.setProperty("mail.transport.protocol", "smtp");
	prop.setProperty("mail.smtp.auth", "true");

	// 1、创建session
	Session session = Session.getInstance(prop);
	Transport ts = null;

	// 2、通过session得到transport对象
	ts = session.getTransport();

	// 3、连上邮件服务器
	ts.connect(MAIL_SERVER_HOST, USER, PASSWORD);

	// 4、创建邮件
	MimeMessage message = new MimeMessage(session);

	// 邮件消息头
	message.setFrom(new InternetAddress(MAIL_FROM)); // 邮件的发件人
	message.setRecipient(Message.RecipientType.TO, new InternetAddress(MAIL_TO)); // 邮件的收件人
	message.setRecipient(Message.RecipientType.CC, new InternetAddress(MAIL_CC)); // 邮件的抄送人
	message.setRecipient(Message.RecipientType.BCC, new InternetAddress(MAIL_BCC)); // 邮件的密送人
	message.setSubject("测试HTML邮件"); // 邮件的标题

	String htmlContent = "<h1>Hello</h1>" + "<p>显示图片<img src='cid:abc.jpg'>1.jpg</p>";
	MimeBodyPart text = new MimeBodyPart();
	text.setContent(htmlContent, "text/html;charset=UTF-8");
	MimeBodyPart image = new MimeBodyPart();
	DataHandler dh = new DataHandler(new FileDataSource("D:\\05_Datas\\图库\\吉他少年背影.png"));
	image.setDataHandler(dh);
	image.setContentID("abc.jpg");

	// 描述数据关系
	MimeMultipart mm = new MimeMultipart();
	mm.addBodyPart(text);
	mm.addBodyPart(image);
	mm.setSubType("related");
	message.setContent(mm);
	message.saveChanges();

	// 5、发送邮件
	ts.sendMessage(message, message.getAllRecipients());
	ts.close();
}
 
Example 16
Source File: JplagClient.java    From jplag with GNU General Public License v3.0 4 votes vote down vote up
public String invoke_compareSource(String[] args) {
	// package a zipped file
	File file = new File(args[0]);
	//		MimeMultipart result=null;
	String result = null;

	System.out.println("Entering try block...");

	try {
		FileDataSource fds = new FileDataSource(file);

		// Construct a MimeBodyPart

		// Add Part on the .....

		MimeMultipart mmp = new MimeMultipart();
		MimeBodyPart mbp = new MimeBodyPart();
		mbp.setDataHandler(new DataHandler(fds));
		mbp.setFileName(file.getName());

		mmp.addBodyPart(mbp);

		System.out.println("Creating Option object...");

		// Prepare Options

		/*
		 * String username= "mo"; boolean use_root_dir =true ; String
		 * directories =""; int sensitivity_of_comparison =9 ; boolean
		 * use_basecode =false ; String basecode_dir =""; boolean
		 * read_subdirs =true ; boolean clustering_on =true ; String
		 * clustertype="max"; int store_matches = 30 ; int store_in_percent
		 * = 10 ; boolean exclude_file_on = false ; String excluded_file =
		 * ""; boolean include_file_on=false ; String included_file ="";
		 * boolean suffixes_on =true ; String suffixes = "java";
		 */
		String language = "java12";
		String title = "Server test";

		Option option = new Option(args[0],/* username, */
		null, 0, null, true, "avr", "50", null, null, language, title, "en");
		// running Jplag

		System.out.println("Calling compareSource...");

		result = this.stub.compareSource(option, mmp);
		System.out.println("\n" + "############# JPLAG-RESULT :REQUEST =compareSource()  ##############" + "\nResult= " + result);

	} catch (Exception ex) {
		if (ex instanceof JPlagException) {
			JPlagException jex = (JPlagException) ex;
			System.out.println(jex.getExceptionType());
			System.out.println(jex.getDescription());
			System.out.println(jex.getRepair());
		}
		ex.printStackTrace();
	}
	return result; //extractPart(result, args[1]);
}
 
Example 17
Source File: GreenMailUtil.java    From greenmail with Apache License 2.0 4 votes vote down vote up
/**
 * Create new multipart with a text part and an attachment
 *
 * @param msg         Message text
 * @param attachment  Attachment data
 * @param contentType MIME content type of body
 * @param filename    File name of the attachment
 * @param description Description of the attachment
 * @return New multipart
 */
public static MimeMultipart createMultipartWithAttachment(String msg, final byte[] attachment, final String contentType,
                                                           final String filename, String description) {
    try {
        MimeMultipart multiPart = new MimeMultipart();

        MimeBodyPart textPart = new MimeBodyPart();
        multiPart.addBodyPart(textPart);
        textPart.setText(msg);

        MimeBodyPart binaryPart = new MimeBodyPart();
        multiPart.addBodyPart(binaryPart);

        DataSource ds = new DataSource() {
            @Override
            public InputStream getInputStream() {
                return new ByteArrayInputStream(attachment);
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
                byteStream.write(attachment);
                return byteStream;
            }

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

            @Override
            public String getName() {
                return filename;
            }
        };
        binaryPart.setDataHandler(new DataHandler(ds));
        binaryPart.setFileName(filename);
        binaryPart.setDescription(description);
        return multiPart;
    } catch (MessagingException e) {
        throw new IllegalArgumentException("Can not create multipart message with attachment", e);
    }
}
 
Example 18
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);
}
 
Example 19
Source File: MimeMessageHelper.java    From spring4-understanding with Apache License 2.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 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);
}