English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

JSP メール送信

JSPを使用してメール送信機能を実現することは簡単ですが、JavaMail APIが必要であり、JavaBean Activation Frameworkをインストールする必要があります。

  • 最新バージョンのJavaMailをJavaウェブサイトからダウンロードできます。 JavaMail、ウェブページの右側に ダウンロード リンクをクリックしてダウンロードしてください。

  • 最新バージョンのJavaMailをJavaウェブサイトからダウンロードできます。 JAF(バージョン 1.1.1)

これらのファイルをダウンロードして解凍し、ルートディレクトリにアクセスすると、一連のjarパッケージが見つかります。mail.jarパッケージとactivation.jarパッケージをCLASSPATH変数に追加してください。

簡単なメールの送信

この例では、localhostがネットワークに接続されており、メールを送信できることを前提として、あなたのマシンから簡単なメールを送信する方法を示しています。その一方で、mail.jarパッケージとactivation.jarパッケージがCLASSPATH変数に追加されていることをもう一度確認してください。

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   // 受信者の電子メール
   String to = "[email protected]";
   // 送信者の電子メール
   String from = "[email protected]";
   // ローカルホストから電子メールを送信していると仮定します
   String host = "localhost";
   // システムプロパティオブジェクトを取得します
   Properties properties = System.getProperties();
   // メールサーバーを設定します
   properties.setProperty("mail.smtp.host", host);
   // デフォルトのSessionオブジェクトを取得します。
   Session mailSession = Session.getDefaultInstance(properties);
   try{
      // デフォルトのMimeMessageオブジェクトを作成します。
      MimeMessage message = new MimeMessage(mailSession);
      // From:ヘッダーフィールドを設定する
      message.setFrom(new InternetAddress(from));
      // To:ヘッダーフィールドを設定する
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
      // Subject:ヘッダーフィールドを設定する
      message.setSubject("This is the Subject Line!");
      // 現在設定している実際のメッセージ
      message.setText("This is actual message");
      // メッセージを送信する
      Transport.send(message);
      result = "Sent message successfully....";
   }catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: unable to send message....";
   }
%>
<html>
<head>
<title>Send Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p align="center">
<% 
   out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>

現在http:にアクセスしてください//localhost:8080/SendEmail.jspは、[email protected]にメールを送信し、以下の結果を表示します:

JSPを使用してメールを送信
Result: メッセージを成功送信しました....

メールを複数の人に送信したい場合、以下に示すメソッドを使用して複数のメールアドレスを指定できます:

void addRecipients(Message.RecipientType type, 
                   Address[] addresses)
MessagingExceptionがスローされます

パラメータの説明は以下の通りです:

  • type:この値はTO(宛先)、CCまたはBCCに設定されます。CCはCarbon Copy(抄送)を、BCCはBlind Carbon Copy(密件抄送)を意味します。例プログラムではTOを使用しています。

  • addresses:これはメールアドレスの配列です。メールアドレスを指定する場合は、InternetAddress()メソッドを使用する必要があります。

HTMLメールの送信

この例では、簡単なHTMLメールを送信します。localhostがネットワークに接続されており、メールを送信できることを前提としています。その一方で、mail.jarパッケージとactivation.jarパッケージがCLASSPATH変数に追加されていることをもう一度確認してください。

