Servlets-sending-email
サーブレット-電子メールの送信
サーブレットを使用して電子メールを送信するのは非常に簡単ですが、最初に JavaMail API および* Java Activation Framework(JAF)*をマシンにインストールする必要があります。
- Javaの標準Webサイトからhttps://java.sun.com/products/javamail/[JavaMail(Version 1.2)]の最新バージョンをダウンロードできます。
- 最新バージョンのhttps://java.sun.com/products/javabeans/glasgow/jafl[JAF(Version 1.1.1)]は、Javaの標準Webサイトからダウンロードできます。
これらのファイルをダウンロードして解凍すると、新しく作成された最上位ディレクトリに、両方のアプリケーションの多数のjarファイルがあります。 CLASSPATHに mail.jar および activation.jar ファイルを追加する必要があります。
簡単なメールを送信する
以下は、マシンから簡単なメールを送信する例です。 ここでは、 localhost がインターネットに接続されており、メールを送信するのに十分な能力があると想定されています。 同時に、Java Email APIパッケージと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はブラックカーボンコピーを表します。 例_Message.RecipientType.TO_
- アドレス-これは電子メールIDの配列です。 電子メールIDを指定するときにInternetAddress()メソッドを使用する必要があります。
HTMLメールを送信する
以下は、マシンからHTMLメールを送信する例です。 ここでは、 localhost がインターネットに接続されており、メールを送信するのに十分な能力があると想定されています。 同時に、Java Email APIパッケージと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");
上記で説明したように、電子メール送信メカニズムの残りの部分は残ります。