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