如何在使用 Java 邮件发送 html 电子邮件时嵌入多个图像

发布于 2024-11-05 01:37:31 字数 1325 浏览 2 评论 0原文

我正在尝试从 javamail 发送电子邮件。我正在嵌入图像并使用 CID。但问题是如何在一条消息中嵌入多个图像。如果我尝试添加标头..它只是采用最后设置的标头。如何使用 CID 添加多个图像和参考。

MimeMultipart multipart = new MimeMultipart("related");

    // first part  (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
//    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<H1>Hello</H1><br/> <p align=center><img src=\"cid:senny\"> </p>";
    htmlText+="<p align=center><img src=\"cid:senny\"> </p>";
    htmlText+="<p align=center><img src=\"cid:image\"> </p>";
    messageBodyPart.setContent(htmlText, "text/html");

    // add it
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource
      ("C:\\images\\cec_header_457.png");
    DataSource fds1 = new FileDataSource
    ("C:\\images\\cec_header_420.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setDataHandler(new DataHandler(fds1));
    messageBodyPart.addHeader("Content-ID","<image>");
    messageBodyPart.addHeader("Content-ID","<senny>");
    // add it
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

I'm trying to send email from javamail. I'm embeding the images and using CID. But the problem is how do I embed multiple images in a single message. if I try to add in header.. it is just taking the last set header. how do I add multiple images and reference using CID.

MimeMultipart multipart = new MimeMultipart("related");

    // first part  (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
//    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<H1>Hello</H1><br/> <p align=center><img src=\"cid:senny\"> </p>";
    htmlText+="<p align=center><img src=\"cid:senny\"> </p>";
    htmlText+="<p align=center><img src=\"cid:image\"> </p>";
    messageBodyPart.setContent(htmlText, "text/html");

    // add it
    multipart.addBodyPart(messageBodyPart);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource
      ("C:\\images\\cec_header_457.png");
    DataSource fds1 = new FileDataSource
    ("C:\\images\\cec_header_420.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setDataHandler(new DataHandler(fds1));
    messageBodyPart.addHeader("Content-ID","<image>");
    messageBodyPart.addHeader("Content-ID","<senny>");
    // add it
    multipart.addBodyPart(messageBodyPart);

    // put everything together
    message.setContent(multipart);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怂人 2024-11-12 01:37:32

每个图像都需要有自己的 MimeBodyPart,将这段代码分解

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
  ("C:\\images\\cec_header_457.png");
DataSource fds1 = new FileDataSource
("C:\\images\\cec_header_420.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setDataHandler(new DataHandler(fds1));
messageBodyPart.addHeader("Content-ID","<image>");
messageBodyPart.addHeader("Content-ID","<senny>");
// add it
multipart.addBodyPart(messageBodyPart);

为两个多部分,例如

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds1 = new FileDataSource
("C:\\images\\cec_header_420.png");
messageBodyPart.setDataHandler(new DataHandler(fds1));
messageBodyPart.addHeader("Content-ID","<senny>");
// add it
multipart.addBodyPart(messageBodyPart);

messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
  ("C:\\images\\cec_header_457.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.addHeader("Content-ID","<image>");
// add it
multipart.addBodyPart(messageBodyPart);

Each image needs to be its own MimeBodyPart, break up this code,

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
  ("C:\\images\\cec_header_457.png");
DataSource fds1 = new FileDataSource
("C:\\images\\cec_header_420.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setDataHandler(new DataHandler(fds1));
messageBodyPart.addHeader("Content-ID","<image>");
messageBodyPart.addHeader("Content-ID","<senny>");
// add it
multipart.addBodyPart(messageBodyPart);

Into two multi parts, something like

// second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds1 = new FileDataSource
("C:\\images\\cec_header_420.png");
messageBodyPart.setDataHandler(new DataHandler(fds1));
messageBodyPart.addHeader("Content-ID","<senny>");
// add it
multipart.addBodyPart(messageBodyPart);

messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource
  ("C:\\images\\cec_header_457.png");
messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.addHeader("Content-ID","<image>");
// add it
multipart.addBodyPart(messageBodyPart);
微暖i 2024-11-12 01:37:32

是的,每个图像都需要自己的 MimeBodyPart。上述解决方案仅适用于两张图像。如果有多个图像,为 MimeBodyPart 创建多个对象效率不高。

那么,我们就上函数吧,

public void imgUpload(Multipart multipart,String fileName) throws MessagingException
{
    int no = rand.nextInt();
    String contentId = Integer.toString(no);
    System.out.println(contentId);

    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<img align=\" center \" src=\"cid:"+contentId+"\"><br>";
    messageBodyPart.setContent(htmlText+"<br>", "text/html");

    // add it
    multipart.addBodyPart(messageBodyPart);
    System.out.println(contentId);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource(fileName);

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<"+contentId+">");
    System.out.println(contentId);

    // add image to the multipart
    multipart.addBodyPart(messageBodyPart);
}

这里要传递的参数是MimeBodyPart对象和图像路径
每个图像都需要自己的 content-id,因此 content-id 是针对此场景随机生成的。

嵌入多个图像的完整代码:

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendImageEmail
{
   public static void main(String [] args)
   {
      SendImageEmail sendEmail = new SendImageEmail(); 
      sendEmail.SendemailwithImage();
   } 
   public void imgUpload(Multipart multipart,String fileName) throws MessagingException
   {
     int no = rand.nextInt();
     String contentId = Integer.toString(no);
     System.out.println(contentId);

     BodyPart messageBodyPart = new MimeBodyPart();
     String htmlText = "<img align=\" center \" src=\"cid:"+contentId+"\"><br>";
     messageBodyPart.setContent(htmlText+"<br>", "text/html");

     // add it
     multipart.addBodyPart(messageBodyPart);
     System.out.println(contentId);

     // second part (the image)
     messageBodyPart = new MimeBodyPart();
     DataSource fds = new FileDataSource(fileName);

     messageBodyPart.setDataHandler(new DataHandler(fds));
     messageBodyPart.setHeader("Content-ID", "<"+contentId+">");
     System.out.println(contentId);

     // add image to the multipart
     multipart.addBodyPart(messageBodyPart);
   }

  public void SendemailwithImage(){
       SendImageEmail imgEmail = new SendImageEmail(); 
       List<String> imgPath = new ArrayList<String>();
       imgPath.add("D:\\img1.png");
       imgPath.add("D:\\img2.png");
       imgPath.add("D:\\img3.png");

  // Recipient's email ID needs to be mentioned.
  String to = "[email protected]";

  // Sender's email ID needs to be mentioned
  String from = "[email protected]";

  // Assuming you are sending email from localhost
  String host = "localhost";

  // Get system properties
  Properties properties = System.getProperties();

  // Setup mail server
  properties.setProperty("mail.smtp.host", host);

  // Get the default Session object.
  Session session = Session.getDefaultInstance(properties);

  try{
     // Create a default MimeMessage object.
     MimeMessage message = new MimeMessage(session);

     // Set From: header field of the header.
     message.setFrom(new InternetAddress(from));

     // Set To: header field of the header.
     message.addRecipient(Message.RecipientType.TO,
                              new InternetAddress(to));

     // Set Subject: header field
     message.setSubject("This is the Subject Line!");

     // Create the message part 
     BodyPart messageBodyPart = new MimeBodyPart();

     // Fill the message
     messageBodyPart.setText("This is message body");

     // Create a multipar message
     Multipart multipart = new MimeMultipart();

     // Set text message part
     multipart.addBodyPart(messageBodyPart);

    for(String fileName : imgPath)
     {
       imgEmail.upload(multipart,fileName); 
     }       
     // Send the complete message parts
     message.setContent(multipart );

     // Send message
     Transport.send(message);
     System.out.println("Sent message successfully....");
  }catch (MessagingException mex) {
     mex.printStackTrace();
  }}}

Yes each image needs its own MimeBodyPart. Above solution is only for two images. In case, if there are multiple images, it is not efficient to create multiple object for MimeBodyPart.

So,Lets go up with function,

public void imgUpload(Multipart multipart,String fileName) throws MessagingException
{
    int no = rand.nextInt();
    String contentId = Integer.toString(no);
    System.out.println(contentId);

    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<img align=\" center \" src=\"cid:"+contentId+"\"><br>";
    messageBodyPart.setContent(htmlText+"<br>", "text/html");

    // add it
    multipart.addBodyPart(messageBodyPart);
    System.out.println(contentId);

    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource(fileName);

    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<"+contentId+">");
    System.out.println(contentId);

    // add image to the multipart
    multipart.addBodyPart(messageBodyPart);
}

Here parameters to be passed are Object of MimeBodyPart and path of image.
Each image needs its own content-id, so content-id is generated randomly for this scenario.

Full code to embed multiple images :

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendImageEmail
{
   public static void main(String [] args)
   {
      SendImageEmail sendEmail = new SendImageEmail(); 
      sendEmail.SendemailwithImage();
   } 
   public void imgUpload(Multipart multipart,String fileName) throws MessagingException
   {
     int no = rand.nextInt();
     String contentId = Integer.toString(no);
     System.out.println(contentId);

     BodyPart messageBodyPart = new MimeBodyPart();
     String htmlText = "<img align=\" center \" src=\"cid:"+contentId+"\"><br>";
     messageBodyPart.setContent(htmlText+"<br>", "text/html");

     // add it
     multipart.addBodyPart(messageBodyPart);
     System.out.println(contentId);

     // second part (the image)
     messageBodyPart = new MimeBodyPart();
     DataSource fds = new FileDataSource(fileName);

     messageBodyPart.setDataHandler(new DataHandler(fds));
     messageBodyPart.setHeader("Content-ID", "<"+contentId+">");
     System.out.println(contentId);

     // add image to the multipart
     multipart.addBodyPart(messageBodyPart);
   }

  public void SendemailwithImage(){
       SendImageEmail imgEmail = new SendImageEmail(); 
       List<String> imgPath = new ArrayList<String>();
       imgPath.add("D:\\img1.png");
       imgPath.add("D:\\img2.png");
       imgPath.add("D:\\img3.png");

  // Recipient's email ID needs to be mentioned.
  String to = "[email protected]";

  // Sender's email ID needs to be mentioned
  String from = "[email protected]";

  // Assuming you are sending email from localhost
  String host = "localhost";

  // Get system properties
  Properties properties = System.getProperties();

  // Setup mail server
  properties.setProperty("mail.smtp.host", host);

  // Get the default Session object.
  Session session = Session.getDefaultInstance(properties);

  try{
     // Create a default MimeMessage object.
     MimeMessage message = new MimeMessage(session);

     // Set From: header field of the header.
     message.setFrom(new InternetAddress(from));

     // Set To: header field of the header.
     message.addRecipient(Message.RecipientType.TO,
                              new InternetAddress(to));

     // Set Subject: header field
     message.setSubject("This is the Subject Line!");

     // Create the message part 
     BodyPart messageBodyPart = new MimeBodyPart();

     // Fill the message
     messageBodyPart.setText("This is message body");

     // Create a multipar message
     Multipart multipart = new MimeMultipart();

     // Set text message part
     multipart.addBodyPart(messageBodyPart);

    for(String fileName : imgPath)
     {
       imgEmail.upload(multipart,fileName); 
     }       
     // Send the complete message parts
     message.setContent(multipart );

     // Send message
     Transport.send(message);
     System.out.println("Sent message successfully....");
  }catch (MessagingException mex) {
     mex.printStackTrace();
  }}}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文