首先引入依賴,生成二維碼用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標(biāo)簽
<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);