java eml 附件_向EML文件追加附件的Java实现

这篇博客介绍了如何使用Java处理EML文件,特别是当EML文件已有附件时,如何安全地追加新的附件而不破坏源文件。通过Apache Commons Email库,实现了读取、追加附件和保存更新后的EML文件的功能。
摘要由CSDN通过智能技术生成

说明

之前在网上也找了一下该需求的实现,但是后面测试发现几乎全部都只能够对没有附件的eml文件进行追加,如果已近带了附件的eml文件在执行时源文件会被破坏掉。所有在此写下可以附件追加代码。

代码

import org.apache.commons.mail.util.MimeMessageUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import utils.ParseEmailUtil;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.*;

import javax.mail.internet.*;

import java.io.*;

import java.util.List;

/**

* Created by jacob on 2016/11/28.

*/

public class AddAttachemnt2Eml {

private static final Logger logger = LoggerFactory.getLogger(AddAttachemnt2Eml.class );

public static void add(String emlPath, String writeto, List attachments) {

Properties props = new Properties();

Session session = Session.getDefaulInstance(props, null);

InputStream inMsg;

inMsg = new FileInputStream(emlPath);

Message message = new MimeMessage(session, inMsg);

OutputStream os = null;

try {

os = new FileOutputStream(writeto+File.separator+new File(emlPath).getName());

// ParseEmailUtil.getContentHtml(emlPath);

// Message message = ParseEmailUtil.getMessage();

for(File filename : attachments){

message = attachment(message,filename);

}

new File(emlPath).delete();

message.saveChanges();

message.writeTo(os);

}catch (Exception e){

logger.error(String.format("failed to add attachment to eml file %s",emlPath ),e);

}finally {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

private static Message attachment (Message message,File filename) {

try{

Multipart mp = (Multipart) message.getContent();

MimeBodyPart attachment = new MimeBodyPart();

DataSource source = new FileDataSource(filename);

attachment.setDataHandler(new DataHandler(source));

attachment.setFileName(filename.getName());

if (mp.getContentType().equalsIgnoreCase("multipart/alternative")) { //原始文件已近有附件的情况直接追加即可

mp.addBodyPart(attachment);

message.setContent(mp);

} else { //原始文件不带附件需要将之前的正文与新加附件并列

Multipart allPart = new MimeMultipart();

MimeBodyPart contentPart = new MimeBodyPart();

contentPart.setContent(mp);

allPart.addBodyPart(contentPart);

allPart.addBodyPart(attachment);

message.setContent(allPart);

}

source.getInputStream().close();

}catch (javax.mail.MessagingException e){

logger.error(String.format("add attachment %s fail",filename.getAbsolutePath() ),e);

}catch (IOException e2){

logger.error(String.format("add attachment %s fail", filename),e2);

}

return message;

}

}

注:manve依赖:

org.apache.commons

commons-email

1.4

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值