一、将mail服务器的一些基本配置信息提取到一个属性文件当中去,如需进行ssl加密也可在这里配置,如下
#发送邮件配置
mail.transport.protocol=smtp
mail.smtp.class=com.sun.mail.smtp.SMTPTransport
mail.smtp.auth=true
mail.smtp.host=smtp.qq.com
mail.smtp.port=25
#接受邮件配置
mail.store.protocol=imap
mail.imap.class=com.sun.mail.imap.IMAPStore
mail.imap.host=imap.qq.com
mail.imap.port=143
mail.imap.partialfetch=false
mail.imap.fetchsize=16k
这里只针对QQ的IMAP协议。
二、写一个邮件工具类(MailUtil),用来处理一些公用的常见的邮件问题,写一个读取配置属性的方法,如下
/**
* 得到属性文件信息
*
* @return 属性信息
*/
public static Properties getProperties(String bundleName) {
try {
Properties pro = new Properties();
PropertyResourceBundle bundle = (PropertyResourceBundle) PropertyResourceBundle
.getBundle(bundleName);
Enumeration<String> enm = bundle.getKeys();
while (enm.hasMoreElements()) {
String key = (String) enm.nextElement();
String value = bundle.getString(key);
pro.setProperty(key, value);
}
return pro;
} catch (Exception e) {
MailLog.saveMailLog(MailUtil.class, "other", bundleName
+ "属性文件读取错误", e, 1);
return null;
}
三、邮件关闭方法
public static void close(Folder folder, Store store) {
try {
if (folder != null) {
if (folder.isOpen()) {
folder.close(true);
}
}
if (store != null) {
if (store.isConnected()) {
store.close();
}
}
} catch (Exception e) {
MailLog.saveMailLog(MailUtil.class, "", "邮箱关闭失败", e, 1);
} finally {
folder = null;
store = null;
}
}
四、处理错误日志方法(MailLog.saveMailLog),我是将错误信息保存到log4j或者数据库中,这是在配置文件中配置的,你们可以根据你们的需求来自定义日志存储。
本片文章就是为了引导大家如何着手去做一个邮件客户端,a重在编程思想,不要拘泥于代码。
由于时间关系,本文就写到这里,从下一篇开始将具体的介绍javamail的应用