サーブレット-メールの送信

サーブレットを使用してメールを送信するのは簡単ですが、最初に必要なのは JavaMail API そして Java Activation Framework (JAF) マシンにインストールされています。

  • JavaMailの最新バージョン(バージョン1.2)は、Javaの標準Webサイトからダウンロードできます。

  • JAFの最新バージョン(バージョン1.1.1)は、Javaの標準Webサイトからダウンロードできます。

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

簡単なメールを送信する

これは、マシンから簡単な電子メールを送信する例です。ここでは、localhostインターネットに接続されており、電子メールを送信するのに十分な能力があります。同時に、Java EmailAPIパッケージとJAFパッケージのすべてのjarファイルがCLASSPATHで使用可能であることを確認してください。

// File Name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // 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
      Properties properties = System.getProperties();
 
      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
 
      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);
      
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      try {
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
         
         // 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);
         String title = "Send Email";
         String res = "Sent message successfully....";
         String docType =
            "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
         
         out.println(docType +
            "<html>\n" +
               "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor = \"#f0f0f0\">\n" +
                  "<h1 align = \"center\">" + title + "</h1>\n" +
                  "<p align = \"center\">" + res + "</p>\n" +
               "</body>
            </html>"
         );
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

次に、上記のサーブレットをコンパイルして、web.xmlに次のエントリを作成しましょう。

....
 <servlet>
   <servlet-name>SendEmail</servlet-name>
   <servlet-class>SendEmail</servlet-class>
</servlet>
 
<servlet-mapping>
   <servlet-name>SendEmail</servlet-name>
   <url-pattern>/SendEmail</url-pattern>
</servlet-mapping>
....

ここで、URL http:// localhost:8080 / SendEmailを使用してこのサーブレットを呼び出します。これにより、指定された電子メールID [email protected]電子メールが送信され、次の応答が表示されます-

Send Email

Sent message successfully....

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

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

パラメータの説明は次のとおりです-

  • type−これは、TO、CC、またはBCCに設定されます。ここで、CCはカーボンコピーを表し、BCCはブラックカーボンコピーを表します。メッセージの.RecipientType.TO

  • addresses−これはEメールIDの配列です。電子メールIDを指定するときは、InternetAddress()メソッドを使用する必要があります。

HTMLメールを送信する

これは、マシンからHTMLメールを送信する例です。ここでは、localhostインターネットに接続されており、電子メールを送信するのに十分な能力があります。同時に、Java EmailAPIパッケージとJAFパッケージのすべてのjarファイルがCLASSPATHで使用可能であることを確認してください。

この例は前の例と非常に似ていますが、ここではsetContent()メソッドを使用して、2番目の引数が「text / html」であるコンテンツを設定し、HTMLコンテンツがメッセージに含まれるように指定しています。

この例を使用すると、好きなだけ大きなHTMLコンテンツを送信できます。

// File Name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail extends HttpServlet {
    
   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // 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
      Properties properties = System.getProperties();
 
      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
 
      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);
      
      // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      try {
         
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
         
         // 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);
         String title = "Send Email";
         String res = "Sent message successfully....";
         String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
         
         out.println(docType +
            "<html>\n" +
               "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor = \"#f0f0f0\">\n" +
                  "<h1 align = \"center\">" + title + "</h1>\n" +
                  "<p align = \"center\">" + res + "</p>\n" +
               "</body>
            </html>"
         );
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

上記のサーブレットをコンパイルして実行し、指定された電子メールIDでHTMLメッセージを送信します。

電子メールで添付ファイルを送信する

これは、マシンから添付ファイル付きの電子メールを送信する例です。ここでは、localhost インターネットに接続されており、電子メールを送信するのに十分な能力があります。

// File Name SendEmail.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
 
public class SendEmail extends HttpServlet {

   public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      
      // 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
      Properties properties = System.getProperties();
 
      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
 
      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);
      
	  // Set response content type
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      try {
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
 
         // 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 multipar 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";
         String res = "Sent message successfully....";
         String docType =
         "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
         
         out.println(docType +
            "<html>\n" +
               "<head><title>" + title + "</title></head>\n" +
               "<body bgcolor = \"#f0f0f0\">\n" +
                  "<h1 align = \"center\">" + title + "</h1>\n" +
                  "<p align = \"center\">" + res + "</p>\n" +
               "</body>
            </html>"
         );
      } catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

上記のサーブレットをコンパイルして実行し、ファイルを添付ファイルとして、指定された電子メールIDのメッセージとともに送信します。

ユーザー認証部分

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

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

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