【JavaMail开发】使javamail-1.4.2 发送邮件时中文附件乱码或显示"??"的解决办法

时间:2022-09-24 09:29:37

使javamail-1.4.2 发送邮件时中文附件乱码或显示”??”的解决办法

首先需要导入的jar包 :

1. mail-1.4.1.jar 记得不是 javax.mail.jar

代码如下:

public class SendEmail {
public static final String user = "xxxxxxxxx@163.com";// 发送邮件邮箱
public static final String pwd = "***************";// 发送邮件邮箱密码
public static final String smtp = "smtp.163.com";// 简单邮件传输协议
public static void main(String[] args) {
List<String> recipients = new ArrayList<String>();// 收件人列表
String recipient = "xxxxxx@sina.com";// 收件人邮箱
recipients.add(recipient);
List<File> FileList = new ArrayList<File>();// 附件列表
File file = new File("D:\\新建 360压缩 ZIP 文件.zip");
FileList.add(file);
String title = "邮件主题";
String username = "发送邮件人";
String text = "邮件文本";
try {
Properties props = System.getProperties();
props.put("mail.smtp.host", smtp);// 这里默认使用163邮箱
Session session = null;
if (user != null && pwd != null) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.user", user);
props.put("mail.smtp.password", pwd);

} else {
props.put("mail.smtp.auth", "false");
}
session = Session.getInstance(props, new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, pwd);
}
});
SMTPMessage message = new SMTPMessage(session);
message.setSubject(title);
message.setFrom(new InternetAddress(user, username));
int receiverCount = recipients.size();
if (receiverCount > 0) {
InternetAddress[] address = new InternetAddress[receiverCount];
for (int i = 0; i < receiverCount; i++) {
address[i] = new InternetAddress((String) recipients.get(i));
}
message.addRecipients(Message.RecipientType.TO, address);
}

MimeMultipart multi = new MimeMultipart();
BodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(text);
multi.addBodyPart(textBodyPart);
if (FileList != null) {
for (int i = 0; i < FileList.size(); i++) {
File f = (File) FileList.get(i);
FileDataSource fds = new FileDataSource(f);
BodyPart fileBodyPart = new MimeBodyPart();
fileBodyPart.setDataHandler(new DataHandler(fds));
fileBodyPart.setFileName(MimeUtility.encodeText(f.getName()));// 如果附件有中文通过转换没有问题了
multi.addBodyPart(fileBodyPart);
}
}
message.setContent(multi);
message.setSentDate(new Date());
Transport.send(message);
System.out.println("发送成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
}

最终效果如下 可正常显示中文附件名称

【JavaMail开发】使javamail-1.4.2 发送邮件时中文附件乱码或显示"??"的解决办法

注意事项

  1. 虽然 mail-1.4.1.jar 和 javax.mail.jar 这两个包基本功能都一样 , 但是使用后者时发送附件总出现问题 ,我是测了半天才发现的这个问题 .
  2. 以下代码要特别注意:
    fileBodyPart.setFileName(MimeUtility.encodeText(f.getName()));