JavaMail邮件接收小例子
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Store;
public class JavaMailDemo1 {
public static void main(String[] args) throws Exception {
String pop3Server = "pop3.sohu.com";
String protocol = "pop3";
String user = "z_p_u";
String pwd = "**********";
// 创建一个有具体连接信息的Properties对象
Properties props = new Properties();
props.setProperty("mail.store.protocol", protocol);
props.setProperty("mail.pop3.host", pop3Server);
// 使用Properties对象获得Session对象
Session session = Session.getInstance(props);
session.setDebug(true);
// 利用Session对象获得Store对象,并连接pop3服务器
Store store = session.getStore();
store.connect(pop3Server, user, pwd);
// 获得邮箱内的邮件夹Folder对象,以"只读"打开
Folder folder = store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
// 获得邮件夹Folder内的所有邮件Message对象
Message [] messages = folder.getMessages();
int mailCounts = messages.length;
for(int i = 0; i < mailCounts; i++) {
String subject = messages[i].getSubject();
String from = (messages[i].getFrom()[0]).toString();
System.out.println("第 " + (i+1) + "封邮件的主题:" + subject);
System.out.println("第 " + (i+1) + "封邮件的发件人地址:" + from);
System.out.println("是否打开该邮件(yes/no)?:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
if("yes".equalsIgnoreCase(input)) {
// 直接输出到控制台中
messages[i].writeTo(System.out);
}
}
folder.close(false);
store.close();
}
}
package demo2;
import java.util.Properties;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Store;
public class JavaMailDemo2 {
public static void main(String[] args) throws Exception{
Properties props=new Properties();
props.setProperty("mail.store.protocol", "pop3");
props.setProperty("mail.pop3.host", "pop3.sohu.com");
Session session=Session.getInstance(props);
session.setDebug(true);
Store store=session.getStore();
store.connect("pop3.sohu.com","z_p_u","***********");
Folder folder=store.getFolder("inbox");
folder.open(Folder.READ_ONLY);
System.out.println(folder.getMessageCount()+"-----------");
Message msg[]=folder.getMessages();
for(Message msgg:msg)
{
Multipart mp=(Multipart) msgg.getContent();
for(int i=0;i<mp.getCount();i++)
{
System.out.println(mp.getBodyPart(i).getContent());
System.out.println(mp.getBodyPart(i).getContentType());
}
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。