说明
之前在网上也找了一下该需求的实现,但是后面测试发现几乎全部都只能够对没有附件的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<File> 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依赖:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-email</artifactId>
<version>1.4</version>
</dependency>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。