I would like to send an email with the Java Mail API (javax.mail). The message must contain html and inside there is a reference to an image. There is a challenge, because no reference to a physical file on disk is allowed but instead I have created a base64 string (http://www.base64-image.de/step-1.php) for that image and copied that data to a static String variable.
With javax.mail I build a message of type MulitPart with two parts. The first part is the html itself and the second part is the image. The html part reference to the image via <img src="cid:image-id"/>.
Message msg = new MimeMessage(session);
Multipart multipart = new MimeMultipart("related");
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
"<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");
multipart.addBodyPart(htmlPart);
public static final String base64logo = "/9j/4AAQSkZJRgABAQEASABIAAD/4QBe…"; // ein ganz langer String erzeugt über http://www.base64-image.de/step-1.php
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] imageByte = decoder.decodeBuffer(base64logo);
InternetHeaders header = new InternetHeaders();
BodyPart imgPart=new MimeBodyPart(header, imageByte);
imgPart.setHeader("Content-ID","the-img-1");
imgPart.setDisposition(MimeBodyPart.INLINE);
multipart.addBodyPart(imgPart);
msg.setContent(multipart);
Unfortunately the image is missing in the incoming email.
When I point to the file on my disk it is working:
DataSource ds=new FileDataSource("c:/temp/image001.jpg");
imgPart.setDataHandler(new DataHandler(ds));
We are developing with Talend and we cannot reference
to external files because that would make the deployment process
more complicate.
Can you find some wrong doings in my approach?
Kind regards
Hilderich
Try putting angle braces here
imgPart.setHeader("Content-ID","<the-img-1>");
I found this answer on the comments of an old post from this blog
http://www.jroller.com/eyallupu/entry/javamail_sending_embedded_image_in
In the comment of Aravind Velayudhan Nair
It worked for me!
This has been asked before a long time ago. But I will answer this as I have faced the same issue, from my own answer here.
byte[] tile = DatatypeConverter.parseBase64Binary(base64logo);
BodyPart messageBodyPart = new MimeBodyPart();
DataHandler dataHandler = new DataHandler(new ByteArrayDataSource(tile, "image/jpeg"));
messageBodyPart.setDataHandler(dataHandler);
messageBodyPart.setHeader("Content-ID", "<the-img-1>");
multipart.addBodyPart(messageBodyPart);
msg.setContent(multipart);
Hope it will help someone.
Related
I'd like to add an inline bitmap (generated within the code) to an email to be sent via JavaMail in Android. Below is my code currently:
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:\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);
}
I was thinking of converting the bitmap to a File object and then adding it to the body of the message, but I was thinking that there could be a more straightfirward and efficient way.
The Jakarta Mail FAQ is your best resource. See How do I send HTML mail that includes images?. That describes 3 choices:
Link image to web site, which I doubt works for you.
Inline the image <img src="data:image/jpeg;base64,base64-encoded-data-here" />
Construct a multipart/related message as you are doing.
The issue, as seen from the code, was that I was adding the text to the multipart, then the image (effectively overriding the text), and then I was assigning the multipart to the message. The solution was to add the text, using addBodyPart(text), and then use addBodyPart(image). After that, I could use setContent(multipart) to properly assign the text and image to the email.
// 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);
I am trying to send inline image in a mail through java.I have byte array so I converted byte array to string using below function.
public static String getImgString(byte[] fileImg) throws IOException {
String imageString = new String(fileImg,"UTF-8");
return imageString;
}
I got an string and this string I verified through converter it displayed and image which I used.
Now I attached my image to body of mail with below code.
byte[] arr = getImageFileBytes(); // I got byte[] from this function
DataSource dataSourceImage = new ByteArrayDataSource(getImgString(arr),"image/png"");
MimeBodyPart imageBodyPart = new MimeBodyPart();
imageBodyPart.setDataHandler(new DataHandler(dataSourceImage));
I am receiving email as below.
I think there is some format I am missing in DataSource conversion or I need to add extra
data:image/png;base64 to image string??
What changes I need to do to get an image that I have in String.
Thanks in advance.
If your image data is actually in a file, you should use the attachFile method:
MimeBodyPart mbp = new MimeBodyPart();
mbp.attachFile("file.png", "image/png", "base64");
If you only have the image data in memory, you need to do something like this:
MimeBodyPart mbp = new MimeBodyPart();
ByteArrayDataSource bds = new ByteArrayDataSource(getImageFileBytes(), "image/png");
mbp.setContent(new DataHandler(bds));
Of course, if you're referencing this image from a separate html part, you'll want to make sure both are wrapped in a multipart/related part.
More information is in the JavaMail FAQ.
I am currently trying to send an email with a picture inside the mail using the Google App Engine 1.9.5. This features is availible only from the version 1.9.0 of the SDK :
Users now have the ability to embed images in emails via the Content-Id attachment header.
https://code.google.com/p/googleappengine/issues/detail?id=965
https://code.google.com/p/googleappengine/issues/detail?id=10503
Source : https://code.google.com/p/googleappengine/wiki/SdkForJavaReleaseNotes
This is my code :
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress("leo.mieulet#xxx.com", "xxx.com newsletter"));
msg.addRecipient(Message.RecipientType.TO, new InternetAddress("leo.mieulet#xx.com", "Leo Mieulet"));
msg.setSubject("Inline image test : "+new Date().getTime());
String imageCid = "graph";
DataSource ds = new ByteArrayDataSource(imageBase64, "image/png");
MimeBodyPart imagePart = new MimeBodyPart();
imagePart.setDataHandler(new DataHandler(ds));
imagePart.setFileName(imageCid + ".png");
imagePart.setHeader("Content-Type", "image/png");
imagePart.addHeader("Content-ID", "<" + imageCid + ">");
String htmlBody = "My html text... <img src=\"cid:"+imageCid+"\"> ... ends here.";
// Create alternate message body.
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent("<html><body>"+htmlBody+"</body></html>", "text/html");
final Multipart multipart = new MimeMultipart();
multipart.addBodyPart(htmlPart);
multipart.addBodyPart(imagePart);
msg.setContent(multipart);
msg.saveChanges();
Transport.send(msg);
I receive an email which looks like :
Could anyone help me with the problem ?
Based on the imageBase64 variable name, you seems to give to the ByteArrayDataSource the image already encoded in Base64. You should directly use the image byte array without Base64.encode() it.
Awesome ! ;)
If you want to display the image in pure HTML ( in app-engine doGet() context ) :
//byte[] imgContent = the content of your image
Base64 base64 = new Base64();
imgContent = base64.encode(imgContent);
resp.getWriter().write("<html><img src='data:image/png;base64,"+new String(imgContent)+"'></html>");
And as said #benoit-s, you don't need to encode in base64 the content of your image.
I just edited this line :
DataSource ds = new ByteArrayDataSource(imageBase64, "image/png");
to
//byte[] imageAsByteArray = the content of your image
DataSource ds = new ByteArrayDataSource(imageAsByteArray, "image/png");
Ok so I'm having to alter some old code from another dev that he sent up for sending emails from our app with Java Mail. This has worked fine for a long time but now we are required to send pdf attachments as well.
So basically below, assume there is an object "mail" that has getters for the text and html messages as well as now a getter for the pdf filename to load from the filesystem and attach to the mail.
I've altered the below code where marked, so if there is a pdf to attach, load from filesystem and attach. I've tried to use the same structure as the previous code, although I suspect its not all required?
Multipart mp = new MimeMultipart("alternative");
// Create a "text" Multipart message
BodyPart textPart = new MimeBodyPart();
textPart.setContent(mail.getText(), "text/plain");
mp.addBodyPart(textPart);
// Create a "HTML" Multipart message
Multipart htmlContent = new MimeMultipart("related");
BodyPart htmlPage = new MimeBodyPart();
htmlPage.setContent(mail.getHtml(), "text/html; charset=UTF-8");
htmlContent.addBodyPart(htmlPage);
BodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent);
mp.addBodyPart(htmlPart);
// NEW CODE STARTS HERE
if(StringUtils.isNotBlank(mail.getPdfAttachmentFileName())) {
Multipart pdfContent = new MimeMultipart("mixed"); //<---- this appears to be an issue???
BodyPart pdfPage = new MimeBodyPart();
File file = new File(uploadDir + "/" + mail.getPdfAttachmentFileName());
DataSource dataSource = new ByteArrayDataSource(new FileInputStream(file), "application/pdf");
pdfPage.setDataHandler(new DataHandler(dataSource));
pdfPage.setFileName(mail.getPdfAttachmentFileName());
pdfContent.addBodyPart(pdfPage);
BodyPart pdfPart = new MimeBodyPart();
pdfPart.setContent(pdfContent);
mp.addBodyPart(pdfPart);
}
// NEW CODE ENDS HERE
mimeMessage.setContent(mp);
At any rate, the above works, sort of. There are no errors or exceptions and the message gets sent. BUT the attachment doesn't appear depending on which email client you recieve the mail with.
With the code as above, Outlook receives the message as readable and the attachment is visible and downloadable. This is perfect. BUT in GMail, the message is still readable, the paperclip appears to indicate there is an attachment, but there is no attachment to download?
If you switch the `Multipart pdfContent = new MimeMultipart("mixed");' to be "related" rather than "mixed" the exact opposite is true. GMail receives it perfectly but Outlook only gets the message and paperclip, no actual attachment.
Obviously we need to be sending emails to our customers with no knowledge of their email client used to open them! Obviously I'm a novice at Java Mail so have simply copied suggested code but this isn't gelling well with our existing code!
Any ideas how to alter the above to make it completely email client independant?
Ok turns out Spring has a helper class to hide all this mess away from you.
I've refactored all of the above code into the following and it works great;
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8");
message.setTo(mail.getTo());
message.setFrom(mail.getFrom());
message.setSubject(mail.getSubject());
message.setText(mail.getText(), mail.getHtml());
if(StringUtils.isNotBlank(mail.getPdfAttachmentFileName())) {
File file = new File(uploadDir + "/" + mail.getPdfAttachmentFileName());
DataSource dataSource = new ByteArrayDataSource(new FileInputStream(file), "application/pdf");
message.addAttachment(mail.getPdfAttachmentFileName(), dataSource);
}
From http://www.oracle.com/technetwork/java/faq-135477.html#sendmpa:
You'll want to send a MIME multipart/alternative message. You
construct such a message essentially the same way you construct a
multipart/mixed message, using a MimeMultipart object constructed
using new MimeMultipart("alternative"). You then insert the text/plain
body part as the first part in the multpart and insert the text/html
body part as the second part in the multipart. You'll need to
construct the plain and html parts yourself to have appropriate
content. See RFC2046 for details of the structure of such a message.
Can someone show me some sample code for this?
This is a part of my own code:
final Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(senderAddress, senderDisplayName));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(m.getRecipient(), m.getRecipientDisplayName()));
msg.setSubject(m.getSubject());
// Unformatted text version
final MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(m.getText(), "text/plain");
// HTML version
final MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(m.getHtml(), "text/html");
// Create the Multipart. Add BodyParts to it.
final Multipart mp = new MimeMultipart("alternative");
mp.addBodyPart(textPart);
mp.addBodyPart(htmlPart);
// Set Multipart as the message's content
msg.setContent(mp);
LOGGER.log(Level.FINEST, "Sending email {0}", m);
Transport.send(msg);
Where m is an instance of my own class.