Javamail-api-send-inlineimage-in-email

提供:Dev Guides
移動先:案内検索

JavaMail API-インライン画像でメールを送信する

以下は、インラインイメージを使用してマシンからHTMLメールを送信する例です。 ここでは、JangoSMPTサーバーを使用して、宛先メールアドレスにメールを送信しています。 設定については、リンク:/javamail_api/javamail_api_environment_setup [Environment Setup]の章で説明しています。

インライン画像を含むメールを送信するには、次の手順に従います。

  • セッションを取得する
  • デフォルトのMimeMessageオブジェクトを作成し、メッセージに_From、_ To、 _Subject_を設定します。
  • MimeMultipartオブジェクトを作成します。
  • この例では、電子メールにHTML部分と画像があります。 したがって、最初にHTMLコンテンツを作成し、マルチパートオブジェクトに次のように設定します。
//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);
  • 次に、次のようにDatahandlerを作成して画像を追加します。
//second part (the image)
messageBodyPart = new MimeBodyPart();
DataSource fds = new FileDataSource(
 "/home/manisha/javamail-mini-logo.png");

messageBodyPart.setDataHandler(new DataHandler(fds));
messageBodyPart.setHeader("Content-ID", "<image>");
  • 次に、メッセージのマルチパートを次のように設定します。
message.setContent(multipart);
  • Transportオブジェクトを使用してメッセージを送信します。

Javaクラスを作成する

Javaクラスファイル SendInlineImagesInEmail を作成します。その内容は次のとおりです。

package com.finddevguides;

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.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 SendInlineImagesInEmail {
   public static void main(String[] args) {
     //Recipient's email ID needs to be mentioned.
      String to = "[email protected]";

     //Sender's email ID needs to be mentioned
      String from = "[email protected]";
      final String username = "manishaspatil";//change accordingly
      final String password = "******";//change accordingly

     //Assuming you are sending email through relay.jangosmtp.net
      String host = "relay.jangosmtp.net";

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

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

      try {

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

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

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

        //Set Subject: header field
         message.setSubject("Testing Subject");

        //This mail has 2 part, the BODY 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 (the image)
         messageBodyPart = new MimeBodyPart();
         DataSource fds = new FileDataSource(
            "/home/manisha/javamail-mini-logo.png");

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

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

        //put everything together
         message.setContent(multipart);
        //Send message
         Transport.send(message);

         System.out.println("Sent message successfully....");

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

ホストプロバイダーJangoSMTPが提供するSMTPサーバーを使用しているため、ユーザー名とパスワードを認証する必要があります。 _javax.mail.PasswordAuthentication_クラスは、パスワードの認証に使用されます。

コンパイルして実行する

クラスの準備ができたので、上記のクラスをコンパイルしましょう。 クラスSendInlineImagesInEmail.javaをディレクトリ /home/manisha/JavaMailAPIExercise に保存しました。 クラスパスに_javax.mail.jar_および_activation.jar_のjarが必要です。 以下のコマンドを実行して、コマンドプロンプトからクラス(両方のjarが/home/manisha/ディレクトリに配置されます)をコンパイルします。

javac -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail.java

クラスがコンパイルされたので、次のコマンドを実行して実行します。

java -cp/home/manisha/activation.jar:/home/manisha/javax.mail.jar: SendInlineImagesInEmail

出力を検証する

コマンドコンソールに次のメッセージが表示されます。

Sent message successfully....

JangoSMTPを介してGmailアドレスにメールを送信しているため、Gmailアカウントの受信トレイで次のメールが受信されます。

JavaMail APIインライン画像付きメール送信