首先引入依赖,生成二维码用zxing的
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
生成二维码,这里返回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标签
<p><img src='cid:pic'></p>
最后把二维码图片通过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);