Java发送邮件时标题和发件人乱码

时间:2024-01-10 12:58:56

最近碰到一个问题,Java发送邮件时,查看邮箱结果,发件人及邮件标题正文全部乱码

通过翻阅资料,原因及解决方法如下:

            // Set Subject: 头字段
message.setSubject(MimeUtility.encodeText(mail, MimeUtility.mimeCharset("gb2312"), null));
// 设置邮件发送日期
message.setSentDate(new Date());
// 设置邮件发件人名称
Address address = new InternetAddress(mailTitle, MimeUtility.encodeText(mailTitle, MimeUtility.mimeCharset("gb2312"), null));
// Set From: 头部头字段
message.setFrom(address);
// Set To: 头部头字段
message.addRecipient(Message.RecipientType.TO, new InternetAddress(toMail));// 设置邮件格式
message.setContent(str, "text/html;charset=gbk");