gpt4 book ai didi

java - 如何将邮件附件保存为utf8

转载 作者:行者123 更新时间:2023-12-01 14:45:20 25 4
gpt4 key购买 nike

我需要以 utf8 格式保存电子邮件附件。我尝试了这段代码,但仍然缺少一些字符:

public static void main(String args[]) throws Exception {
File emlFile = new File("example.eml");

InputStream source;

source = new FileInputStream(emlFile);

MimeMessage message = new MimeMessage(null, source);

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

for (int x = 0; x < multipart.getCount(); x++) {

BodyPart bodyPart = multipart.getBodyPart(x);
String disposition = bodyPart.getDisposition();

if (disposition != null && (disposition.equals(BodyPart.ATTACHMENT))) {
System.out.println("Mail have some attachment : ");

DataHandler handler = bodyPart.getDataHandler();
System.out.println("file name : " + handler.getName());


//start reading inpustream from attachment
InputStream is = bodyPart.getInputStream();
File f = new File(bodyPart.getFileName());
OutputStreamWriter sout = new OutputStreamWriter(new FileOutputStream(f), "UTF8");
BufferedWriter buff_out = new BufferedWriter(sout);
int bytesRead;
while ((bytesRead = is.read()) != -1) {
buff_out.write(bytesRead);
}
buff_out.close();

}
}
}

最佳答案

您正在从附件中读取字节,忽略任何编码,并将字符输出到文件。您很可能想要选择其中之一,而不是混合两者。

如果附件包含原始字节,则对输出进行 UTF 编码没有意义,您可以使用原始流。

如果它包含文本,您还需要将附件作为文本而不是原始字节读取,并使用编码进行读取和写入。

在后一种情况下,类似;

InputStream is = bodyPart.getInputStream();
InputStreamReader sin = new InputStreamReader(is,
"UTF8"); // <-- attachment charset

File f = new File(bodyPart.getFileName());
OutputStreamWriter sout = new OutputStreamWriter(new FileOutputStream(f), "UTF8");
BufferedReader buff_in = new BufferedReader(sin);
BufferedWriter buff_out = new BufferedWriter(sout);

int charRead;
while ((charRead = buff_in.read()) != -1) {
buff_out.write(charRead);
}

buff_in.close();
buff_out.close();

关于java - 如何将邮件附件保存为utf8,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15479122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com