OutputStreamWriter generates CSV, and JavaMail sends garbled email title attachments

Solution to garbled attachments:

// 这里使用ByteArrayOutputStream是因为长度是自动拓展, 而byte[]必须指定大小
var os = new ByteArrayOutputStream();
// 只需要在这里指定charsetName为指定的编码格式即可,我这里是因为用Office打开csv附件
// Office的excel默认为GB2312,具体那个软件用啥编码格式可以自行百度,保持一致就可以了
Writer writer = new OutputStreamWriter(os, "GB2312")

The email title is garbled, because the title is too long, don’t divide it, so it will be garbled

It's like saying that a title has 100 bytes, but if the 80th byte is divided, it will not form a word, and it will be displayed in garbled characters! ! !

Solution to the title: Add this code to the main method of the startup class

// 设置邮件标题过长不用分割
System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
// 设置邮件编码
System.getProperties().setProperty("mail.mime.charset", "UTF-8");

The content of the mail may be garbled, set the character encoding format

// 主要从以下两个类去考虑解决乱码问题,详细的可以自行百度
MimeMessage mimeMessage = null;
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, CharsetUtil.UTF_8);

Reference link 1
Reference link 2

Guess you like

Origin blog.csdn.net/qq_42071369/article/details/124273087