GmailのSMTPは無料で利用できます。これはシステム開発にとってとてもありがたいことです。今回はefwのメール送信モジュールを利用して、GmailのSMTPへ送信してみます。
Gmailのアプリパスワード作成
googleのアカウント管理画面のサイトメニューから「セキュリティ」のアイコンをクリックして、右側から「googleにログインする方法」の2段階認証プロセスを選択します。
最後までスクロールして、「アプリパスワード」を選択します。
メールとWindowsパソコンを選んで作成ボタンを押してパスワードを生成します。
efwのcontext.xmlの設定
以下のようにcontext.xmlにリソースを設定します。nameは「mail/efw」です。これは、efw.propertiesに定義したefw.mail.resourceの値です。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Context>
<Context>
<Resource
name = "mail/efw"
auth = "Container"
type = "javax.mail.Session"
username = "[your account]@gmail.com"
password = "[your password]"
mail.debug = "false"
mail.user = "[your account]@gmail.com"
mail.from = "[your account]@gmail.com"
mail.transport.protocol="smtp"
mail.smtp.host = "smtp.gmail.com"
mail.smtp.auth = "true"
mail.smtp.port = "587"
mail.smtp.starttls.enable="true"
description = "E-Mail Resource"
/>
</Context>
メールリソースに設定可能な属性については、以下の表をご参考ください。
Name | Type | Description |
---|---|---|
mail.smtp.user | String | Default user name for SMTP. |
mail.smtp.host | String | The SMTP server to connect to. |
mail.smtp.port | int | The SMTP server port to connect to, if the connect() method doesn't explicitly specify one. Defaults to 25. |
mail.smtp.connectiontimeout | int | Socket connection timeout value in milliseconds.This timeout is implemented by java.net.Socket.Default is infinite timeout. |
mail.smtp.timeout | int | Socket read timeout value in milliseconds.This timeout is implemented by java.net.Socket.Default is infinite timeout. |
mail.smtp.writetimeout | int | Socket write timeout value in milliseconds.This timeout is implemented by using a java.util.concurrent.ScheduledExecutorService per connectionthat schedules a thread to close the socket if the timeout expires.Thus, the overhead of using this timeout is one thread per connection.Default is infinite timeout. |
mail.smtp.from | String | Email address to use for SMTP MAIL command. This sets the envelope return address. Defaults to msg.getFrom() or InternetAddress.getLocalAddress(). NOTE: mail.smtp.user was previously used for this. |
mail.smtp.localhost | String | Local host name used in the SMTP HELO or EHLO command.Defaults to InetAddress.getLocalHost().getHostName() .Should not normally need to be set if your JDK and your name service are configured properly. |
mail.smtp.localaddress | String | Local address (host name) to bind to when creating the SMTP socket. Defaults to the address picked by the Socket class. Should not normally need to be set, but useful with multi-homed hosts where it's important to pick a particular local address to bind to. |
mail.smtp.localport | int | Local port number to bind to when creating the SMTP socket. Defaults to the port number picked by the Socket class. |
mail.smtp.ehlo | boolean | If false, do not attempt to sign on with the EHLO command. Defaults to true. Normally failure of the EHLO command will fallback to the HELO command; this property exists only for servers that don't fail EHLO properly or don't implement EHLO properly. |
mail.smtp.auth | boolean | If true, attempt to authenticate the user using the AUTH command. Defaults to false. |
mail.smtp.auth.mechanisms | String | If set, lists the authentication mechanisms to consider, and the order in which to consider them. Only mechanisms supported by the server and supported by the current implementation will be used.The default is "LOGIN PLAIN DIGEST-MD5 NTLM" , which includes all the authentication mechanisms supported by the current implementation except XOAUTH2. |
mail.smtp.auth.login.disable | boolean | If true, prevents use of the AUTH LOGIN command. Default is false. |
mail.smtp.auth.plain.disable | boolean | If true, prevents use of the AUTH PLAIN command. Default is false. |
mail.smtp.auth.digest-md5.disable | boolean | If true, prevents use of the AUTH DIGEST-MD5 command. Default is false. |
mail.smtp.auth.ntlm.disable | boolean | If true, prevents use of the AUTH NTLM command. Default is false. |
mail.smtp.auth.ntlm.domain | String | The NTLM authentication domain. |
mail.smtp.auth.ntlm.flags | int | NTLM protocol-specific flags. See http://curl.haxx.se/rfc/ntlm.html#theNtlmFlags for details. |
mail.smtp.auth.xoauth2.disable | boolean | If true, prevents use of the AUTHENTICATE XOAUTH2 command. Because the OAuth 2.0 protocol requires a special access token instead ofa password, this mechanism is disabled by default. Enable it by explicitlysetting this property to "false" or by setting the "mail.smtp.auth.mechanisms"property to "XOAUTH2". |
mail.smtp.submitter | String | The submitter to use in the AUTH tag in the MAIL FROM command. Typically used by a mail relay to pass along information about theoriginal submitter of the message. See also the setSubmitter method of SMTPMessage . Mail clients typically do not use this. |
mail.smtp.dsn.notify | String | The NOTIFY option to the RCPT command. Either NEVER, or somecombination of SUCCESS, FAILURE, and DELAY (separated by commas). |
mail.smtp.dsn.ret | String | The RET option to the MAIL command. Either FULL or HDRS. |
mail.smtp.allow8bitmime | boolean | If set to true, and the server supports the 8BITMIME extension, textparts of messages that use the "quoted-printable" or "base64" encodingsare converted to use "8bit" encoding if they follow the RFC2045 rulesfor 8bit text. |
mail.smtp.sendpartial | boolean | If set to true, and a message has some valid and some invalidaddresses, send the message anyway, reporting the partial failure witha SendFailedException. If set to false (the default), the message isnot sent to any of the recipients if there is an invalid recipientaddress. |
mail.smtp.sasl.enable | boolean | If set to true, attempt to use the javax.security.sasl package tochoose an authentication mechanism for login. Defaults to false. |
mail.smtp.sasl.mechanisms | String | A space or comma separated list of SASL mechanism names to tryto use. |
mail.smtp.sasl.authorizationid | String | The authorization ID to use in the SASL authentication. If not set, the authentication ID (user name) is used. |
mail.smtp.sasl.realm | String | The realm to use with DIGEST-MD5 authentication. |
mail.smtp.sasl.usecanonicalhostname | boolean | If set to true, the canonical host name returned byInetAddress.getCanonicalHostName is passed to the SASL mechanism, instead of the host name used to connect. Defaults to false. |
mail.smtp.quitwait | boolean | If set to false, the QUIT command is sentand the connection is immediately closed. If set to true (the default), causes the transport to waitfor the response to the QUIT command. |
mail.smtp.reportsuccess | boolean | If set to true, causes the transport to include anSMTPAddressSucceededException for each address that is successful. Note also that this will cause aSendFailedException to be thrown from thesendMessage method ofSMTPTransport even if all addresses were correct and the message was sentsuccessfully. |
mail.smtp.socketFactory | SocketFactory | If set to a class that implements thejavax.net.SocketFactory interface, this classwill be used to create SMTP sockets. Note that this is aninstance of a class, not a name, and must be set using theput method, not the setProperty method. |
mail.smtp.socketFactory.class | String | If set, specifies the name of a class that implements thejavax.net.SocketFactory interface. This classwill be used to create SMTP sockets. |
mail.smtp.socketFactory.fallback | boolean | If set to true, failure to create a socket using the specifiedsocket factory class will cause the socket to be created usingthe java.net.Socket class. Defaults to true. |
mail.smtp.socketFactory.port | int | Specifies the port to connect to when using the specified socketfactory. If not set, the default port will be used. |
mail.smtp.ssl.enable | boolean | If set to true, use SSL to connect and use the SSL port by default. Defaults to false for the "smtp" protocol and true for the "smtps" protocol. |
mail.smtp.ssl.checkserveridentity | boolean | If set to true, check the server identity as specified byRFC 2595. These additional checks based on the content of the server's certificateare intended to prevent man-in-the-middle attacks. Defaults to false. |
mail.smtp.ssl.trust | String | If set, and a socket factory hasn't been specified, enables use of aMailSSLSocketFactory . If set to "*", all hosts are trusted. If set to a whitespace separated list of hosts, those hosts are trusted. Otherwise, trust depends on the certificate the server presents. |
mail.smtp.ssl.socketFactory | SSLSocketFactory | If set to a class that extends thejavax.net.ssl.SSLSocketFactory class, this classwill be used to create SMTP SSL sockets. Note that this is aninstance of a class, not a name, and must be set using theput method, not the setProperty method. |
mail.smtp.ssl.socketFactory.class | String | If set, specifies the name of a class that extends thejavax.net.ssl.SSLSocketFactory class. This classwill be used to create SMTP SSL sockets. |
mail.smtp.ssl.socketFactory.port | int | Specifies the port to connect to when using the specified socketfactory. If not set, the default port will be used. |
mail.smtp.ssl.protocols | string | Specifies the SSL protocols that will be enabled for SSL connections. The property value is a whitespace separated list of tokens acceptableto the javax.net.ssl.SSLSocket.setEnabledProtocols method. |
mail.smtp.ssl.ciphersuites | string | Specifies the SSL cipher suites that will be enabled for SSL connections. The property value is a whitespace separated list of tokens acceptableto the javax.net.ssl.SSLSocket.setEnabledCipherSuites method. |
mail.smtp.starttls.enable | boolean | If true, enables the use of the STARTTLS command (ifsupported by the server) to switch the connection to a TLS-protectedconnection before issuing any login commands. If the server does not support STARTTLS, the connection continues withoutthe use of TLS; see themail.smtp.starttls.required property to fail if STARTTLS isn't supported. Note that an appropriate trust store must configured so that the clientwill trust the server's certificate. Defaults to false. |
mail.smtp.starttls.required | boolean | If true, requires the use of the STARTTLS command. If the server doesn't support the STARTTLS command, or the commandfails, the connect method will fail. Defaults to false. |
mail.smtp.proxy.host | string | Specifies the host name of an HTTP web proxy server that will be used forconnections to the mail server. |
mail.smtp.proxy.port | string | Specifies the port number for the HTTP web proxy server. Defaults to port 80. |
mail.smtp.proxy.user | string | Specifies the user name to use to authenticate with the HTTP web proxy server. By default, no authentication is done. |
mail.smtp.proxy.password | string | Specifies the password to use to authenticate with the HTTP web proxy server. By default, no authentication is done. |
mail.smtp.socks.host | string | Specifies the host name of a SOCKS5 proxy server that will be used forconnections to the mail server. |
mail.smtp.socks.port | string | Specifies the port number for the SOCKS5 proxy server. This should only need to be used if the proxy server is not usingthe standard port number of 1080. |
mail.smtp.mailextension | String | Extension string to append to the MAIL command. The extension string can be used to specify standard SMTPservice extensions as well as vendor-specific extensions. Typically the application should use theSMTPTransport method supportsExtension to verify that the server supports the desired service extension. See RFC 1869and other RFCs that define specific extensions. |
mail.smtp.userset | boolean | If set to true, use the RSET command instead of the NOOP commandin the isConnected method. In some cases sendmail will respond slowly after many NOOP commands;use of RSET avoids this sendmail issue. Defaults to false. |
mail.smtp.noop.strict | boolean | If set to true (the default), insist on a 250 response code from the NOOPcommand to indicate success. The NOOP command is used by theisConnected method to determineif the connection is still alive. Some older servers return the wrong response code on success, someservers don't implement the NOOP command at all and so always returna failure code. Set this property to false to handle serversthat are broken in this way. Normally, when a server times out a connection, it will send a 421response code, which the client will see as the response to the nextcommand it issues. Some servers send the wrong failure response code when timing out aconnection. Do not set this property to false when dealing with servers that arebroken in this way. |
jspのソース
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="efw" uri="efw" %>
<!DOCTYPE HTML>
<HTML>
<HEAD>
<title>mail テスト</title>
<efw:Client lang="jp"/>
</HEAD>
<BODY>
TO:<input type="text" id="txtTo"><br>
CC:<input type="text" id="txtCC"><br>
BCC:<input type="text" id="txtBCC"><br>
開封確認:<input type="text" id="txtMDN"><br>
発信者:<input type="text" id="txtFrom"><br>
名称:<input type="text" id="txtName"><br>
<button onclick="Efw('helloMail_submit')">メール送信</button>
<br>
</BODY>
</HTML>
jsイベント
var helloMail_submit={};
helloMail_submit.paramsFormat={
"#txtTo":null,
"#txtName":null,
"#txtCC":null,
"#txtBCC":null,
"#txtMDN":null,
"#txtFrom":null,
};
helloMail_submit.fire=function(params){
mail.send("mails","hello",{
to:params["#txtTo"],
nm:params["#txtName"],
cc:params["#txtCC"],
bcc:params["#txtBCC"],
mdn:params["#txtMDN"],
from:params["#txtFrom"],
});
}
efwのメールテンプレート
WEB-INF/efw/mail/mails.xmlにメールテンプレートを登録します。以下のサンプルのように、開封確認送信先という特殊機能をサポートしています。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mails>
<mails>
<!-- パスワード送信メール -->
<mail id="hello">
<to>:to</to><!-- 送信先 -->
<cc>:cc</cc><!-- CC先 -->
<bcc>:bcc</bcc><!-- BCC先 -->
<mdn>:mdn</mdn><!-- 開封確認送信先 -->
<from>:from</from><!-- 発信者 -->
<subject>helloメール送信</subject>
<body>
:nm 様:
テストです。
</body>
</mail>
</mails>
テスト画面のイメージ
以下はテストエビデンスです。発信者設定は、context.xmlに定義したfromが有効になっています。個別メールに定義する発信者はまだ有効になっていません。この件についてまだ調査してません。TODOですね。
送信先に日本語名を付けたい場合、以下のようにメールアドレスを加工すれば実現できます。
あいうえお<test@test.test>
jar入手
efw-4.XX.XXX.jarは、app/WEB-INF/libフォルダに格納します。
<dependency>
<groupId>io.github.efwgrp</groupId>
<artifactId>efw</artifactId>
<version>4.07.000</version>
</dependency>
jdk15以上の場合、関連jarが必要です。
<dependency>
<groupId>org.openjdk.nashorn</groupId>
<artifactId>nashorn-core</artifactId>
<version>15.4</version>
</dependency>
javax.mail-1.6.2.jarは、tomcat/libフォルダに格納します。
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
もしご利用のJDKがjava11以降の場合、javax.activation-1.2.0.jarも必要です。場所はtomcat/libフォルダです。
<dependency>
<groupId>com.sun.activation</groupId>
<artifactId>javax.activation</artifactId>
<version>1.2.0</version>
</dependency>
今回のサンプルは以下のリンクからダウンロードできます。