I'm looking for the solution in two ways:
- Get the file PATH:
I would like to get the path
of an image that is in res/drawable
in my Android project.
I'm needing path
because I have to send it attached by email, and I'm using JavaMail for this and it only accepts a path
or a File
, for attached file.
- Make JavaMail be able to accept a Bitmap:
Change how to create the email attachment, today I'm doing this:
MimeMultipart content = new MimeMultipart();
MimeBodyPart attachmentPart = new MimeBodyPart();
// aqui teria que setar um bitmap ao inves de um Path ou File;
attachmentPart.attachFile(attachment);
attachmentPart.setContentID("<image>");
attachmentPart.setDisposition(MimeBodyPart.INLINE);
content.addBodyPart(attachmentPart);
I'll try to explain the problem a little better:
I need this if I do not find a user-configured logo (in a specific folder with a specific name in the sdcard) for email signature, then I would use a standard logo of my application, and this standard logo is available in my resources (res / drawable), since it is immutable.
I saw the solution that @ramaral posted, but in spite of being good, it is not a solution that I expected, I believe there must be another way, as having to make a copy of the image to the sdcard. I do not think it smells good.
Final Solution with the help of the cited answers
Using ByteArrayDataSource as quoted by @Elcio Arthur Cardoso in his response , I changed my method that includes the attachment to allow attaching a file to byte[]
like this:
MimeMultipart content = new MimeMultipart();
// ... add message part
// converter bitmap to byte[]
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.transparent_1x1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageBytes = stream.toByteArray();
// criar anexo do email, apartir de um array de byte (byte[])
MimeBodyPart attachmentPart = new MimeBodyPart();
DataHandler handlerAttach = new DataHandler(new ByteArrayDataSource(imageBytes));
attachmentPart.setDataHandler(handlerAttach);
attachmentPart.setFileName("image.png");
attachmentPart.setContentID("<image>");
attachmentPart.setDisposition(MimeBodyPart.INLINE);
content.addBodyPart(attachmentPart);
This solution worked perfectly for me.