2

画像を埋め込んでメールを送信したい。そのために、以下のコードを使用しました。完全なコードではありません。そのコードの一部

        Multipart multipart = new MimeMultipart("related");
        // Create the message part 
        BodyPart messageBodyPart;
        messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(msgBody); // msgbody contains the contents of the html file
        messageBodyPart.setHeader("Content-Type", "text/html");
        multipart.addBodyPart(messageBodyPart);

        //add file attachments
        DataSource source;
        File file = new File("D:/sample.jpeg");
        if(file.exists()){
            // add attachment
            messageBodyPart = new MimeBodyPart();
            source = new FileDataSource(file);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(file.getName());
            messageBodyPart.setHeader("Content-ID", "<BarcodeImage>");
            messageBodyPart.setDisposition("inline");
            multipart.addBodyPart(messageBodyPart);
        }

        // Put parts in message
        msg.setContent(multipart);
        Transport.send(msg);

私が直面している問題は、メールを受け取ることはできますが、画像を見ることができません..メールに表示されません。
以下はhtmlファイルの私の部分です

             <img src=\"cid:BarcodeImage\" alt="Barcode" width="166" height="44" align="right" />

画像がメールに表示されない理由と添付ファイルにない理由を教えてください??

4

4 に答える 4

2

私は同様の問題に遭遇しました。次の投稿は大いに役立ちました: Java を使用して画像が埋め込まれたメールを送信する方法 コードの最も重要な部分は次のとおりです。

String cid = generateCID();
MimeBodyPart textPart = new MimeBodyPart();
textPart.setText("<html><head>"
+ "<title>This is not usually displayed</title>"
+ "</head>n"
+ "<body><div><strong>Hi there!</strong></div>"
+ "<div>Sending HTML in email is so <em>cool!</em> </div>n"
+ "<div>And here's an image: <img src=\"cid:\"" + cid + " /></div>" 
+ "<div>I hope you like it!</div></body></html>",
"US-ASCII", "html");
content.addBodyPart(textPart);

MimeBodyPart imagePart = new MimeBodyPart();
imagePart.attachFile("resources/teapot.jpg");
imagePart.setContentID("<" + cid + ">");
imagePart.setDisposition(MimeBodyPart.INLINE);
content.addBodyPart(imagePart);

関数 generateCID() は一意の文字列を返す必要があります。例えば:

java.util.UUID.randomUUID()
于 2016-05-19T09:54:18.413 に答える
0

次の行を削除してみてください。

messageBodyPart.setDisposition("inline");
于 2009-06-10T08:32:52.017 に答える
0

に変更new MimeMultipart("related");new MimeMultipart();ます (オプションmsg.setContent(multipart);で にも変更しmsg.setContent(multipart,"multipart/related");ます)。また、必ず に変更img src=\"cid:BarcodeImage\"してくださいimg src="cid:BarcodeImage"。それでうまくいくはずです。

于 2015-04-13T13:43:46.623 に答える