【问题标题】:sending image to mail by java program without attaching?通过java程序将图像发送到邮件而不附加?
【发布时间】:2012-10-03 21:30:35
【问题描述】:

我想知道如何通过 java 程序将图像发送到邮件。我可以发送文本和图像,但它显示为附件.. 我希望它应该成为我的文本的过去...... 以下是我用过的

// Create new message with mail session.  
Message message = new MimeMessage(session);  

// Create multipart message.  
MimeMultipart multipart = new MimeMultipart();  

// Create bodypart.  
BodyPart bodyPart = new MimeBodyPart();  

// Create the HTML with link to image CID.  
// Prefix the link with "cid:".  
String str = "<html><h1>Hello</h1>" +  
            "<img src=\"cid:image_cid\"></html>";  

// Set the MIME-type to HTML.  
bodyPart.setContent(str, "text/html");  

// Add the HTML bodypart to the multipart.  
multipart.addBodyPart(bodyPart);  

// Create another bodypart to include the image attachment.  
bodyPart = new MimeBodyPart();  

// Read image from file system.  
DataSource ds = new FileDataSource("C:\\images\\image.png");  
bodyPart.setDataHandler(new DataHandler(ds));  

// Set the content-ID of the image attachment.  
// Enclose the image CID with the lesser and greater signs.  
bodyPart.setHeader("Content-ID", "<image_cid>");  

// Add image attachment to multipart.  
multipart.addBodyPart(bodyPart);  

// Add multipart content to message.  
message.setContent(multipart);  

// Now set the header and send the email.  
...  

如果有人知道请告诉我..

感谢广告

【问题讨论】:

    标签: jakarta-ee


    【解决方案1】:

    您所做的一切都是正确的,我使用的是 gmail,我需要点击“显示图片”来查看电子邮件中的图片,您可以添加以下行来查看图片:

    mbp2.setFileName("image.png");
    

    我的完整代码如下所示:

        // create a message
        MimeMessage msg = new MimeMessage(session);
        msg.setRecipients(Message.RecipientType.TO, to);
        msg.setSubject(subject);
    
        // create and fill the first message part
        MimeBodyPart mbp1 = new MimeBodyPart();
        mbp1.setContent(bodyText, "text/html");
    
        // create the second message part
        MimeBodyPart mbp2 = new MimeBodyPart();
        // attach the file to the message
            DataSource source = new FileDataSource(new File("image.png"));
            mbp2.setDataHandler(new DataHandler(source));
            mbp2.setFileName("image.png");
            mbp2.setHeader("Content-ID", "<image_cid>"); // cid:image_cid
        // create the Multipart and add its parts to it
        Multipart mp = new MimeMultipart();
        mp.addBodyPart(mbp1);
        mp.addBodyPart(mbp2);
        // add the Multipart to the message
        msg.setContent(mp);
        // send the message
        Transport.send(msg);
    

    而html消息体是这样的:

    bodyText = "<p><img style='float:right' src='cid:image_cid'>Hello World example</p>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-07
      • 1970-01-01
      • 2011-01-09
      • 1970-01-01
      • 2016-11-21
      • 2013-12-01
      • 1970-01-01
      • 2013-12-29
      相关资源
      最近更新 更多