*代码来源gpt
XSSFWorkbook wb = new XSSFWorkbook();
//省略excel生成过程
//解决文件名乱码
System.getProperties().setProperty("mail.mime.splitlongparameters", "false");
try {
// 结果流
ByteArrayOutputStream bos = new ByteArrayOutputStream();
wb.write(bos);
//InputStream is = new ByteArrayInputStream(bos.toByteArray());
byte[] excelBytes = bos.toByteArray();
// Email configuration
String to = "接收者@qq.com";
String from = "发送者@qq.com";
String host = "smtp.qq.com"; //发送邮箱编码
String username = "发送者@qq.com";
String password = "授权码";
Properties properties = System.getProperties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", "587");
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
Session session = Session.getDefaultInstance(properties, new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
// Create a MIME message
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("邮件标题");
// Create the Excel attachment
MimeBodyPart excelAttachment = new MimeBodyPart();
String encodedFileName = MimeUtility.encodeText("附件名称.xlsx", "UTF-8", "B");
//excelAttachment.attachFile(encodedFileName); // You can change the file name(存在多个excel附件,名称乱码问题)
excelAttachment.setFileName(encodedFileName);//此代码,测试无上述问题
excelAttachment.setDataHandler(new DataHandler(new ByteArrayDataSource(excelBytes, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")));
// Create the multipart message
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(excelAttachment);
message.setContent(multipart);
// Send the email
Transport.send(message);
System.out.println("Email sent successfully.");
} catch (Exception e) {
e.printStackTrace();
}