View Javadoc

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 		// グローバルReturn-Pathの設定
106 		putOnReturnPath(this.returnPath);
107 
108 		try {
109 			// SMTPサーバに接続
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 		session = Session.getInstance(prop);
137 	}
138 
139 	/***
140 	 * @see com.ozacc.mail.SendMailPro#disconnect()
141 	 */
142 	public synchronized void disconnect() throws MailException {
143 		if (connected) {
144 			try {
145 				log.debug("SMTPサーバ[" + host + "]との接続を切断します。");
146 
147 				// SMTPサーバとの接続を切断
148 				transport.close();
149 				connected = false;
150 
151 				log.debug("SMTPサーバ[" + host + "]との接続を切断しました。");
152 			} catch (MessagingException ex) {
153 				log.error("SMTPサーバ[" + host + "]との接続切断に失敗しました。", ex);
154 				throw new MailException("SMTPサーバ[" + host + "]との接続切断に失敗しました。");
155 			} finally {
156 				// グローバルReturn-Pathの解除
157 				releaseReturnPath(false);
158 			}
159 		} else {
160 			log.warn("SMTPサーバ[" + host + "]との接続が確立されていない状態で、接続の切断がリクエストされました。");
161 		}
162 	}
163 
164 	/***
165 	 * ReturnPathをセットします。
166 	 * 
167 	 * @param returnPath
168 	 */
169 	private void putOnReturnPath(String returnPath) {
170 		if (returnPath != null) {
171 			session.getProperties().put(RETURN_PATH_KEY, returnPath);
172 			log.debug("Return-Path[" + returnPath + "]を設定しました。");
173 		}
174 	}
175 
176 	/***
177 	 * ReturnPathの設定をクリアします。
178 	 * <p>
179 	 * setGlobalReturnPathAgainがtrueに指定されている場合、一旦Return-Path設定をクリアした後に、
180 	 * グローバルなReturn-Path(setReturnPath()メソッドで、このインスタンスにセットされたReturn-Pathアドレス)を設定します。
181 	 * グローバルなReturn-PathがセットされていなければReturn-Pathはクリアされたままになります。
182 	 * <p>
183 	 * クリアされた状態でsend()メソッドが実行されると、Fromの値がReturn-Pathに使用されます。
184 	 * 
185 	 * @param setGlobalReturnPathAgain Return-Path設定をクリアした後、再度グローバルなReturn-Pathをセットする場合 true
186 	 */
187 	private void releaseReturnPath(boolean setGlobalReturnPathAgain) {
188 		session.getProperties().remove(RETURN_PATH_KEY);
189 		log.debug("Return-Path設定をクリアしました。");
190 
191 		if (setGlobalReturnPathAgain && this.returnPath != null) {
192 			putOnReturnPath(this.returnPath);
193 		}
194 	}
195 
196 	/***
197 	 * @see com.ozacc.mail.SendMailPro#send(javax.mail.internet.MimeMessage)
198 	 */
199 	public void send(MimeMessage mimeMessage) throws MailException {
200 		Address[] addresses;
201 		try {
202 			addresses = mimeMessage.getAllRecipients();
203 		} catch (MessagingException ex) {
204 			log.error("メールの送信に失敗しました。", ex);
205 			throw new MailSendException("メールの送信に失敗しました。", ex);
206 		}
207 		processSend(mimeMessage, addresses);
208 	}
209 
210 	/***
211 	 * @param mimeMessage 
212 	 */
213 	private void processSend(MimeMessage mimeMessage, Address[] addresses) {
214 		if (!connected) {
215 			log.error("SMTPサーバへの接続が確立されていません。");
216 			throw new NotConnectedException("SMTPサーバへの接続が確立されていません。");
217 		}
218 
219 		try {
220 			// 送信日時をセット
221 			mimeMessage.setSentDate(new Date());
222 			mimeMessage.saveChanges();
223 			// 送信
224 			log.debug("メールを送信します。");
225 			transport.sendMessage(mimeMessage, addresses);
226 			log.debug("メールを送信しました。");
227 		} catch (MessagingException ex) {
228 			log.error("メールの送信に失敗しました。", ex);
229 			throw new MailSendException("メールの送信に失敗しました。", ex);
230 		}
231 	}
232 
233 	/***
234 	 * @see com.ozacc.mail.SendMailPro#send(com.ozacc.mail.Mail)
235 	 */
236 	public void send(Mail mail) throws MailException {
237 		if (mail.getReturnPath() != null) {
238 			sendMailWithReturnPath(mail);
239 		} else {
240 			sendMail(mail);
241 		}
242 	}
243 
244 	/***
245 	 * 指定されたMailからMimeMessageを生成し、send(MimeMessage)メソッドに渡します。
246 	 * 
247 	 * @param mail
248 	 * @throws MailException
249 	 */
250 	private void sendMail(Mail mail) throws MailException {
251 		// MimeMessageの生成
252 		MimeMessage message = createMimeMessage();
253 		MimeMessageBuilder builder = new MimeMessageBuilder(message, charset);
254 		try {
255 			builder.buildMimeMessage(mail);
256 		} catch (UnsupportedEncodingException e) {
257 			throw new MailBuildException("サポートされていない文字コードが指定されました。", e);
258 		} catch (MessagingException e) {
259 			throw new MailBuildException("MimeMessageの生成に失敗しました。", e);
260 		}
261 		// 送信
262 		if (mail.getEnvelopeTo().length > 0) {
263 			log.debug("メールはenvelope-toアドレスに送信されます。");
264 			processSend(message, mail.getEnvelopeTo());
265 		} else {
266 			send(message);
267 		}
268 	}
269 
270 	/***
271 	 * 指定されたMailにセットされたReturn-Pathを設定して、メールを送信します。
272 	 * 同期メソッドです。
273 	 * 
274 	 * @param mail
275 	 * @throws MailException
276 	 */
277 	private synchronized void sendMailWithReturnPath(Mail mail) throws MailException {
278 		putOnReturnPath(mail.getReturnPath().getAddress());
279 
280 		sendMail(mail);
281 
282 		releaseReturnPath(true);
283 	}
284 
285 	/***
286 	 * 新しいMimeMessageオブジェクトを生成します。
287 	 * 
288 	 * @return 新しいMimeMessageオブジェクト
289 	 */
290 	public MimeMessage createMimeMessage() {
291 		if (isMessageIdCustomized()) {
292 			return new OMLMimeMessage(session, messageId);
293 		}
294 		return new MimeMessage(session);
295 	}
296 
297 	/***
298 	 * Message-Idヘッダのドメイン部分を独自にセットしているかどうか判定します。
299 	 * 
300 	 * @return Message-Idヘッダのドメイン部分を独自にセットしている場合 true
301 	 */
302 	private boolean isMessageIdCustomized() {
303 		return messageId != null;
304 	}
305 
306 	/***
307 	 * @return Sessionインスタンス
308 	 */
309 	protected Session getSession() {
310 		return session;
311 	}
312 
313 	/***
314 	 * エンコーディングに使用する文字コードを返します。
315 	 * 
316 	 * @return エンコーディングに使用する文字コード
317 	 */
318 	public String getCharset() {
319 		return charset;
320 	}
321 
322 	/***
323 	 * メールの件名や本文のエンコーディングに使用する文字コードを指定します。
324 	 * デフォルトは ISO-2022-JP です。
325 	 * <p>
326 	 * 日本語環境で利用する場合は通常変更する必要はありません。
327 	 * 
328 	 * @param charset エンコーディングに使用する文字コード
329 	 */
330 	public void setCharset(String charset) {
331 		this.charset = charset;
332 	}
333 
334 	/***
335 	 * @return Returns the host.
336 	 */
337 	public String getHost() {
338 		return host;
339 	}
340 
341 	/***
342 	 * SMTPサーバのホスト名、またはIPアドレスをセットします。
343 	 * デフォルトは localhost です。
344 	 * 
345 	 * @param host SMTPサーバのホスト名、またはIPアドレス
346 	 */
347 	public void setHost(String host) {
348 		this.host = host;
349 	}
350 
351 	/***
352 	 * @return SMTPサーバ認証パスワード
353 	 */
354 	public String getPassword() {
355 		return password;
356 	}
357 
358 	/***
359 	 * SMTPサーバの接続認証が必要な場合にパスワードをセットします。
360 	 * 
361 	 * @param password SMTPサーバ認証パスワード
362 	 */
363 	public void setPassword(String password) {
364 		this.password = password;
365 	}
366 
367 	/***
368 	 * @return SMTPサーバのポート番号
369 	 */
370 	public int getPort() {
371 		return port;
372 	}
373 
374 	/***
375 	 * SMTPサーバのポート番号をセットします。
376 	 * 
377 	 * @param port SMTPサーバのポート番号
378 	 */
379 	public void setPort(int port) {
380 		this.port = port;
381 	}
382 
383 	/***
384 	 * プロトコルを返します。
385 	 * 
386 	 * @return プロトコル
387 	 */
388 	public String getProtocol() {
389 		return protocol;
390 	}
391 
392 	/***
393 	 * プロトコルをセットします。デフォルトは「smtp」。
394 	 * 
395 	 * @param protocol プロトコル
396 	 */
397 	public void setProtocol(String protocol) {
398 		this.protocol = protocol;
399 	}
400 
401 	/***
402 	 * @return Return-Pathアドレス
403 	 */
404 	public String getReturnPath() {
405 		return returnPath;
406 	}
407 
408 	/***
409 	 * Return-Pathアドレスをセットします。
410 	 * <p>
411 	 * 送信するMailインスタンスに指定されたFromアドレス以外のアドレスをReturn-Pathとしたい場合に使用します。
412 	 * ここでセットされたReturn-Pathより、MailインスタンスにセットされたReturn-Pathが優先されます。
413 	 * 
414 	 * @param returnPath Return-Pathアドレス
415 	 */
416 	public void setReturnPath(String returnPath) {
417 		this.returnPath = returnPath;
418 	}
419 
420 	/***
421 	 * @return SMTPサーバ認証ユーザ名
422 	 */
423 	public String getUsername() {
424 		return username;
425 	}
426 
427 	/***
428 	 * SMTPサーバの接続認証が必要な場合にユーザ名をセットします。
429 	 * 
430 	 * @param username SMTPサーバ認証ユーザ名
431 	 */
432 	public void setUsername(String username) {
433 		this.username = username;
434 	}
435 
436 	/***
437 	 * 生成されるMimeMessageに付けられるMessage-Idヘッダのドメイン部分を指定します。<br>
438 	 * 指定されない場合(nullや空文字列の場合)は、JavaMailがMessage-Idヘッダを生成します。
439 	 * JavaMailが生成する「JavaMail.実行ユーザ名@ホスト名」のMessage-Idを避けたい場合に、このメソッドを使用します。
440 	 * <p>
441 	 * messageIdプロパティがセットされている場合、Mailから生成されるMimeMessageのMessage-Idには
442 	 * <code>タイムスタンプ + ランダムに生成される16桁の数値 + ここでセットされた値</code>
443 	 * が使用されます。
444 	 * <p>
445 	 * 生成されるMessage-Idの例。 (実際の数値部分は送信メール毎に変わります)<ul>
446 	 * <li>messageIdに'example.com'を指定した場合・・・1095714924963.5619528074501343@example.com</li>
447 	 * <li>messageIdに'@example.com'を指定した場合・・・1095714924963.5619528074501343@example.com (上と同じ)</li>
448 	 * <li>messageIdに'OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com</li>
449 	 * <li>messageIdに'.OML@example.com'を指定した場合・・・1095714924963.5619528074501343.OML@example.com (上と同じ)</li>
450 	 * </ul>
451 	 * <p>
452 	 * <strong>注:</strong> このMessage-Idは<code>send(Mail)</code>か<code>send(Mail[])</code>メソッドが呼びだれた時にのみ有効です。MimeMessageを直接送信する場合には適用されません。
453 	 * 
454 	 * @param messageId メールに付けられるMessage-Idヘッダのドメイン部分
455 	 * @throws IllegalArgumentException @を複数含んだ文字列を指定した場合
456 	 */
457 	public void setMessageId(String messageId) {
458 		if (messageId == null || messageId.length() < 1) {
459 			return;
460 		}
461 
462 		String[] parts = messageId.split("@");
463 		if (parts.length > 2) {
464 			throw new IllegalArgumentException("messageIdプロパティに'@'を複数含むことはできません。[" + messageId
465 					+ "]");
466 		}
467 
468 		this.messageId = messageId;
469 	}
470 
471 	/***
472 	 * SMTPサーバとの接続タイムアウトをセットします。
473 	 * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。
474 	 * <p>
475 	 * -1を指定すると無限大になりますが、お薦めしません。
476 	 * 
477 	 * @since 1.1.4
478 	 * @param connectionTimeout SMTPサーバとの接続タイムアウト
479 	 */
480 	public void setConnectionTimeout(int connectionTimeout) {
481 		this.connectionTimeout = connectionTimeout;
482 	}
483 
484 	/***
485 	 * SMTPサーバへの送受信時のタイムアウトをセットします。
486 	 * 単位はミリ秒。デフォルトは5,000ミリ秒(5秒)です。
487 	 * <p>
488 	 * -1を指定すると無限大になりますが、お薦めしません。
489 	 * 
490 	 * @since 1.1.4
491 	 * @param readTimeout SMTPサーバへの送受信時のタイムアウト
492 	 */
493 	public void setReadTimeout(int readTimeout) {
494 		this.readTimeout = readTimeout;
495 	}
496 }