0

javamail を使用して HTML に画像を埋め込む方法のチュートリアルに成功しました。ただし、テンプレート html ファイルから読み取って、送信する前に画像を埋め込もうとしています。

私が使用するときのように、コードが埋め込み画像に適していると確信しています:

bodyPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
               "<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");

画像は正常に表示されます。ただし、次を使用してファイルから読み取る場合:

readHTMLToString reader = new readHTMLToString();
String str = reader.readHTML();  
bodyPart.setContent(str, "text/html");

メール送信時に画像が表示されません。

html を文字列に読み取るための私のコードは次のとおりです。

public class readHTMLToString {
static String finalFile;

public static String readHTML() throws IOException{

//intilize an InputStream
    File htmlfile = new File("C:/temp/basictest.html");
    System.out.println(htmlfile.exists());
try {
  FileInputStream fin = new FileInputStream(htmlfile);

  byte[] buffer= new byte[(int)htmlfile.length()];
new DataInputStream(fin).readFully(buffer);
    fin.close();
    String s = new String(buffer, "UTF-8");
    finalFile = s;
}
catch(FileNotFoundException e)
{
  System.out.println("File not found" + e);
}
catch(IOException ioe)
{
  System.out.println("Exception while reading the file " + ioe);
}
return finalFile;
  }
}

電子メールを送信するための私の完全なクラスは次のとおりです。

package com.bcs.test;

import java.io.IOException;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class SendEmail {

public static void main(String[] args) throws IOException {

    final String username = "usernamehere@gmail.com";
    final String password = "passwordhere";

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.smtp.port", "587");


    Session session = Session.getInstance(props,
      new javax.mail.Authenticator() {
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
      });

    try {

        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress("from-email@gmail.com"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("recepientemailhere"));
        message.setSubject("Testing Subject");

        //SET MESSAGE AS HTML
        MimeMultipart multipart = new MimeMultipart("related");  

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

        // Create the HTML with link to image CID.  
        // Prefix the link with "cid:". 

        //bodyPart.setContent("<html><body><h2>A title</h2>Some text in here<br/>" +
              // "<img src=\"cid:the-img-1\"/><br/> some more text<img src=\"cid:the-img-1\"/></body></html>", "text/html");
        readHTMLToString reader = new readHTMLToString();
        String str = reader.readHTML();  

        // 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 imgPart = new MimeBodyPart();  

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

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

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

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



        //message.setText("Dear Mail Crawler,"
        //  + "\n\n No spam to my email, please!");

        Transport.send(message);

        System.out.println("Done");

    } catch (MessagingException e) {
        throw new RuntimeException(e);
    }
}
}

これに関する多くの回答を読みましたが、なぜこれが起こっているのか本当にわかりません. 私のhtmlファイルの問題が原因だと思っていましたが、上記の最初のsetContentコードと同じコンテンツを使用して非常に基本的なものを作成しましたが、この基本的な例には画像が表示されません。

バイト配列への読み込みと関係がありますか?

どんな助けでも大歓迎です。

ありがとう

4

2 に答える 2

0

もちろん、ファイル内のデータが実際にUTF-8でエンコードされており、コンピューターのデフォルトのエンコードではないことを確認する必要があります。これをすべてのASCIIテキストでテストする場合、問題はありません。

上記のサンプルコードの文字列と同じテキストがファイルにあると仮定すると、2つのケース(文字列、ファイル)を比較して、message.writeTo(new FileOutputStream(new FileOutputStream( "msg.txt")); Transport.send呼び出しの直前または代わり。

于 2012-04-20T20:24:33.873 に答える
0

電子メール クライアントが HTML コードを解釈する方法は、HTML テンプレート ファイルへの書き込みとは異なります。ただし、テンプレートを取得したら、画像のバイト配列を src 属性にコピーすることをお勧めします。ブラウザが src 属性を解釈するので、インライン画像を試して、データを取得するために別のリクエストを行うことができます。

コンセプトについてより多くの洞察を与えてくれます。HTML のインライン画像

于 2012-04-20T14:53:28.020 に答える