Jsp-sending-email

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

JSP-電子メールの送信

この章では、JSPを使用して電子メールを送信する方法について説明します。 JSPを使用して電子メールを送信するには、 JavaMail API と* Java Activation Framework(JAF)*がマシンにインストールされている必要があります。

  • Javaの標準Webサイトからhttps://java.sun.com/products/javamail/[JavaMail(Version 1.2)]の最新バージョンをダウンロードできます。
  • JavaBeans Activation Frameworkの最新バージョンhttps://www.oracle.com/technetwork/java/javase/jaf-136260l[JAF(Version 1.0.2)]は、Javaの標準Webサイトからダウンロードできます。

これらのファイルを、新しく作成した最上位ディレクトリにダウンロードして解凍します。 両方のアプリケーション用の多数のjarファイルがあります。 CLASSPATHに mail.jar および activation.jar ファイルを追加する必要があります。

簡単なメールを送信する

以下は、マシンから簡単なメールを送信する例です。 localhost はインターネットに接続されており、メールを送信するのに十分な能力があると想定されています。 Java Email APIパッケージとJAFパッケージのすべての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;

  //Recipient's email ID needs to be mentioned.
   String to = "[email protected]";

  //Sender's email ID needs to be mentioned
   String from = "[email protected]";

  //Assuming you are sending email from localhost
   String host = "localhost";

  //Get system properties object
   Properties properties = System.getProperties();

  //Setup mail server
   properties.setProperty("mail.smtp.host", host);

  //Get the default Session object.
   Session mailSession = Session.getDefaultInstance(properties);

   try {
     //Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(mailSession);

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

     //Set To: header field of the header.
      message.addRecipient(Message.RecipientType.TO,
                               new InternetAddress(to));
     //Set Subject: header field
      message.setSubject("This is the Subject Line!");

     //Now set the actual message
      message.setText("This is actual message");

     //Send 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>

上記のコードを SendEmail.jsp ファイルに配置し、URL http://localhost:8080/SendEmail.jsp を使用してこのJSPを呼び出します。 これは、指定されたメールID *[email protected]*にメールを送信するのに役立ちます。 次の応答が表示されます-

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

あなたが複数の受信者に電子メールを送信したい場合は、次の方法を使用して複数の電子メールIDを指定します-

void addRecipients(Message.RecipientType type, Address[] addresses)
throws MessagingException

ここにパラメータの説明があります-

  • type -これは、TO、CC、またはBCCに設定されます。 ここで、CCはカーボンコピーを表し、BCCはブラックカーボンコピーを表します。 例_Message.RecipientType.TO_
  • アドレス-これは電子メールIDの配列です。 電子メールIDを指定するときにInternetAddress()メソッドを使用する必要があります

HTMLメールを送信する

以下は、マシンからHTMLメールを送信する例です。 localhost はインターネットに接続されており、メールを送信するのに十分な能力があると想定されています。 * Java Email APIパッケージ*および* JAFパッケージ*のすべてのjarファイルがCLASSPATHで利用可能であることを確認してください。

この例は前の例と非常に似ていますが、ここでは* setContent()メソッドを使用して、2番目の引数が *"text/html" であるコンテンツを設定し、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;

  //Recipient's email ID needs to be mentioned.
   String to = "[email protected]";

  //Sender's email ID needs to be mentioned
   String from = "[email protected]";

  //Assuming you are sending email from localhost
   String host = "localhost";

  //Get system properties object
   Properties properties = System.getProperties();

  //Setup mail server
   properties.setProperty("mail.smtp.host", host);

  //Get the default Session object.
   Session mailSession = Session.getDefaultInstance(properties);

   try {
     //Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(mailSession);

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

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

     //Set Subject: header field
      message.setSubject("This is the Subject Line!");

     //Send the actual HTML message, as big as you like
      message.setContent("<h1>This is actual message</h1>", "text/html" );

     //Send message
      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を使用して、特定の電子メールIDで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;

  //Recipient's email ID needs to be mentioned.
   String to = "[email protected]";

  //Sender's email ID needs to be mentioned
   String from = "[email protected]";

  //Assuming you are sending email from localhost
   String host = "localhost";

  //Get system properties object
   Properties properties = System.getProperties();

  //Setup mail server
   properties.setProperty("mail.smtp.host", host);

  //Get the default Session object.
   Session mailSession = Session.getDefaultInstance(properties);

   try {
     //Create a default MimeMessage object.
      MimeMessage message = new MimeMessage(mailSession);

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

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

     //Set Subject: header field
      message.setSubject("This is the Subject Line!");

     //Create the message part
      BodyPart messageBodyPart = new MimeBodyPart();

     //Fill the message
      messageBodyPart.setText("This is message body");

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

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

     //Part two is attachment
      messageBodyPart = new MimeBodyPart();

      String filename = "file.txt";
      DataSource source = new FileDataSource(filename);
      messageBodyPart.setDataHandler(new DataHandler(source));
      messageBodyPart.setFileName(filename);
      multipart.addBodyPart(messageBodyPart);

     //Send the complete message parts
      message.setContent(multipart );

     //Send message
      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 Attachment Email using JSP</title>
   </head>

   <body>
      <center>
         <h1>Send Attachment Email using JSP</h1>
      </center>

      <p align = "center">
         <%out.println("Result: " + result + "\n");%>
      </p>
   </body>
</html>

ここで、上記のJSPを実行して、指定された電子メールIDのメッセージとともにファイルを添付ファイルとして送信します。

ユーザー認証部

認証のためにメールサーバーにユーザーIDとパスワードを提供する必要がある場合は、次のようにこれらのプロパティを設定できます-

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

電子メール送信メカニズムの残りの部分は、上記で説明したとおりです。

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

あなたは、電子メールのパラメータを受け入れるためにHTMLフォームを使用することができますし、次のようにすべての情報を取得するために*リクエスト*オブジェクトを使用することができます-

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

すべての情報を入手したら、上記のプログラムを使用してメールを送信できます。