添加附件时为setFileName需要指定utf-8的编码格式,否则解析不出来会随机给一个类似下面名称的附件名
tcmime.1882.2250.7267.bin
正确的set方式:
MimeUtility.encodeText(file.getName(), "UTF-8", "B")
下面是整个发送邮件的例子:
public static boolean sendMail(boolean haveFile,String content) {
Properties props = new Properties();
props.put("mail.smtp.host", Mail.HOST);//设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
props.put("mail.smtp.auth", "true"); //需要经过授权,也就是有户名和密码的校验,这样才能通过验证(一定要有这一条)
// 发件人的账号
props.put("mail.user", Mail.USER);
// 访问SMTP服务时需要提供的密码
props.put("mail.password", Mail.PWD);
// 构建授权信息,用于进行SMTP进行身份验证
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// 用户名、密码
String userName = props.getProperty("mail.user");
String password = props.getProperty("mail.password");
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(props,authenticator);//用props对象构建一个session
MimeMessage message = new MimeMessage(session);//用session为参数定义消息对象
try {
message.setFrom(new InternetAddress(Mail.USER));// 加载发件人地址
InternetAddress[] sendTo = new InternetAddress[Mail.TOS.length]; // 加载收件人地址
for (int i = 0; i < Mail.TOS.length; i++) {
sendTo[i] = new InternetAddress(Mail.TOS[i]);
}
message.addRecipients(Message.RecipientType.TO,sendTo);
String encodedSubject = MimeUtility.encodeText("主题", MimeUtility.mimeCharset("gb2312"), null);
message.setSubject(encodedSubject);//加载标题
Multipart multipart = new MimeMultipart();//向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
BodyPart contentPart = new MimeBodyPart();//设置邮件的文本内容
contentPart.setText(content);
multipart.addBodyPart(contentPart);
if(haveFile){//添加附件
BodyPart messageBodyPart = new MimeBodyPart();
String fileName = CommonUtils.getExcelPath() + "\\" + CommonUtils.getExcelFileName() + ".xlsx";
System.out.println("邮件附件地址:"+fileName);
File file = new File(fileName);
DataSource source = new FileDataSource(file);
messageBodyPart.setDataHandler(new DataHandler(source));//添加附件的内容
messageBodyPart.setFileName(MimeUtility.encodeText(file.getName(), "UTF-8", "B"));
multipart.addBodyPart(messageBodyPart);
}
message.setContent(multipart);//将multipart对象放到message中
message.saveChanges(); //保存邮件
Transport.send(message);// 发送邮件
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
static String HOST = ""; // smtp服务器
static String TO = ""; // 收件人地址 多个收件人用 , 分割
static String USER = ""; // 用户名
static String PWD = ""; // 163的授权码
static String[] TOS = null;
static {
Properties props = CommonUtils.getMailProperties();
HOST=props.getProperty("host");
TO=props.getProperty("to");
TOS=TO.split(",");
USER=props.getProperty("user");
PWD=props.getProperty("pwd");
}
host=smtp.exmail.qq.com
#发件人账号
user=******
#发件人密码
pwd=*******
#收件人地址多个用 ,分割
to=*******