2

私はJavaメールが初めてです。画像を添付してメールを送信したい。メールに画像を添付するために次のコードを試しました。

BodyPart messageBodyPart = new MimeBodyPart();

                if (content == null) {
                    messageBodyPart.setText("");
                } else {
                    messageBodyPart.setText(content);
                }

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

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

                // Part two is attachment
                // messageBodyPart = new MimeBodyPart();
                DataSource source = new ByteArrayDataSource(
                        attachedFile2.getBytes("UTF-8"),
                        "application/octet-stream");

                //attachedFile2 is the filename of image.
                messageBodyPart = new MimeBodyPart();

                messageBodyPart.setDataHandler(new DataHandler(source));
                messageBodyPart.setFileName(attachedFile2);
                multipart.addBodyPart(messageBodyPart);
                message.setContent(multipart);

このコードは機能しています。画像が添付されたメールが届きました。ただし、問題は、画像がサポートされていない形式で表示されるか、元の画像が表示されないことです。

この問題を解決する方法がわかりません。

私を助けてください..

前もって感謝します..

4

1 に答える 1

0

これを試すことができます:

private void addImageResource(final MimeMultipart content, final String resourceName,
    final String resourceTitle) throws MessagingException, IOException {
    MimeBodyPart msgBodyPart = new MimeBodyPart();
    URL imgURL = getClass().getClassLoader().getResource(resourceName);
    final DataSource dsImg = new FileDataSource(imgURL.getFile());
    msgBodyPart.setDataHandler(new DataHandler(dsImg));
    msgBodyPart.setHeader("Content-ID", resourceTitle);
    content.addBodyPart(msgBodyPart);
}
于 2012-09-18T10:15:17.800 に答える