ITeye博客

SMTP

lujin55 · 2012-06-10 14:14 · 编程语言 · Markdown

简单的读收邮件


package smtp;

import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SmtpTest {
	private Session session;

	public void init() {
		Properties props = new Properties();
		props.put("mail.smtp.host", "smtp.163.com");
		props.put("mail.smtp.auth", "true");
		session = Session.getInstance(props, new Authenticator() {
			@Override
			public PasswordAuthentication getPasswordAuthentication() {
				return new PasswordAuthentication("lujin55", "123456");
			}
		});
	}

	public void sendMail() {
		MimeMessage mm = new MimeMessage(session);
		try {
			InternetAddress fia = new InternetAddress("lujin55@163.com");
			mm.setFrom(fia);
			InternetAddress tia = new InternetAddress("417952406@qq.com");
			mm.addRecipient(Message.RecipientType.TO, tia);
			mm.setSubject("study");
			mm.setText("dear liu");
			Transport.send(mm);
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void readMail() {
		try {
			Properties props = new Properties();
			Session s = Session.getInstance(props, null);
			//s.setDebug(true);
			Store store = s.getStore("pop3");
			store.connect("pop3.163.com","lujin55@163.com", "123456");
			Folder folder = store.getFolder("INBOX");
			folder.open(Folder.READ_ONLY);
			Message[] messages = folder.getMessages();
			for(int i=0;i<messages.length;i++){
				System.out.println(messages[i].getFrom());
				System.out.println(messages[i].getSubject());
			}
		} catch (NoSuchProviderException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void main(String args[]) {
		SmtpTest test = new SmtpTest();
		// test.init();
		// test.sendMail();
		test.readMail();
	}

}

其中遇见:553 you are not authorized to send mail authentication is required。 解决:props.put("mail.smtp.auth", "true"); true没加双引号,真的是郁闷了半天。 读取的时候遇见问题:connect refused。 解决:store.connect("pop3.163.com","lujin55@163.com", "123456");我看别人都是用smtp.163.com,可是报错了,改成pop3.163.com就对了。还不知道为什么?

下面的地址有更详细的介绍。 http://www.blogjava.net/action/archive/2006/04/24/42794.html http://blog.csdn.net/steven_05514/article/details/3478776 http://www.roseindia.net/tutorialhelp/comment/86637

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。