このインスタンスは前のインスタンスと非常に似ていますが、このインスタンスではsetContent()メソッドを使用して、"text}}/html"を二番目の引数として渡して、メッセージにHTML内容が含まれていることを示します。

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   // 受信者の電子メール
   String to = "[email protected]";
   // 送信者の電子メール
   String from = "[email protected]";
   // ローカルホストから電子メールを送信していると仮定します
   String host = "localhost";
   // システムプロパティオブジェクトを取得します
   Properties properties = System.getProperties();
   // メールサーバーを設定します
   properties.setProperty("mail.smtp.host", host);
   // デフォルトのSessionオブジェクトを取得します。
   Session mailSession = Session.getDefaultInstance(properties);
   try{
      // デフォルトのMimeMessageオブジェクトを作成します。
      MimeMessage message = new MimeMessage(mailSession);
      // From:ヘッダーフィールドを設定する
      message.setFrom(new InternetAddress(from));
      // To:ヘッダーフィールドを設定する
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
      // Subject:ヘッダーフィールドを設定する
      message.setSubject("This is the Subject Line!");
     
      // HTMLメッセージを設定
      message.setContent("<h1>This is actual message</h1>",
                            "text/html" );
      // メッセージを送信する
      Transport.send(message);
      result = "Sent message successfully....";
   }catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: unable to send message....";
   }
%>
<html>
<head>
<title>Send HTML Email using JSP</title>
</head>
<body>
<center>
<h1>Send Email using JSP</h1>
</center>
<p align="center">
<% 
   out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>

今や、上記のJSPファイルを使用してHTMLメッセージの電子メールを送信することができます。

メールに添付ファイルを含める

このインスタンスは、添付ファイルを含むメールを送信する方法を教えています。

<%@ page import="java.io.*,java.util.*,javax.mail.*"%>
<%@ page import="javax.mail.internet.*,javax.activation.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%
   String result;
   // 受信者の電子メール
   String to = "[email protected]";
   // 送信者の電子メール
   String from = "[email protected]";
   // ローカルホストから電子メールを送信していると仮定します
   String host = "localhost";
   // システムプロパティオブジェクトを取得します
   Properties properties = System.getProperties();
   // メールサーバーを設定します
   properties.setProperty("mail.smtp.host", host);
   // デフォルトのSessionオブジェクトを取得します。
   Session mailSession = Session.getDefaultInstance(properties);
   try{
      // デフォルトのMimeMessageオブジェクトを作成します。
      MimeMessage message = new MimeMessage(mailSession);
      // From:ヘッダーフィールドを設定する
      message.setFrom(new InternetAddress(from));
      // To:ヘッダーフィールドを設定する
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
      // Subject:ヘッダーフィールドを設定する
      message.setSubject("This is the Subject Line!");
      // メッセージ部分を作成する
      BodyPart messageBodyPart = new MimeBodyPart();
      // メッセージを埋め込む
      messageBodyPart.setText("This is message body");
      
      // マルチメディアメッセージを作成する
      Multipart multipart = new MimeMultipart();
      // テキストメッセージ部分を設定する
      multipart.addBodyPart(messageBodyPart);
      // 添付部分
      messageBodyPart = new MimeBodyPart();
      String filename = "file.txt";
      DataSource source = new FileDataSource(filename);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(filename);
      multipart.addBodyPart(messageBodyPart);
      // 完全なメッセージを送信する
      message.setContent(multipart );
      // メッセージを送信する
      Transport.send(message);
      String title = "Send Email";
      result = "Sent message successfully....";
   }catch (MessagingException mex) {
      mex.printStackTrace();
      result = "Error: unable to send message....";
   }
%>
<html>
<head>
<title>Send Attachement Email using JSP</title>
</head>
<body>
<center>
<h1>Send Attachement Email using JSP</h1>
</center>
<p align="center">
<% 
   out.println("Result: " + result + "\n");
%>
</p>
</body>
</html>

ユーザー認証部分

メールサーバーがユーザー認証にユーザー名とパスワードが必要な場合、以下のように設定できます:

 properties.setProperty("mail.user", "myuser");
 properties.setProperty("mail.password", "mypwd");

フォームを使用してメールを送信

HTML フォームを使用して一封のメールを受け取り、request オブジェクトを使用してすべてのメール情報を取得します:

String to = request.getParameter("to");
String from = request.getParameter("from");
String subject = request.getParameter("subject");
String messageText = request.getParameter("body");

以上の情報を取得した後、前述の例を使用してメールを送信できます。