package com.gatgets.mail;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.FetchProfile;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Message.RecipientType;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
/**
* 邮件工具类
* 需要导入mail.jar包(j2ee自带)
* @author 王正镇
* @date 2011-8-14
*/
public class EmailUtil {
private String username = null; // 邮箱用户名
private String password = null; // 邮箱密码
/**
* 传入自己的邮箱用户名和密码
* @param username
* @param password
*/
public EmailUtil(String username, String password) {
this.username = username;
this.password = password;
}
/**
* 创建连接会话
* @param props
* @return
*/
public Session createSession(Properties props) {
Session session = Session.getInstance(props, new Authenticator() {
// 返回用户名密码认证
@Override
public PasswordAuthentication getPasswordAuthentication() {
PasswordAuthentication pa = new PasswordAuthentication(username, password);
return pa;
}
});
return session;
}
/**
* 发送邮件(需设置SMTP)
* @throws Exception
*/
public void sendMail(Properties props, SendEmailMessage sem) throws Exception {
Session session = createSession(props);
// 消息
Message msg = new MimeMessage(session);
msg.setFrom(InternetAddress.parse(MimeUtility.decodeText(sem.getFrom()))[0]);
// TO为初级收件人,CC为邮件副本抄送,BCC应该是密秘抄送吧
msg.setRecipients(RecipientType.TO, InternetAddress.parse(sem.getRecipient()));
msg.setSubject(sem.getSubject());
msg.setText(sem.getText());
msg.setSentDate(new Date());
// 发送消息
Transport.send(msg);
}
/**
* 接收邮件(需设置POP3或SAMP)
* @throws Exception
*/
public void receiveMail(Properties props, String protocol) throws Exception {
Session session = createSession(props);
Store store = session.getStore(protocol);
store.connect(); // 连接
Folder inbox = store.getFolder("INBOX"); // 进入根目录
inbox.open(Folder.READ_WRITE); // 只读方式
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE); // 获取信封
Message[] msgs = inbox.getMessages(); // 得到所有邮件
inbox.fetch(msgs, profile); // 预获取信息
// 打印
for (int i = 0; i < msgs.length; i++) {
System.out.println("发送时间:" + msgs[i].getSentDate());
System.out.println("发送人:" + decodeText(msgs[i].getFrom()[0].toString()));
System.out.println("大小:" + msgs[i].getSize());
System.out.println("标题:" + msgs[i].getSubject());
System.out.println("内容" + msgs[i].getContent());
System.out.println("-------------------");
}
store.close();
}
/**
* 处理中文编码问题
* @param text
* @return
* @throws UnsupportedEncodingException
*/
private String decodeText(String text) throws UnsupportedEncodingException {
if (text == null) {
return null;
}
if (text.startsWith("=?GB") || text.startsWith("=?gb"))
text = MimeUtility.decodeText(text);
else
text = new String(text.getBytes("ISO8859_1"));
return text;
}
}
package com.gatgets.mail;
import java.util.Properties;
/**
* 邮件默认配置类
* 方法中的必要参好,可根据实际情况修改
* @author 王正镇
* @date 2011-8-14
*/
public class DefaultConfigurer {
/**
* 获取SMTP默认配置
* @return
*/
public static Properties getSMTP() {
Properties p = new Properties();
p.setProperty("mail.smtp.host", "smtp.qq.com"); // 按需要更改
p.setProperty("mail.smtp.protocol", "smtp");
p.setProperty("mail.smtp.port", "465");
p.setProperty("mail.smtp.auth", "true");
// SSL安全连接参数
p.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.setProperty("mail.smtp.socketFactory.fallback", "false");
p.setProperty("mail.smtp.socketFactory.port", "465");
return p;
}
/**
* 获取POP3收信配置
* @return
*/
public static Properties getPOP3() {
Properties p = new Properties();
p.setProperty("mail.pop3.host", "pop.qq.com"); // 按需要更改
p.setProperty("mail.pop3.port", "995");
// SSL安全连接参数
p.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.setProperty("mail.pop3.socketFactory.fallback", "false");
p.setProperty("mail.pop3.socketFactory.port", "995");
return p;}
/**
* 获取IMAP收信配置
* @return
*/
public static Properties getIMAP() {
Properties p = new Properties();
p.setProperty("mail.imap.host", "imap.qq.com"); // 按需要更改
p.setProperty("mail.imap.port", "993");
// SSL安全连接参数
p.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
p.setProperty("mail.imap.socketFactory.fallback", "false");
p.setProperty("mail.imap.socketFactory.port", "993");
return p;}
}
package com.gatgets.mail;
/**
* 发送邮件消息包装属性类
*
* @author 王正镇
* @date 2011-8-14
*/
public class SendEmailMessage {
private String type; // 格式类型,如 text/html;charset=gbk
private String from; // 发送人
private String subject; // 标题
private String text; // 内容
private String recipient; // 接收人,多个接收人用逗号分隔
private String datetime; // 发送时间
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getRecipient() {
return recipient;
}
public void setRecipient(String recipient) {
this.recipient = recipient;
}
public String getDatetime() {
return datetime;
}
public void setDatetime(String datetime) {
this.datetime = datetime;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
package com.gatgets.mail;
/**
* 测试类
* @author 王正镇
* @date 2011-8-14
*/
public class TestEmail {
/**
* 程序入口点
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// 默认情况下,在这里输入QQ号和密码,便可收信与发信
EmailUtil eu = new EmailUtil("xxx", "xxx");
SendEmailMessage sem = new SendEmailMessage();
sem.setFrom("wzz<
[email protected]>");
sem.setRecipient("
[email protected],
[email protected]");
sem.setSubject("镇长");
sem.setText("hello world");
eu.sendMail(DefaultConfigurer.getSMTP(), sem);
System.out.println("发送成功");
// 收邮件
eu.receiveMail(DefaultConfigurer.getPOP3(), "pop3"); // pop3收信
System.out.println("收取完毕");
// 使用IMAP收信会抛出 Failed to load IMAP envelope 异常
//eu.receiveMail(DefaultConfigurer.getIMAP(), "imap"); // imap收信
}
}