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

The following examples show how to use javax.mail.internet.MimeBodyPart#setContentID() . 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: 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 2
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 3
Source File: JavaMailAttachmentHandler.java    From ogham with Apache License 2.0 5 votes vote down vote up
/**
 * Add an attachment on the mime message.
 * 
 * @param multipart
 *            the mime message to fill
 * @param attachment
 *            the attachment to add
 * @throws AttachmentResourceHandlerException
 *             when the attachment couldn't be attached
 */
public void addAttachment(Multipart multipart, Attachment attachment) throws AttachmentResourceHandlerException {
	try {
		MimeBodyPart part = new MimeBodyPart();
		part.setFileName(attachment.getResource().getName());
		part.setDisposition(attachment.getDisposition());
		part.setDescription(attachment.getDescription());
		part.setContentID(attachment.getContentId());
		attachmentContentHandler.setData(part, attachment.getResource(), attachment);
		multipart.addBodyPart(part);
	} catch (MessagingException e) {
		throw new AttachmentResourceHandlerException("Failed to attach " + attachment.getResource().getName(), attachment, e);
	}
}
 
Example 4
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 5
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 6
Source File: EmailFormatterOutboud.java    From matrix-appservice-email with GNU Affero General Public License v3.0 4 votes vote down vote up
private MimeMessage makeEmail(TokenData data, _EmailTemplate template, List<_BridgeMessageContent> contents, boolean allowReply) throws MessagingException, IOException {
    MimeMultipart body = new MimeMultipart();
    body.setSubType("alternative");

    for (_BridgeMessageContent content : contents) {
        MimeMultipart contentBody = new MimeMultipart();
        contentBody.setSubType("related");

        Optional<_EmailTemplateContent> contentTemplateOpt = template.getContent(content.getMime());
        if (!contentTemplateOpt.isPresent()) {
            continue;
        }

        _EmailTemplateContent contentTemplate = contentTemplateOpt.get();
        contentBody.addBodyPart(makeBodyPart(data, contentTemplate, content));

        if (contentTemplate.getContent().contains(EmailTemplateToken.SenderAvatar.getToken()) &&
                data.getSenderAvatar() != null && data.getSenderAvatar().isValid()) {
            log.info("Adding avatar for sender");

            MimeBodyPart avatarBp = new MimeBodyPart();
            _MatrixContent avatar = data.getSenderAvatar();
            String filename = avatar.getFilename()
                    .map(f -> f.replace("image/", "").replace("\"", ""))
                    .filter(StringUtils::isNotBlank)
                    .orElseGet(() -> "unknown." + avatar.getType());

            avatarBp.setContent(avatar.getData(), avatar.getType());
            avatarBp.setContentID("<" + senderAvatarId + ">");
            avatarBp.setDisposition("inline; filename=\"" + filename + "\"; size=" + avatar.getData().length + ";");

            contentBody.addBodyPart(avatarBp);
        }

        MimeBodyPart part = new MimeBodyPart();
        part.setContent(contentBody);

        body.addBodyPart(part);
    }

    return makeEmail(data, template, body, allowReply);
}
 
Example 7
Source File: SesSendNotificationHandler.java    From smart-security-camera with GNU General Public License v3.0 4 votes vote down vote up
public Parameters handleRequest(Parameters parameters, Context context) {
	context.getLogger().log("Input Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	try {
		Session session = Session.getDefaultInstance(new Properties());
		MimeMessage message = new MimeMessage(session);
		message.setSubject(EMAIL_SUBJECT, "UTF-8");
		message.setFrom(new InternetAddress(System.getenv("EMAIL_FROM")));
		message.setReplyTo(new Address[] { new InternetAddress(System.getenv("EMAIL_FROM")) });
		message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(System.getenv("EMAIL_RECIPIENT")));

		MimeBodyPart wrap = new MimeBodyPart();
		MimeMultipart cover = new MimeMultipart("alternative");
		MimeBodyPart html = new MimeBodyPart();
		cover.addBodyPart(html);
		wrap.setContent(cover);
		MimeMultipart content = new MimeMultipart("related");
		message.setContent(content);
		content.addBodyPart(wrap);

		URL attachmentURL = new URL(
				System.getenv("S3_URL_PREFIX") + parameters.getS3Bucket() + '/' + parameters.getS3Key());

		StringBuilder sb = new StringBuilder();
		String id = UUID.randomUUID().toString();
		sb.append("<img src=\"cid:");
		sb.append(id);
		sb.append("\" alt=\"ATTACHMENT\"/>\n");

		MimeBodyPart attachment = new MimeBodyPart();
		DataSource fds = new URLDataSource(attachmentURL);
		attachment.setDataHandler(new DataHandler(fds));

		attachment.setContentID("<" + id + ">");
		attachment.setDisposition("attachment");

		attachment.setFileName(fds.getName());
		content.addBodyPart(attachment);

		String prettyPrintLabels = parameters.getRekognitionLabels().toString();
		prettyPrintLabels = prettyPrintLabels.replace("{", "").replace("}", "");
		prettyPrintLabels = prettyPrintLabels.replace(",", "<br>");
		html.setContent("<html><body><h2>Uploaded Filename : " + parameters.getS3Key().replace("upload/", "")
				+ "</h2><p><i>Step Function ID : " + parameters.getStepFunctionID()
				+ "</i></p><p><b>Detected Labels/Confidence</b><br><br>" + prettyPrintLabels + "</p>" + sb
				+ "</body></html>", "text/html");

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		message.writeTo(outputStream);
		RawMessage rawMessage = new RawMessage(ByteBuffer.wrap(outputStream.toByteArray()));
		SendRawEmailRequest rawEmailRequest = new SendRawEmailRequest(rawMessage);

		AmazonSimpleEmailService client = AmazonSimpleEmailServiceClientBuilder.defaultClient();
		client.sendRawEmail(rawEmailRequest);

	// Convert Checked Exceptions to RuntimeExceptions to ensure that
	// they get picked up by the Step Function infrastructure
	} catch (MessagingException | IOException e) {
		throw new RuntimeException("Error in [" + context.getFunctionName() + "]", e);
	}

	context.getLogger().log("Output Function [" + context.getFunctionName() + "], Parameters [" + parameters + "]");

	return parameters;
}
 
