简体   繁体   中英

JavaMail - How to send html content with image

I have seen many examples, where they have provided img file path separately & have referred that in the html content.Whereas I want read the HTML(with image reference in it) content & sent as mail.When i passed the html content, image is not rendered.

I have referred this site : http://www.rgagnon.com/javadetails/java-0504.html

Java class: SimpleMail

import javax.mail.*;
import javax.mail.internet.*;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Properties;

class SimpleMail {
    public static void main(String[] args) throws Exception{
        System.out.println("Sending mail...");
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.host", "smtp.example.com");
        props.setProperty("mail.user", "user@example.com");
        props.setProperty("mail.password", "password");

        Session mailSession = Session.getDefaultInstance(props, null);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();

        MimeMessage message = new MimeMessage(mailSession);
        message.setSubject("HTML  mail with images");
        message.setFrom(new InternetAddress("me@sender.com"));
        //C:\Users\sv\Desktop\test.html
        BufferedReader br = null;
        FileReader fr = null;

            //br = new BufferedReader(new FileReader(FILENAME));
            fr = new FileReader("C:\\Desktop\\test.html");
            br = new BufferedReader(fr);

            String sCurrentLine;
            String outCome="";

            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
                outCome+="\n"+sCurrentLine;
            }

           // message.setContent(outCome, "text/html:charset=utf-8");
        message.addRecipient(Message.RecipientType.TO,
                new InternetAddress("user1@example.com"));

        transport.connect();
        Multipart mp = new MimeMultipart();
        MimeBodyPart htmlPart = new MimeBodyPart();
        htmlPart.setContent(outCome, "text/html");
        htmlPart.setHeader("Content-Type", "text/html"  );
        mp.addBodyPart(htmlPart);
        message.setContent(mp);
        transport.sendMessage(message,
                message.getRecipients(Message.RecipientType.TO));
        transport.close();
    }
}

Html file : test.html

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

 <img src="tr.png" alt="Smiley face" height="42" width="42"> 
<div class="container">
  <h2>Dropdowns</h2>
  <p>The .dropdown class is used to indicate a dropdown menu.</p>
  <p>Use the .dropdown-menu class to actually build the dropdown menu.</p>
  <p>To open the dropdown menu, use a button or a link with a class of .dropdown-toggle and data-toggle="dropdown".</p>                                          
  <div class="dropdown">
    <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Dropdown Example
    <span class="caret"></span></button>
    <ul class="dropdown-menu">
      <li><a href="https://www.w3schools.com/html/default.asp">HTML</a></li>
      <li><a href="https://www.w3schools.com/css/default.asp">CSS</a></li>
      <li><a href="https://www.w3schools.com/js/default.asp">JavaScript</a></li>
    </ul>
  </div>
</div>

</body>
</html>

Output:

在此处输入图片说明

Try this:

// Your mail has 2 parts, the BODY(html) and the EMBEDDED image
MimeMultipart multipart = new MimeMultipart("related");

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

// Add it
multipart.addBodyPart(messageBodyPart);

// Second part (EMBEDDED image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource("/path/to/your/image/tr.png");

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

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

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

// Send message
Transport.send(message);

The image-URL in your mail is relative, so the mail client can't load it from the website you copied the HTML-file from. You need to use an absolute URL. As the page you used as reference already explained, this will most likely not work, either, because most mail clients don't load external images anymore due to abuse by spammers. So you should go the way that's described in that page as third approach by adding the image as attachment to the mail and refer to it within the HTML-page by using the URL cid:unique-content-id . I skip providing an example because the page you linked already contains one that should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM