Java邮件附件乱码

Mark一下
有两个地方需要处理

全局的设置

static {
        System.setProperty("mail.mime.splitlongparameters", "false");
        System.setProperty("mail.mime.charset", "UTF-8");
    }

文件名处理

//编码处理
String filename = MimeUtility.encodeText(attachment.getName());
//去掉换行和回车
 filename = filename.replaceAll("\r", "").replaceAll("\n", "");

具体可以进源码查看

// Set the Content-Disposition "filename" parameter
    String s = part.getHeader("Content-Disposition", null);
    ContentDisposition cd = 
        new ContentDisposition(s == null ? Part.ATTACHMENT : s);
    // ensure that the filename is encoded if necessary
    String charset = MimeUtility.getDefaultMIMECharset();
    ParameterList p = cd.getParameterList();
    if (p == null) {
        p = new ParameterList();
        cd.setParameterList(p);
    }
    if (encodeFileName)
        p.setLiteral("filename", name);
    else
        p.set("filename", name, charset);
    part.setHeader("Content-Disposition", cd.toString());

你可能感兴趣的:(Java邮件附件乱码)