JSP メール送信

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

  • Java Webサイトから最新バージョンをダウンロードできます。JavaMailWebページの右側にはDownloadsリンクがあり、それをクリックしてダウンロードします。
  • Java Webサイトから最新バージョンをダウンロードできます。JAF(バージョン 1.1.1)。

また、当サイトが提供するダウンロードリンクを使用できます:

  • JavaMail mail.jar 1.4.5
  • JAF(バージョン 1.1.1) activation.jar

これらのファイルをダウンロードして解凍すると、ルートディレクトリに一連の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 = "abcd@gmail.com";

   // 发件人的电子邮件
   String from = "mcmohd@gmail.com";

   // 假设你是从本地主机发送电子邮件
   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: 头部的header字段
      message.setFrom(new InternetAddress(from));
      // 设置 To: 头部的header字段
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
      // 设置 Subject: header字段
      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 にアクセスすると、abcd@gmail.com にメールが送信され、次の結果が表示されます:

Send Email using JSP
Result: Sent message successfully....

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

void addRecipients(Message.RecipientType type, 
                   Address[] addresses)
throws 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"を2番目のパラメータとして渡して、メッセージに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 = "abcd@gmail.com";

   // 发件人的电子邮件
   String from = "mcmohd@gmail.com";

   // 假设你是从本地主机发送电子邮件
   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: 头部的header字段
      message.setFrom(new InternetAddress(from));
      // 设置 To: 头部的header字段
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
      // 设置 Subject: header字段
      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 = "abcd@gmail.com";

   // 发件人的电子邮件
   String from = "mcmohd@gmail.com";

   // 假设你是从本地主机发送电子邮件
   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: 头部的header字段
      message.setFrom(new InternetAddress(from));

      // 设置 To: 头部的header字段
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));

      // 设置 Subject: header字段
      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");

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

その他の拡張機能