详细的JavaMail技术介绍参考http://book.csdn.net/bookfiles/371/10037114086.shtml
一、使用JavaMail 发送邮件
package com.bb.basic.javamail;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;
/**
* 使用JavaMail API发送邮件
* @author Administrator
*
*/
public class JavaMailSender {
public static void main(String[] args) {
// TODO Auto-generated method stub
Transport transport=null; //Transport对象负责发送邮件
try{//设置邮件发送环境
Properties props=new Properties();
props.put("mail.transport.protocol","smtp");//邮件发送协议
//smtp服务器的地址 如:smtp.sina.com.cn
props.put("mail.smtp.host","smtp.sina.com.cn");
//smtp服务器是否需要用户认证,默认为false
props.put("mail.smtp.auth","true"); //注意是"true",并非true
//设置认证信息:用户名和密码
Authenticator auth=new Authenticator(){
protected PasswordAuthentication getPasswordAuthentication(){
return new PasswordAuthentication("dongkk","password");
}
};
Session session=Session.getInstance(props,auth);
Message msg=new MimeMessage(session);
msg.setFrom(new InternetAddress("dongkk@sina.com"));
msg.setRecipient(Message.RecipientType.TO,
new InternetAddress("dongkk@sina.com"));
msg.setSubject("Test Mail");
msg.setSentDate(new Date());
msg.setText("Java Mail API");
transport=session.getTransport();
transport.send(msg);
System.out.println("邮件发送成功!");
}catch(MessagingException e){ e.printStackTrace();
}finally{
try{
transport.close();
}catch(Exception e){}
}
}
}
二、使用JavaMail 接收邮件
package com.bb.basic.javamail;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.*;
public class JavaMailSSLReceiver {
public static void main(String[] args) {
// TODO Auto-generated method stub
Properties props=new Properties();
Session session=Session.getDefaultInstance(props);
//第1个参数为接受协议,第2个参数为邮件接收服务器的地址,第三个参数为pop3协议的端口,最后两个为用户名和密码
URLName url=new URLName("pop3","pop.sina.com.cn",110,null,"dongkk","password");
//使用SSL加密传输协议,gmail可以使用ssl协议来保证邮件传输的安全,使用SSL的POP3S的默认端口为995。
//URLName url=new URLName("pop3s","pop.gmail.com",995,null,"masterspring","spring");
Store store=null;
Folder inbox=null;
try{
store=session.getStore(url);
//使用URLName指定Session邮件环境,包括认证信息
store.connect(); //连接邮件服务器
//从邮件服务器中返回邮箱内的信息
inbox=store.getFolder("INBOX");
inbox.open(Folder.READ_ONLY); //打开Folder
FetchProfile fp=new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
Message[] msgs=inbox.getMessages();
inbox.fetch(msgs, fp);
//显示邮件信息
for(int i=0;i<msgs.length;i++){
String from=msgs[i].getFrom()[0].toString();
InternetAddress id=new InternetAddress(from);
System.out.println();
System.out.println("发送者:"+id.getPersonal()+"/"+id.getAddress());
System.out.println("标题:"+msgs[i].getSubject());
System.out.println("大小:"+msgs[i].getSize());
System.out.println("时间:"+msgs[i].getSentDate());
}
}catch(Exception er){
System.out.println("发生异常:"+er.toString());
}finally{
try{
inbox.close(false);
store.close();
}catch(Exception e){}
}
} }