Java excel文件通过流方式发送邮件

*代码来源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();
        }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值