Example 8
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 9
Source File: EmailNotificationService.java    From athenz with Apache License 2.0 4 votes vote down vote up
private MimeMessage getMimeMessage(String subject, String body, Collection<String> recipients, String from, byte[] logoImage) throws MessagingException {
    Session session = Session.getDefaultInstance(new Properties());

    // Create a new MimeMessage object.
    MimeMessage message = new MimeMessage(session);

    // Add subject, from and to lines.
    message.setSubject(subject, CHARSET_UTF_8);
    message.setFrom(new InternetAddress(from));
    message.setRecipients(javax.mail.Message.RecipientType.BCC, InternetAddress.parse(String.join(",", recipients)));

    // Create a multipart/alternative child container.
    MimeMultipart msgBody = new MimeMultipart("alternative");

    // Create a wrapper for the HTML and text parts.
    MimeBodyPart wrap = new MimeBodyPart();

    // Set the text part.
    MimeBodyPart textPart = new MimeBodyPart();
    textPart.setContent(body, "text/plain; charset=" + CHARSET_UTF_8);

    // Set the HTML part.
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(body, "text/html; charset=" + CHARSET_UTF_8);

    // Add the text and HTML parts to the child container.
    msgBody.addBodyPart(textPart);
    msgBody.addBodyPart(htmlPart);

    // Add the child container to the wrapper object.
    wrap.setContent(msgBody);

    // Create a multipart/mixed parent container.
    MimeMultipart msgParent = new MimeMultipart("related");

    // Add the multipart/alternative part to the message.
    msgParent.addBodyPart(wrap);

    // Add the parent container to the message.
    message.setContent(msgParent);

    if (logoImage != null) {
        MimeBodyPart logo = new MimeBodyPart();
        logo.setContent(logoImage, "image/png");
        logo.setContentID(HTML_LOGO_CID_PLACEHOLDER);
        logo.setDisposition(MimeBodyPart.INLINE);
        // Add the attachment to the message.
        msgParent.addBodyPart(logo);
    }

    return message;
}
 
Example 10
Source File: MailSender.java    From che with Eclipse Public License 2.0 4 votes vote down vote up
public void sendMail(EmailBean emailBean) throws SendMailException {
  File tempDir = null;
  try {
    MimeMessage message = new MimeMessage(mailSessionProvider.get());
    Multipart contentPart = new MimeMultipart();

    MimeBodyPart bodyPart = new MimeBodyPart();
    bodyPart.setText(emailBean.getBody(), "UTF-8", getSubType(emailBean.getMimeType()));
    contentPart.addBodyPart(bodyPart);

    if (emailBean.getAttachments() != null) {
      tempDir = Files.createTempDir();
      for (Attachment attachment : emailBean.getAttachments()) {
        // Create attachment file in temporary directory
        byte[] attachmentContent = Base64.getDecoder().decode(attachment.getContent());
        File attachmentFile = new File(tempDir, attachment.getFileName());
        Files.write(attachmentContent, attachmentFile);

        // Attach the attachment file to email
        MimeBodyPart attachmentPart = new MimeBodyPart();
        attachmentPart.attachFile(attachmentFile);
        attachmentPart.setContentID("<" + attachment.getContentId() + ">");
        contentPart.addBodyPart(attachmentPart);
      }
    }

    message.setContent(contentPart);
    message.setSubject(emailBean.getSubject(), "UTF-8");
    message.setFrom(new InternetAddress(emailBean.getFrom(), true));
    message.setSentDate(new Date());
    message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(emailBean.getTo()));

    if (emailBean.getReplyTo() != null) {
      message.setReplyTo(InternetAddress.parse(emailBean.getReplyTo()));
    }
    LOG.info(
        "Sending from {} to {} with subject {}",
        emailBean.getFrom(),
        emailBean.getTo(),
        emailBean.getSubject());

    Transport.send(message);
    LOG.debug("Mail sent");
  } catch (Exception e) {
    LOG.error(e.getLocalizedMessage());
    throw new SendMailException(e.getLocalizedMessage(), e);
  } finally {
    if (tempDir != null) {
      try {
        FileUtils.deleteDirectory(tempDir);
      } catch (IOException exception) {
        LOG.error(exception.getMessage());
      }
    }
  }
}