1 package com.ozacc.mail.impl;
2
3 import java.io.UnsupportedEncodingException;
4 import java.util.Date;
5 import java.util.Properties;
6
7 import javax.mail.Address;
8 import javax.mail.AuthenticationFailedException;
9 import javax.mail.MessagingException;
10 import javax.mail.Session;
11 import javax.mail.Transport;
12 import javax.mail.internet.MimeMessage;
13
14 import org.apache.commons.logging.Log;
15 import org.apache.commons.logging.LogFactory;
16
17 import com.ozacc.mail.Mail;
18 import com.ozacc.mail.MailAuthenticationException;
19 import com.ozacc.mail.MailBuildException;
20 import com.ozacc.mail.MailException;
21 import com.ozacc.mail.MailSendException;
22 import com.ozacc.mail.NotConnectedException;
23 import com.ozacc.mail.SendMailPro;
24
25 /***
26 * SendMailProインターフェースの実装クラス。
27 *
28 * @since 1.0
29 * @author Tomohiro Otsuka
30 * @version $Id: SendMailProImpl.java,v 1.4.2.3 2005/01/29 23:09:36 otsuka Exp $
31 */
32 public class SendMailProImpl implements SendMailPro {
33
34 /*** smtp */
35 public static final String DEFAULT_PROTOCOL = "smtp";
36
37 /*** -1 */
38 public static final int DEFAULT_PORT = -1;
39
40 /*** localhost */
41 public static final String DEFAULT_HOST = "localhost";
42
43 /*** ISO-2022-JP */
44 public static final String JIS_CHARSET = "ISO-2022-JP";
45
46 private static final String RETURN_PATH_KEY = "mail.smtp.from";
47
48 private static Log log = LogFactory.getLog(SendMailProImpl.class);
49
50 /*** 接続タイムアウト */
51 private static final int DEFAULT_CONNECTION_TIMEOUT = 5000;
52
53 /*** 読込タイムアウト */
54 private static final int DEFAULT_READ_TIMEOUT = 5000;
55
56 private String protocol = DEFAULT_PROTOCOL;
57
58 private String host = DEFAULT_HOST;
59
60 private int port = DEFAULT_PORT;
61
62 private String username;
63
64 private String password;
65
66 private String charset = JIS_CHARSET;
67
68 private String returnPath;
69
70 private Session session;
71
72 private Transport transport;
73
74 private boolean connected;
75
76 private String messageId;
77
78 private int connectionTimeout = DEFAULT_CONNECTION_TIMEOUT;
79
80 private int readTimeout = DEFAULT_READ_TIMEOUT;
81
82 /***
83 * コンストラクタ。
84 */
85 public SendMailProImpl() {}
86
87 /***
88 * コンストラクタ。使用するSMTPサーバを指定します。
89 *
90 * @param host SMTPサーバのホスト名、またはIPアドレス
91 */
92 public SendMailProImpl(String host) {
93 this();
94 setHost(host);
95 }
96
97 /***
98 * @see com.ozacc.mail.SendMailPro#connect()
99 */
100 public synchronized void connect() throws MailException {
101 if (session == null) {
102 initSession();
103 }
104
105
106 putOnReturnPath(this.returnPath);
107
108 try {
109
110 log.debug("SMTPサーバ[" + host + "]に接続します。");
111
112 transport = session.getTransport(protocol);
113 transport.connect(host, port, username, password);
114 } catch (AuthenticationFailedException ex) {
115 log.error("SMTPサーバ[" + host + "]への接続認証に失敗しました。", ex);
116 throw new MailAuthenticationException(ex);
117 } catch (MessagingException ex) {
118 log.error("SMTPサーバ[" + host + "]への接続に失敗しました。", ex);
119 throw new MailSendException("SMTPサーバ[" + host + "]への接続に失敗しました。", ex);
120 }
121
122 log.debug("SMTPサーバ[" + host + "]に接続しました。");
123
124 connected = true;
125 }
126
127 /***
128 * Sessionの初期化を行います。
129 * タイムアウト値を設定したPropertiesをセットします。
130 */
131 private void initSession() {
132 Properties prop = new Properties();
133
134 prop.put("mail.smtp.connectiontimeout", String.valueOf(connectionTimeout));
135 prop.put("mail.smtp.timeout", String.valueOf(readTimeout));
136
137 if (username != null && !"".equals(username) && password != null && !"".equals(password)) {
138 prop.put("mail.smtp.auth", "true");
139 }
140 session = Session.getInstance(prop);
141 }
142
143 /***
144 * @see com.ozacc.mail.SendMailPro#disconnect()
145 */
146 public synchronized void disconnect() throws MailException {
147 if (connected) {
148 try {
149 log.debug("SMTPサーバ[" + host + "]との接続を切断します。");
150
151
152 transport.close();
153 connected = false;
154
155 log.debug("SMTPサーバ[" + host + "]との接続を切断しました。");
156 } catch (MessagingException ex) {
157 log.error("SMTPサーバ[" + host + "]との接続切断に失敗しました。", ex);
158 throw new MailException("SMTPサーバ[" + host + "]との接続切断に失敗しました。");
159 } finally {
160
161 releaseReturnPath(false);
162 }
163 } else {
164 log.warn("SMTPサーバ[" + host + "]との接続が確立されていない状態で、接続の切断がリクエストされました。");
165 }
166 }
167
168 /***
169 * ReturnPathをセットします。
170 *
171 * @param returnPath
172 */
173 private void putOnReturnPath(String returnPath) {
174 if (returnPath != null) {
175 session.getProperties().put(RETURN_PATH_KEY, returnPath);
176 log.debug("Return-Path[" + returnPath + "]を設定しました。");
177 }
178 }
179
180 /***
181 * ReturnPathの設定をクリアします。
182 * <p>
183 * setGlobalReturnPathAgainがtrueに指定されている場合、一旦Return-Path設定をクリアした後に、
184 * グローバルなReturn-Path(setReturnPath()メソッドで、このインスタンスにセットされたReturn-Pathアドレス)を設定します。
185 * グローバルなReturn-PathがセットされていなければReturn-Pathはクリアされたままになります。
186 * <p>
187 * クリアされた状態でsend()メソッドが実行されると、Fromの値がReturn-Pathに使用されます。
188 *
189 * @param setGlobalReturnPathAgain Return-Path設定をクリアした後、再度グローバルなReturn-Pathをセットする場合 true
190 */
191 private void releaseReturnPath(boolean setGlobalReturnPathAgain) {
192 session.getProperties().remove(RETURN_PATH_KEY);
193 log.debug("Return-Path設定をクリアしました。");
194
195 if (setGlobalReturnPathAgain && this.returnPath != null) {
196 putOnReturnPath(this.returnPath);
197 }
198 }
199
200 /***
201 * @see com.ozacc.mail.SendMailPro#send(javax.mail.internet.MimeMessage)
202 */
203 public void send(MimeMessage mimeMessage) throws MailException {
204 Address[] addresses;
205 try {
206 addresses = mimeMessage.getAllRecipients();
207 } catch (MessagingException ex) {
208 log.error("メールの送信に失敗しました。", ex);
209 throw new MailSendException("メールの送信に失敗しました。", ex);
210 }
211 processSend(mimeMessage, addresses);
212 }
213
214 /***
215 * @param mimeMessage
216 */
217 private void processSend(MimeMessage mimeMessage, Address[] addresses) {
218 if (!connected) {
219 log.error("SMTPサーバへの接続が確立されていません。");
220 throw new NotConnectedException("SMTPサーバへの接続が確立されていません。");
221 }
222
223 try {
224
225 mimeMessage.setSentDate(new Date());
226 mimeMessage.saveChanges();
227
228 log.debug("メールを送信します。");
229 transport.sendMessage(mimeMessage, addresses);
230 log.debug("メールを送信しました。");
231 } catch (MessagingException ex) {
232 log.error("メールの送信に失敗しました。", ex);
233 throw new MailSendException("メールの送信に失敗しました。", ex);
234 }
235 }
236
237 /***
238 * @see com.ozacc.mail.SendMailPro#send(com.ozacc.mail.Mail)
239 */
240 public void send(Mail mail) throws MailException {
241 if (mail.getReturnPath() != null) {
242 sendMailWithReturnPath(mail);
243 } else {
244 sendMail(mail);
245 }
246 }
247
248 /***
249 * 指定されたMailからMimeMessageを生成し、send(MimeMessage)メソッドに渡します。
250 *
251 * @param mail
252 * @throws MailException
253 */
254 private void sendMail(Mail mail) throws MailException {
255
256 MimeMessage message = createMimeMessage();
257 MimeMessageBuilder builder = new MimeMessageBuilder(message, charset);
258 try {
259 builder.buildMimeMessage(mail);
260 } catch (UnsupportedEncodingException e) {
261 throw new MailBuildException("サポートされていない文字コードが指定されました。", e);
262 } catch (MessagingException e) {
263 throw new MailBuildException("MimeMessageの生成に失敗しました。", e);
264 }
265
266 if (mail.getEnvelopeTo().length > 0) {
267 log.debug("メールはenvelope-toアドレスに送信されます。");
268 processSend(message, mail.getEnvelopeTo());
269 } else {
270 send(message);
271 }
272 }
273
274 /***
275 * 指定されたMailにセットされたReturn-Pathを設定して、メールを送信します。
276 * 同期メソッドです。
277 *
278 * @param mail
279 * @throws MailException
280 */
281 private synchronized void sendMailWithReturnPath(Mail mail) throws MailException {
282 putOnReturnPath(mail.getReturnPath().getAddress());
283
284 sendMail(mail);
285
286 releaseReturnPath(true);
287 }
288
289 /***
290 * 新しいMimeMessageオブジェクトを生成します。
291 *
292 * @return 新しいMimeMessageオブジェクト
293 */
294 public MimeMessage createMimeMessage() {
295 if (isMessageIdCustomized()) {
296 return new OMLMimeMessage(session, messageId);
297 }
298 return new MimeMessage(session);
299 }
300
301 /***
302 * Message-Idヘッダのドメイン部分を独自にセットしているかどうか判定します。
303 *
304 * @return Message-Idヘッダのドメイン部分を独自にセットしている場合 true
305 */
306 private boolean isMessageIdCustomized() {
307 return messageId != null;
308 }
309
310 /***
311 * @return Sessionインスタンス
312 */
313 protected Session getSession() {
314 return session;
315 }
316
317 /***
318 * エンコーディングに使用する文字コードを返します。
319 *
320 * @return エンコーディングに使用する文字コード
321 */
322 public String getCharset() {
323 return charset;
324 }
325
326 /***
327 * メールの件名や本文のエンコーディングに使用する文字コードを指定します。
328 * デフォルトは ISO-2022-JP です。
329 * <p>
330 * 日本語環境で利用する場合は通常変更する必要はありません。
331 *
332 * @param charset エンコーディングに使用する文字コード
333 */
334 public void setCharset(String charset) {
335 this.charset = charset;
336 }
337
338 /***
339 * @return Returns the host.
340 */
341 public String getHost() {
342 return host;
343 }
344
345 /***
346 * SMTPサーバのホスト名、またはIPアドレスをセットします。
347 * デフォルトは localhost です。
348 *
349 * @param host SMTPサーバのホスト名、またはIPアドレス
350 */
351 public void setHost(String host) {
352 this.host = host;
353 }
354
355 /***
356 * @return SMTPサーバ認証パスワード
357 */
358 public String getPassword() {
359 return password;
360 }
361
362 /***
363 * SMTPサーバの接続認証が必要な場合にパスワードをセットします。
364 *
365 * @param password SMTPサーバ認証パスワード
366 */
367 public void setPassword(String password) {
368 this.password = password;
369 }
370
371 /***
372 * @return SMTPサーバのポート番号
373 */
374 public int getPort() {
375 return port;
376 }
377
378 /***
379 * SMTPサーバのポート番号をセットします。
380 *
381 * @param port SMTPサーバのポート番号
382 */
383 public void setPort(int port) {
384 this.port = port;
385 }
386
387 /***
388 * プロトコルを返します。
389 *
390 * @return プロトコル
391 */
392 public String getProtocol() {
393 return protocol;
394 }
395
396 /***
397 * プロトコルをセットします。デフォルトは「smtp」。
398 *
399 * @param protocol プロトコル
400 */
401 public void setProtocol(String protocol) {
402 this.protocol = protocol;
403 }
404
405 /***
406 * @return Return-Pathアドレス
407 */
408 public String getReturnPath() {
409 return returnPath;
410 }
411
412 /***
413 * Return-Pathアドレスをセットします。
414 * <p>
415 * 送信するMailインスタンスに指定されたFromアドレス以外のアドレスをReturn-Pathとしたい場合に使用します。
416 * ここでセットされたReturn-Pathより、MailインスタンスにセットされたReturn-Pathが優先されます。
417 *
418 * @param returnPath Return-Pathアドレス
419 */
420 public void setReturnPath(String returnPath) {
421 this.returnPath = returnPath;
422 }
423
424 /***
425 * @return SMTPサーバ認証ユーザ名
426 */
427 public String getUsername() {
428 return username;
429 }
430
431 /***
432 * SMTPサーバの接続認証が必要な場合にユーザ名をセットします。
433 *
434 * @param username SMTPサーバ認証ユーザ名
435 */
436 public void setUsername(String username) {
437 this.username = username;
438 }
439
440 /***
441 * 生成されるMimeMessageに付けられるMessage-Idヘッダのドメイン部分を指定します。<br>
442 * 指定されない場合(nullや空文字列の場合)は、JavaMailがMessage-Idヘッダを生成します。
443 * JavaMailが生成する「JavaMail.実行ユーザ名@ホスト名」のMessage-Idを避けたい場合に、このメソッドを使用します。
444 * <p>
445 * messageIdプロパティがセットされている場合、Mailから生成されるMimeMessageのMessage-Idには
446 * <code>タイムスタンプ + ランダムに生成される16桁の数値 + ここでセットされた値</code>
447 * が使用されます。
448 * <p>
449 * 生成されるMessage-Idの例。 (実際の数値部分は送信メール毎に変わります)<ul>
450 * <li>messageIdに'example.com'を指定した場合・・・1095714924963.5619528074501343@example.com</li>
451 * <li>messageIdに'@example.com'を指定した場合・・・1095714924963.5619528074501343@example.com (上と同じ)</li>
452 * <li>messageIdに'OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com</li>
453 * <li>messageIdに'.OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com (上と同じ)</li>
454 * </ul>
455 * <p>
456 * <strong>注:</strong> このMessage-Idは<code>send(Mail)</code>か<code>send(Mail[])</code>メソッドが呼びだれた時にのみ有効です。MimeMessageを直接送信する場合には適用されません。
457 *
458 * @param messageId メールに付けられるMessage-Idヘッダのドメイン部分
459 * @throws IllegalArgumentException @を複数含んだ文字列を指定した場合
460 */
461 public void setMessageId(String messageId) {
462 if (messageId == null || messageId.length() < 1) {
463 return;
464 }
465
466 String[] parts = messageId.split("@");
467 if (parts.length > 2) {
468 throw new IllegalArgumentException("messageIdプロパティに'@'を複数含むことはできません。[" + messageId
469 + "]");
470 }
471
472 this.messageId = messageId;
473 }
474
475 /***
476 * SMTPサーバとの接続タイムアウトをセットします。
477 * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。
478 * <p>
479 * -1を指定すると無限大になりますが、お薦めしません。
480 *
481 * @since 1.1.4
482 * @param connectionTimeout SMTPサーバとの接続タイムアウト
483 */
484 public void setConnectionTimeout(int connectionTimeout) {
485 this.connectionTimeout = connectionTimeout;
486 }
487
488 /***
489 * SMTPサーバへの送受信時のタイムアウトをセットします。
490 * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。
491 * <p>
492 * -1を指定すると無限大になりますが、お薦めしません。
493 *
494 * @since 1.1.4
495 * @param readTimeout SMTPサーバへの送受信時のタイムアウト
496 */
497 public void setReadTimeout(int readTimeout) {
498 this.readTimeout = readTimeout;
499 }
500 }