본문 바로가기

IT 관련 정리

[JAVA 크롬에서 안 깨지는 mht파일 생성] html 파일 mht 파일로 변환, mht 파일 내부 이미지 저장 방법

반응형

최근에 마이크로소프트 exchange 메일을 mht파일로 만드는 작업이 있었다.

마이크로소프트에서 공식적으로 알려준 코드에는 아래 처럼 문제가 있었다.

(https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-export-items-by-using-ews-in-exchange)

 

1. 만들어진 mht 파일에 제목, 보낸사람, 받는 사람, 시간 등이 안나오고 딱 본문 내용만 나옴

2. 크롬과 엣지에서 mht 파일 내용이 간헐적으로 깨짐 (꽤 빈번했다.)

 

구글링을 해봤지만, 위 문제들에 대한 해결책을 찾지 못해서 

결국 메일을 html 파일로 생성 후 해당 파일을 mht 파일로 변경했고 위 문제들이 모두 해결됐다.

 

그런데 이후 발생한 다른 한 가지 문제점이 있었는데

html 내부에 이미지가 경로로 들어가 있어서 mht파일로 변환했을 때 이미지가 ?로 나왔다.

mht 파일을 어디서나 열람했을 때 내부 이미지가 나와야 해서 경로가 아닌, mht 파일 자체에 이미지를 쓰는 방법으로 찾아봤다.

 

아래는 모든 문제가 해결된 코드이다. 

 

private File createMht(File htmlFile, File mhtFile, List<String> inLineFilesPath, Item item) throws Exception {

 

Properties props = System.getProperties();

//생성된 html파일을 읽어서 String에 저장.

String template = readHTMLFile(htmlFile);

 

try {

Session session = Session.getDefaultInstance(props);

 

Message msg = new MimeMessage(session);

MimeMultipart mp = new MimeMultipart();

mp.setSubType("related");

 

MimeBodyPart mbp1 = new MimeBodyPart();

mbp1.setContent(template, "text/html; charset=UTF-8");

mp.addBodyPart(mbp1);

 

// 내부 이미지 저장하는 방법

// inLineFilesPath는 내부 이미지가 실제로 저장 돼 있는 경로.

if (inLineFilesPath.size() > 0) {

 

int size=inLineFilesPath.size();

 

MimeBodyPart[] messageBodyPart = new MimeBodyPart[size];

DataSource[] fds = new FileDataSource[size];

 

for (int i = 0; i < inLineFilesPath.size(); i++) {

//메일 아이템 이미지의 contentId를 가져온다.

Attachment attachment = item.getAttachments().getItems().get(i);

String contentId = attachment.getContentId();

 

messageBodyPart[i]= new MimeBodyPart();

fds[i] = new FileDataSource(inLineFilesPath.get(i));

 

messageBodyPart[i].setDataHandler(new DataHandler(fds[i]));

// 꼭 < > 를 추가해야된다. 안 그러면 크롬에서 이미지가 안 나옴.

messageBodyPart[i].setHeader("Content-ID", "<"+contentId+">");

mp.addBodyPart(messageBodyPart[i]);

 } 

}

 

msg.setContent(mp);

msg.writeTo(new FileOutputStream(mhtFile));

 

return mhtFile;

}

 

private String readHTMLFile(File htmlFile) throws Exception {

 

try {

BufferedReader reader = new BufferedReader(new FileReader(htmlFile.getPath()));

String htmlText = "";

String lineText = "";

while ((lineText = reader.readLine()) != null) {

htmlText += lineText + System.lineSeparator();

}

reader.close();

return htmlText;

} catch (Exception e) {

logger.info(e.getMessage());

    }

}

 

참고 : https://icksss.tistory.com/entry/javamail-로-메일-보내기body-에-이미지-첨부

 

반응형