JavaMail API提供了邮件处理的框架,我们可以再此基础上封装成适合自己使用的邮件收发组件。
下面提供一个最简单的使用例子,此示例介绍了支持SSL方式的应用,如果不使用SSL可以根据注释,去除相关语句:
package example.mail;
import java.io.UnsupportedEncodingException;
import java.security.Security;
import java.util.Date;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.FetchProfile;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.URLName;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeUtility;
public class Test {
private String username = "";//邮箱账户名 如: abc@qq.com
private String password = "";//邮箱密码
private String toAdd = "";//收件人电子邮箱地址 如:hello@qq.com
//发送邮件测试
public void sendSSLMail() throws AddressException, MessagingException{
//若启用SSL,需要注册安全传输的提供者
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//发送邮件必须的配置
Properties props = System.getProperties();
props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);//若启用SSL,需要设置,否则不设置此项
props.setProperty("mail.smtp.socketFactory.fallback", "false");//若启用SSL,需要设置,否则不设置此项
props.setProperty("mail.smtp.socketFactory.port", "465");//若启用SSL,需要设置,否则不设置此项
props.setProperty("mail.smtp.host", "smtp.qq.com");
props.setProperty("mail.smtp.port", "465");
props.put("mail.smtp.auth", "true");
props.put("mail.debug", "true");
final String username = this.username;//账户名称
final String password = this.password;//密码
//获取会话
Session session = Session.getDefaultInstance(props, new Authenticator(){
@Override
protected PasswordAuthentication getPasswordAuthentication() {
// TODO Auto-generated method stub
return new PasswordAuthentication(username, password);
}
});
//创建消息
Message msg = new MimeMessage(session);
//设置发件人,收件人等信息
msg.setFrom(new InternetAddress(username));
msg.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(this.toAdd, false));
msg.setSubject("Hello");
msg.setText("How are you");
msg.setSentDate(new Date());
//调用传输接口发送邮件消息
Transport.send(msg);
System.out.println("Message sent.");
}
//邮件接收测试
public void receivePOPSSLMail() throws MessagingException, UnsupportedEncodingException{
//若启用SSL,需要注册安全传输的提供者
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//接收邮件必须的配置
Properties props = System.getProperties();
props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY); //若启用SSL,需要设置,否则不设置此项
props.setProperty("mail.pop3.socketFactory.fallback", "false"); //若启用SSL,需要设置,否则不设置此项
props.setProperty("mail.pop3.socketFactory.port", "995"); //若启用SSL,需要设置,否则不设置此项
props.setProperty("mail.pop3.port", "995");
//获取会话
Session session = Session.getInstance(props);
//接收邮箱的信息
URLName urln = new URLName("pop3","pop.qq.com",995,null,
this.username, this.password);
Store store = session.getStore(urln);
Folder inbox = null;
try {
store.connect();
inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE); //以读写方式打开时才能执行写标记动作
FetchProfile profile = new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
Message[] messages = inbox.getMessages();
inbox.fetch(messages, profile);
System.out.println("邮件个数" + messages.length);
//遍历所有邮件
for (int i = 0; i < messages.length; i++) {
//解析一封邮件
String from = decodeText(messages[i].getFrom()[0].toString()); //发件人
InternetAddress ia = new InternetAddress(from); //解析发件人地址
System.out.println("FROM:" + ia.getPersonal()+'('+ia.getAddress()+')');
//其他信息
System.out.println("TITLE:" + messages[i].getSubject());
System.out.println("SIZE:" + messages[i].getSize());
System.out.println("DATE:" + messages[i].getSentDate());
messages[i].setFlag(Flags.Flag.DELETED, false);//设置删除标记
}
} finally {
try {
inbox.close(true);
store.close();
} catch (Exception e) {}
try {
store.close();
} catch (Exception e) {}
}
}
protected static 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;
}
/**
* @param args
* @throws MessagingException
* @throws AddressException
* @throws UnsupportedEncodingException
*/
public static void main(String[] args) throws AddressException, MessagingException, UnsupportedEncodingException {
Test t = new Test();
t.sendSSLMail();//发送邮件
// t.receivePOPSSLMail(); //接收邮件
}
}
总结:
1.若使用pop3协议收取邮件,网上查阅许多资料,貌似不支持对邮件进行已读和未读等标记。因此,只能全部收取然后全部删除,自己来处理对邮件标记的繁杂工作。(IMAP4协议支持)