java mailapi中的变音字符支持

时间:2018-04-26 05:59:45

标签: java javamail

MimeBodyPart mimebodypart = new MimeBodyPart();
DataSource datasource = new FileDataSource(file);
mimebodypart.setDataHandler(new DataHandler(datasource));
//mimebodypart.setFileName(MimeUtility.encodeText(file.getName(), "UTF-8", null));
mimebodypart.setFileName(file.getName());

在上面的代码中,我的文件名为PDFtestöäüßÜÄÖtestDEV2 - 13.06.2016.tiff 附件将以untitled_000000456.tiff的形式出现 < 000000456>是一个随机数字出现。

使用stöäüßÜÄ工作正常,但当字符串长一个字符,即 e stöäüßÜÄÖ时,它无效。

此外,öäüßÜÄÖöäüßÜÄÖ和testtesttest(任何长度)都在工作。

有谁可以请指出我做错了什么?

我正在使用JavaMail API JAR»1.5.6

https://mvnrepository.com/artifact/javax.mail/javax.mail-api/1.5.6

java Version 1.8

修改

在一些标题之后,我能够获得正确的文件名,但缺少消息体。这是更新的代码。

try {
    Message message = new MimeMessage(Session.getInstance(System.getProperties()));
    message.setHeader("MIME-Version", "1.0");
    message.setHeader("Content-Disposition", "attachment; filename=\""+ file.getName() +"\""); 
    //file.getName() returns PDF "testöäüßÜÄÖtest DEV2 - 13.06.2016.tiff"
    message.saveChanges();

    String email_subject = "subject";
    message.setSubject(email_subject, "UTF-8", null));
    message.setSentDate(new Date());

    MimeBodyPart content = new MimeBodyPart();
    String msg_body = "Message body";
    content.setContent("<p style=font-style:italic;font-size:20px>"+ msg_body +" </p>", "text/html;charset=UTF-8");
    Multipart multipart = new MimeMultipart();
    multipart.addBodyPart(content);



    MimeBodyPart attachment = new MimeBodyPart();
    DataSource source = new FileDataSource(file); //file is of type File 
    attachment.setDataHandler(new DataHandler(source));
    multipart.addBodyPart(attachment);

    message.setContent(multipart);
    message.getFlags().add(Flags.Flag.DRAFT);

    OutputStream out = new FileOutputStream(fileName);
    //fileName.getName() returns PDF testöäüßÜÄÖtest DEV2 - 13.06.2016.eml
    message.writeTo(out);
    out.close();
    out=null;
}catch (Exception ex) {
    ex.printStackTrace();
}

身体缺失,我做错了什么?

1 个答案:

答案 0 :(得分:1)

尝试这个更简单,更正确的版本:

Message message = new MimeMessage(Session.getInstance(System.getProperties()));

String email_subject = "subject";
message.setSubject(email_subject, "UTF-8");
message.setSentDate(new Date());

MimeBodyPart content = new MimeBodyPart();
String msg_body = "Message body";
content.setText("<p style=font-style:italic;font-size:20px>"+ msg_body +" </p>", "UTF-8", "html");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(content);

MimeBodyPart attachment = new MimeBodyPart();
attachment.attachFile(file);
multipart.addBodyPart(attachment);

message.setContent(multipart);
message.setFlags(new Flags(Flags.Flag.DRAFT), true);

OutputStream out = new FileOutputStream(fileName);
message.saveChanges();
message.writeTo(out);
out.close();

如果这不起作用,请发布fileName引用的文件内容。