23

Note: I don't want to attach the Image to the Email

I want to show an image in the email body,

I had tried the HTML image tag <img src=\"http://url/to/the/image.jpg\">" and I got output as you can see in this my question on How to add an image in email body, so I tired Html.ImageGetter.

It does not work for me, it also gives me the same output, so I have a doubt is it possible to do this,

My code

Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL,new String[] {"abc@gmail.com"}); 
i.putExtra(Intent.EXTRA_TEXT,
    Html.fromHtml("Hi <img src='http://url/to/the/image.jpg'>",
    imgGetter,
    null));

i.setType("image/png");
startActivity(Intent.createChooser(i,"Email:"));


private ImageGetter imgGetter = new ImageGetter() {

    public Drawable getDrawable(String source) {
        Drawable drawable = null;
            try {
                drawable = getResources().getDrawable(R.drawable.icon);
                drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            } catch (Exception e) {
                e.printStackTrace();
                Log.d("Exception thrown",e.getMessage());
            } 
            return drawable;
    }
};

UPDATE 1: If I use the ImageGetter code for TextView I am able to get the text and image but I am not able to see the image in the email body

Here is my code:

TextView t = null;
t = (TextView)findViewById(R.id.textviewdemo);
t.setText(Html.fromHtml("Hi <img src='http://url/to/the/image.jpg'>",
    imgGetter,
    null));

UPDATE 2: I had used bold tag and anchor tag as i shown below these tag are working fine , but when i used img tag i can able to see a square box which say as OBJ

 i.putExtra(Intent.EXTRA_TEXT,Html.fromHtml("<b>Hi</b><a href='http://www.google.com/'>Link</a> <img src='http://url/to/the/image.jpg'>",
        imgGetter,
        null));
Community
  • 1
  • 1
Sankar Ganesh PMP
  • 11,571
  • 11
  • 54
  • 89
  • Did you tried with another tag? Perhaps it gets sanitize when it comes from an intent. – Macarse Jun 02 '11 at 12:22
  • @Macarse: which tag, can you pls elaborate – Sankar Ganesh PMP Jun 02 '11 at 12:29
  • @Sankar: For instance a bold tag. Just to test if it works. – Macarse Jun 02 '11 at 12:39
  • @Macarse: yes bold tag is working i had used like this Html.fromHtml("Hi ", imgGetter, null)); – Sankar Ganesh PMP Jun 02 '11 at 12:43
  • @Sankar: Interesting. Try with a http link. – Macarse Jun 02 '11 at 13:09
  • @Macarse: I had used anchor tag too it i was also working fine, but the image tag gave me a square image and inside that , i saw obj word – Sankar Ganesh PMP Jun 02 '11 at 13:12
  • @Sankar: ok, I thought there was some kind of limitation but it isn't I guess. No idea then, sorry. – Macarse Jun 02 '11 at 14:25
  • @Macarse: I think i have to set bounty for this Question,:) – Sankar Ganesh PMP Jun 03 '11 at 05:39
  • I'm not really sure what is the use of Html.fromHTML here. also, the type should be "text/html" instead of "image/png". Then it depends on your email client. On the galaxy S, i don't even have the bold part working – njzk2 Jun 17 '11 at 14:23
  • yes, you have: i.setType("image/png"); but you are referencing image.jpg. A different image type. – nickfox Jun 20 '11 at 21:31
  • 1
    The type has to be text/html because you want to viewer (your email client or your browser) to display HTML. And next, the issue is not with the Intent or the receiver or anything else, it is with Html.fromHtml(). This method needs an ImageGetter (check out the other signature of Html.fromHtml()). If we do not provide an ImageGetter, it replaces all the img tags with dummy images. So even though our requirement is only creating well-formatted HTML to post on to the browser (and hence not worry about the display part), we are forced to worry about the display part! – Vikram Bodicherla Aug 08 '11 at 09:11
  • @SankarGanesh Hey, would you able to solve this issue "show an image in the email body?" becoz i am also facing the same problem, and i do exactly the way u do in your code. – AndroidDev Sep 04 '12 at 15:24

4 Answers4

15

Unfortunately, it's not possible to do this with Intents.

The reason why for example bold text is displayed in the EditText and not an Image is that StyleSplan is implementing Parcelable whereas ImageSpan does not. So when the Intent.EXTRA_TEXT is retrieved in the new Activity the ImageSpan will fail to unparcel and therefor not be part of the style appended to the EditText.

Using other methods where you don't pass the data with the Intent is unfortunately not possible here as you're not in control of the receiving Activity.

rochdev
  • 3,785
  • 2
  • 19
  • 18
  • If that is the only difference, you could very well implement your own ImageSpan (copy the code) and just transfer the bitmap (if it is small) via a parcel in the intent. Ergo, it would unparcel and could be shown on the other side? – George Jun 10 '13 at 16:00
  • 11
    Serious about what? You're aware that the post you're linking to is a copy/paste of my answer and not the other way around? – rochdev Jun 18 '13 at 10:19
  • Is there any solution for this issue? – HRM Jul 01 '14 at 07:02
1

I know this doesn't answer the original question but perhaps an acceptable alternative for some people is attaching the image to the email instead. I managed to achieve this with the following code...

String urlOfImageToDownload = "https://ssl.gstatic.com/s2/oz/images/google-logo-plus-0fbe8f0119f4a902429a5991af5db563.png";

// Start to build up the email intent
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { "abc@mail.com" });
i.putExtra(Intent.EXTRA_SUBJECT, "Check Out This Image");
i.putExtra(Intent.EXTRA_TEXT, "There should be an image attached");

