최근에 마이크로소프트 exchange 메일을 mht파일로 만드는 작업이 있었다.
마이크로소프트에서 공식적으로 알려준 코드에는 아래 처럼 문제가 있었다.
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-에-이미지-첨부
'IT 관련 정리' 카테고리의 다른 글
[오라클 디비 프라이머리 키 Primary Key 중복]무결성 제약 조건 위배 해결방법 시퀀스 조회 및 수정 (0) | 2023.04.05 |
---|---|
포스트맨 요청 여러개 새 탭에서 열기 (1) | 2023.01.19 |
[Spring Rest API 호출 방법] 서버 to 서버 파일 다운로드 RestTemplate 헤더 추가 및 예시 코드 (0) | 2022.12.23 |
[이클립스 오류] 맥 Ventura 13.0 업데이트 시 로케일을 인식할 수 없습니다 오류 해결법 (0) | 2022.11.10 |
[JS text 클립보드 복사] div, td 형식에서 내용 클립보드에 복사하는 법 (0) | 2022.10.27 |