Springboot发送带二维码的邮件,邮件中包含二维码

首先引入依赖,生成二维码用zxing的

        
            com.google.zxing
            core
            3.3.0
        
        
            com.google.zxing
            javase
            3.3.0
        

生成二维码,这里返回OutputStream

public static ByteArrayOutputStream generateQRCodeImage(String text, int width, int height)
            throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
//        Path path = FileSystems.getDefault().getPath(filePath);
//        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "jpg", outputStream);
        return outputStream;
    }

最后把图片插入邮件中,先新建message

MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

邮件文字需要使用html语言编写,图片的位置用img标签

最后把二维码图片通过DataScource放入message中

helper.setText(text);
ByteArrayOutputStream outputStream = QRCodeUtils.generateQRCodeImage(getReportUrl(formId), 350, 350);
DataSource aAttachment = new ByteArrayDataSource(outputStream.toByteArray(), "application/octet-stream");

helper.addInline("pic", aAttachment);

你可能感兴趣的:(Springboot发送带二维码的邮件,邮件中包含二维码)