// Do we need to download and attach an icon and is the SD Card available?
if (urlOfImageToDownload != null && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
    // Download the icon...
    URL iconUrl = new URL(urlOfImageToDownload);
    HttpURLConnection connection = (HttpURLConnection) iconUrl.openConnection();
    connection.setDoInput(true);
    connection.connect();
    InputStream input = connection.getInputStream();
    Bitmap immutableBpm = BitmapFactory.decodeStream(input);

    // Save the downloaded icon to the pictures folder on the SD Card
    File directory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    directory.mkdirs(); // Make sure the Pictures directory exists.
    File destinationFile = new File(directory, attachmentFileName);
    FileOutputStream out = new FileOutputStream(destinationFile);
    immutableBpm.compress(Bitmap.CompressFormat.PNG, 90, out);
    out.flush();
    out.close();
    Uri mediaStoreImageUri = Uri.fromFile(destinationFile);     

    // Add the attachment to the intent
    i.putExtra(Intent.EXTRA_STREAM, mediaStoreImageUri);
}                       

// Fire the intent
startActivity(i);

http://www.oliverpearmain.com/blog/android-how-to-launch-an-email-intent-attaching-a-resource-via-a-url/

Oliver Pearmain
  • 17,376
  • 12
  • 77
  • 83
1

Two simple suggestions first:

  • Close your img tag (<img src="..." /> instead of <img src="...">)
  • Use i.setType("text/html") instead of i.setType("image/png")

If neither of those work, maybe you try attaching the image to the email and then referencing it using "cid:ATTACHED_IMAGE_CONTENT_ID" rather than an "http:URL_TO_IMAGE" ?

Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL,new String[] {"abc@gmail.com"}); 
i.putExtra(Intent.EXTRA_STREAM, Uri.parse("http://url/to/the/image.jpg");
i.putExtra(Intent.EXTRA_TEXT,
        Html.fromHtml("Hi <img src='cid:image.jpg' />", //completely guessing on 'image.jpg' here
        imgGetter,
        null));
i.setType("image/png");

See the section titled Sending HTML formatted email with embedded images in the apache email user guide

Though, then you would need to know the content-id of the attached image, and I'm not sure if that is surfaced via the standard Intent approach. Maybe you could inspect the raw email and determine their naming conventions?

matheeeny
  • 1,644
  • 2
  • 17
  • 31
  • Thanks for your replay, but your suggestions are not working , i had used that, may be there is some restriction in the Intent approach. – Sankar Ganesh PMP Jun 21 '11 at 09:56
0
    i resolve problem send image as a body mail in android

   you have need three lib  of java mail 

    1.activation.jar
    2.additionnal.jar
    3.mail.jar




    public class AutomaticEmailActivity extends Activity {

        @Override 
        public void onCreate(Bundle savedInstanceState) { 
            super.onCreate(savedInstanceState); 
            setContentView(R.layout.main); 
            if (android.os.Build.VERSION.SDK_INT > 9) {
                StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                StrictMode.setThreadPolicy(policy);
            }



            final String fromEmail = "abc@gmail.com"; //requires valid gmail id
            final String password = "abc"; // correct password for gmail id
            final String toEmail = "pradeep.bishnoi89@gmail.com"; // can be any email id 

            System.out.println("SSLEmail Start");
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com"); //SMTP Host
            props.put("mail.smtp.socketFactory.port", "465"); //SSL Port
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory"); //SSL Factory Class
            props.put("mail.smtp.auth", "true"); //Enabling SMTP Authentication
            props.put("mail.smtp.port", "465"); //SMTP Port

            Authenticator auth = new Authenticator() {
                //override the getPasswordAuthentication method
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(fromEmail, password);
                }
            };

            final Session session = Session.getDefaultInstance(props, auth);
            Button send_email=(Button) findViewById(R.id.send_email);
            send_email.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    sendImageEmail(session, toEmail,"SSLEmail Testing Subject with Image", "SSLEmail Testing Body with Image");

                }
            });

        }




        public static void sendImageEmail(Session session, String toEmail, String subject, String body){
            try{
                MimeMessage msg = new MimeMessage(session);
                msg.addHeader("Content-type", "text/HTML; charset=UTF-8");
                msg.addHeader("format", "flowed");
                msg.addHeader("Content-Transfer-Encoding", "8bit");

                msg.setFrom(new InternetAddress("no_reply@journaldev.com", "NoReply-JD"));

                msg.setReplyTo(InternetAddress.parse("no_reply@journaldev.com", false));

                msg.setSubject(subject, "UTF-8");

                msg.setSentDate(new Date());

                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmail, false));

                MimeMultipart multipart = new MimeMultipart("related");

                BodyPart messageBodyPart = new MimeBodyPart();
                String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
                messageBodyPart.setContent(htmlText, "text/html");
                // add it
                multipart.addBodyPart(messageBodyPart);


                String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
                String filename = base + "/photo.jpg";

                messageBodyPart = new MimeBodyPart();
                DataSource fds = new FileDataSource(filename);

                messageBodyPart.setDataHandler(new DataHandler(fds));
                messageBodyPart.setHeader("Content-ID", "<image>");
                multipart.addBodyPart(messageBodyPart);   
                msg.setContent(multipart);


                // Send message
                Transport.send(msg);
                System.out.println("EMail Sent Successfully with image!!");
            }catch (MessagingException e) {
                e.printStackTrace();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }
Pradeep Bishnoi
  • 1,605
  • 1
  • 19
  • 24