是否可以将内联位图对象添加到通过JavaMail发送的电子邮件的正文中?



我想添加一个内联位图(在代码中生成(到通过Android中的JavaMail发送的电子邮件中。以下是我当前的代码:

try {
// Compose the message
// javax.mail.internet.MimeMessage class is
// mostly used for abstraction.
Message message = new MimeMessage(session);
// header field of the header.
message.setFrom(new InternetAddress("service@someone.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject("Workside Verification Service");
message.setText(
"Thank you for registering. Please click on the following link to activate your account:nn"
+ urlWithToken
+ "nnRegards,nThe Workside Team");
// Add the generated QR code bitmap here
Multipart multipart = new MimeMultipart("related");
MimeBodyPart imgPart = new MimeBodyPart();
// imageFile is the file containing the image
// TODO - pass bitmap to imageFile below
File file = new File(null);
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
mBitmapQR.compress(Bitmap.CompressFormat.PNG, 90, os);

imgPart.attachFile(imageFile);
multipart.addBodyPart(imgPart);
message.setContent(multipart);
Transport.send(message); // send Message
System.out.println("Email Sent");
} catch (MessagingException | FileNotFoundException e) {
throw new RuntimeException(e);
}

我正在考虑将位图转换为 File 对象,然后将其添加到消息正文中,但我认为可以有一种更直接、更有效的方法。

雅加达邮件常见问题解答是您最好的资源。 请参阅如何发送包含图像的 HTML 邮件?。 这描述了 3 个选择:

  1. 将图像链接到网站,我怀疑这对您有用。
  2. 内联图像<img src="data:image/jpeg;base64,base64-encoded-data-here" />
  3. 像您正在做的那样构建多部分/相关消息。

从代码中可以看出,问题是我将文本添加到多部分,然后是图像(有效地覆盖文本(,然后我将多部分分配给消息。解决方案是使用addBodyPart(text)添加文本,然后使用addBodyPart(image)。之后,我可以使用setContent(multipart)将文本和图像正确分配给电子邮件。

// Add the generated QR code bitmap here
Multipart multipart = new MimeMultipart("related");
MimeBodyPart imgPart = new MimeBodyPart();
// Set the cache path and generate the new file image
String mFilePath = mContext.getCacheDir().toString();
File file = new File(mFilePath, FILE_NAME);
OutputStream os = new BufferedOutputStream(new FileOutputStream(file));
// TITLE
message.setSubject("Workside Verification Service");
// TEXT
MimeBodyPart txtPart = new MimeBodyPart();
txtPart.setContent("Welcome to Workside! nnPlease proceed by scanning the QR code provided using the Workside application available in the Google Play store.nnn"
+ "Regards,nnThe Workside Team", "text/plain");
// ADD TEXT
multipart.addBodyPart(txtPart);
// Generate image using the QR Bitmap, and attach it
mBitmapQR.compress(Bitmap.CompressFormat.JPEG, 90, os);
imgPart.attachFile(mFilePath + FILE_NAME);
// ADD IMAGE
multipart.addBodyPart(imgPart);
message.setContent(multipart);

最新更新