package javamailtest;
import java.util.Date;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
* 邮件的收发器
* @author liudong
*/
public class MailDemo {
public static void main(String[] args) {
// receive();
send();
}
/**
* 邮件接收
*/
protected static void receive() {
try {
Properties prop = new Properties();
Session ses = Session.getInstance(prop);
// 使用 pop3 Provider ,Store用于接收邮件
Store store = ses.getStore("pop3");
// store.connect("hostName",userName,password); //hostName为邮件服务器的地址
store.connect("pop3.sina.com", "[email protected]","xxx");
if (store.isConnected()) {
Folder inbox = store.getFolder("INBOX"); //收件箱
if (inbox.exists()) {
inbox.open(Folder.READ_ONLY); //打开收件箱
int nCount = inbox.getMessageCount(); //获取邮件数量
System.out.println("Inbox contains " + nCount + " messages");
// 依次显示收件箱中的每封邮件
for(int i=1;i<=nCount;i++){
MimeMessage msg = (MimeMessage) inbox.getMessage(i);
System.out.println("Subject : " + msg.getSubject());
System.out.println("From : " + msg.getFrom()[0].toString());
System.out.println("Content type : " + msg.getContentType());
System.out.println(msg.getContent());
}
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 邮件发送
*/
protected static void send() {
try {
Properties prop = new Properties();
// 邮件发送者地址
prop.setProperty("mail.sohu.from","[email protected]");
Session ses = Session.getInstance(prop);
// Transport用于邮件发送的,使用smtp 协议
Transport transport = ses.getTransport("smtp");
// 连接到 Hotmail 服务器,请替换为自己的用户名和口令
transport.connect("smtp.sohu.com", "[email protected]","xxx");
// 准备要发送的邮件
MimeMessage txMsg = new MimeMessage(ses);
txMsg.setSubject("This is the subject");
// 邮件发送者地址
InternetAddress addrFrom = new InternetAddress("[email protected]");
txMsg.setFrom(addrFrom);
// 邮件接收者地址
InternetAddress addrTo = new InternetAddress("[email protected]", "ziji");
txMsg.addRecipient(Message.RecipientType.TO, addrTo);
// 邮件内容
txMsg.setText("Hello world !testtest");
txMsg.setSentDate(new Date());
// 发送邮件
transport.sendMessage(txMsg, txMsg.getAllRecipients()); //发送邮件
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Transport用于发送邮件,Store用于接收邮件,这两个对象都是通过session来获取的,根据协议的名称来获取不同的provider