package com.storlead.mail.util;

import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Part;
import java.io.InputStream;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-05-30 18:05
 */
public class MailFormatPartUtil {

    public static void saveAttachment(BodyPart bodyPart) throws Exception {
        String fileName = bodyPart.getFileName();
        int size = bodyPart.getSize();
        InputStream is = bodyPart.getInputStream();
//        File file = new File("attachments/" + fileName); // 存储附件的文件夹路径
//        try (FileOutputStream fos = new FileOutputStream(file)) {
//            byte[] buffer = new byte[4096];
//            int bytesRead;
//            while ((bytesRead = is.read(buffer)) != -1) {
//                fos.write(buffer, 0, bytesRead);
//            }
//        }
        System.out.println("Saved attachment: " + fileName);
    }


    public static String parseMultipart(Multipart multipart) throws Exception {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < multipart.getCount(); i++) {
            BodyPart bodyPart = multipart.getBodyPart(i);
            if (bodyPart.isMimeType("text/plain")) {
                stringBuilder.append(bodyPart.getContent());
            } else if (bodyPart.isMimeType("text/html")) {
                stringBuilder.append(bodyPart.getContent());
            } else if (bodyPart.isMimeType("multipart/alternative")) {
                parseMultipart((Multipart) bodyPart.getContent());
            } else if (bodyPart.isMimeType("multipart/*")) {
                parseMultipart((Multipart) bodyPart.getContent());
            }else if (Part.ATTACHMENT.equalsIgnoreCase(bodyPart.getDisposition())) {
                saveAttachment(bodyPart);
            }
        }
        return stringBuilder.toString();
    }
}
