我想将内嵌位图(在代码内生成)添加到要通过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("[email protected]"));
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:\n\n"
+ urlWithToken
+ "\n\nRegards,\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对象,然后将其添加到消息的正文中,但是我认为可能会有更直接,更有效的方法。
“雅加达邮件常见问题解答是您最好的资源。参见How do I send HTML mail that includes images?。描述了3个选择:
<img src="data:image/jpeg;base64,base64-encoded-data-here" />
从代码中可以看出,问题是我将文本添加到多部分中,然后是图像(有效地覆盖了文本),然后将多部分分配给了消息。解决方法是使用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! \n\nPlease proceed by scanning the QR code provided using the Workside application available in the Google Play store.\n\n\n"
+ "Regards,\n\nThe 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);