java 如何在电子邮件正文中显示图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6201682/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 14:48:19  来源:igfitidea点击:

How to show an image in the email body?

javaandroidimageemailinline-images

提问by Sankar Ganesh

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.

我已经尝试过 HTML 图像标记,<img src=\"http://url/to/the/image.jpg\">"并且得到了输出,正如您在我关于如何在电子邮件正文中添加图像的问题中所看到的,所以我很累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[] {"[email protected]"}); 
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 ImageGettercode for TextViewI am able to get the text and image but I am not able to see the image in the email body

更新 1:如果我使用ImageGetter代码,TextView我可以获得文本和图像,但我无法在电子邮件正文中看到图像

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

更新 2:我使用了粗体标签和锚标签,如下所示,这些标签工作正常,但是当我使用 img 标签时,我可以看到一个方形框,上面写着 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));

采纳答案by rochdev

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

不幸的是,使用 Intent 无法做到这一点。

The reason why for example boldtext is displayed in the EditText and not an Image is that StyleSplanis implementing Parcelablewhereas ImageSpandoes 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.

为什么例如之所以大胆的文字显示在EditText上,而不是一个图像是StyleSplan正在实施ParcelableImageSpan没有。因此,当在新活动中检索 Intent.EXTRA_TEXT 时,ImageSpan 将无法解包,因此不会成为附加到 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.

不幸的是,使用不通过 Intent 传递数据的其他方法在这里是不可能的,因为您无法控制接收 Activity。

回答by Oliver Pearmain

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[] { "[email protected]" });
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/

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

回答by matheeeny

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")
  • 关闭你的 img 标签(<img src="..." />而不是<img src="...">
  • 使用i.setType("text/html")代替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"?

如果这些都不起作用,也许您尝试将图像附加到电子邮件中,然后使用"cid:ATTACHED_IMAGE_CONTENT_ID"而不是"http:URL_TO_IMAGE"?

Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_EMAIL,new String[] {"[email protected]"}); 
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 imagesin the apache email user guide

请参见标题为发送HTML格式的电子邮件与嵌入式图像apache的电子邮件用户指南

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?

不过,您需要知道附加图像的内容 ID,我不确定这是否是通过标准 Intent 方法浮出水面的。也许您可以检查原始电子邮件并确定它们的命名约定?

回答by Pradeep Bishnoi

    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 = "[email protected]"; //requires valid gmail id
            final String password = "abc"; // correct password for gmail id
            final String toEmail = "[email protected]"; // 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("[email protected]", "NoReply-JD"));

                msg.setReplyTo(InternetAddress.parse("[email protected]", 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();
            }
        }
    }