收取邮件的代码
import java.io.*;
import java.text.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class ReciveOneMail {
private MimeMessage mimeMessage = null;
private String saveAttachPath = ""; //附件下载后的存放目录
private StringBuffer bodytext = new StringBuffer();//存放邮件内容
private String dateformat = "yy-MM-dd HH:mm"; //默认的日前显示格式
public ReciveOneMail(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}
public void setMimeMessage(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}
public String getFrom() throws Exception { //发件人
InternetAddress address[] = (InternetAddress[]) mimeMessage.getFrom();
String from = address[0].getAddress();
if (from == null)
from = "";
String personal = address[0].getPersonal();
if (personal == null)
personal = "";
String fromaddr = personal + "<" + from + ">";
return fromaddr;
}
public String getMailAddress(String type) throws Exception { //to bcc cc
String mailaddr = "";
String addtype = type.toUpperCase();
InternetAddress[] address = null;
if (addtype.equals("TO") || addtype.equals("CC")|| addtype.equals("BCC")) {
if (addtype.equals("TO")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.TO);
} else if (addtype.equals("CC")) {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.CC);
} else {
address = (InternetAddress[]) mimeMessage.getRecipients(Message.RecipientType.BCC);
}
if (address != null) {
for (int i = 0; i < address.length; i++) {
String email = address[i].getAddress();
if (email == null)
email = "";
else {
email = MimeUtility.decodeText(email);
}
String personal = address[i].getPersonal();
if (personal == null)
personal = "";
else {
personal = MimeUtility.decodeText(personal);
}
String compositeto = personal + "<" + email + ">";
mailaddr += "," + compositeto;
}
mailaddr = mailaddr.substring(1);
}
} else {
throw new Exception("Error emailaddr type!");
}
return mailaddr;
}
public String getSubject() throws MessagingException { //主题
String subject = "";
try {
subject = MimeUtility.decodeText(mimeMessage.getSubject());
if (subject == null)
subject = "";
} catch (Exception exce) {}
return subject;
}
public String getSentDate() throws Exception { //发送日期
Date sentdate = mimeMessage.getSentDate();
SimpleDateFormat format = new SimpleDateFormat(dateformat);
return format.format(sentdate);
}
public String getBodyText() { //内容
return bodytext.toString();
}
public void getMailContent(Part part) throws Exception { //解析邮件
String contenttype = part.getContentType();
int nameindex = contenttype.indexOf("name");
boolean conname = false;
if (nameindex != -1)
conname = true;
System.out.println("CONTENTTYPE: " + contenttype);
if (part.isMimeType("text/plain") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("text/html") && !conname) {
bodytext.append((String) part.getContent());
} else if (part.isMimeType("multipart/*")) {
Multipart multipart = (Multipart) part.getContent();
int counts = multipart.getCount();
for (int i = 0; i < counts; i++) {
getMailContent(multipart.getBodyPart(i));
}
} else if (part.isMimeType("message/rfc822")) {
getMailContent((Part) part.getContent());
} else {}
}
public boolean getReplySign() throws MessagingException { //判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
boolean replysign = false;
String needreply[] = mimeMessage
.getHeader("Disposition-Notification-To");
if (needreply != null) {
replysign = true;
}
return replysign;
}
/**
* 获得此邮件的Message-ID
*/
public String getMessageId() throws MessagingException { //判断此邮件是否已读,如果未读返回返回false,反之返回true
return mimeMessage.getMessageID();
}
public boolean isNew() throws MessagingException {
boolean isnew = false;
Flags flags = ((Message) mimeMessage).getFlags();
Flags.Flag[] flag = flags.getSystemFlags();
System.out.println("flags's length: " + flag.length);
for (int i = 0; i < flag.length; i++) {
if (flag[i] == Flags.Flag.SEEN) {
isnew = true;
System.out.println("seen Message.......");
break;
}
}
return isnew;
}
public boolean isContainAttach(Part part) throws Exception { //判断此邮件是否包含附件
boolean attachflag = false;
String contentType = part.getContentType();
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE))))
attachflag = true;
else if (mpart.isMimeType("multipart/*")) {
attachflag = isContainAttach((Part) mpart);
} else {
String contype = mpart.getContentType();
if (contype.toLowerCase().indexOf("application") != -1)
attachflag = true;
if (contype.toLowerCase().indexOf("name") != -1)
attachflag = true;
}
}
} else if (part.isMimeType("message/rfc822")) {
attachflag = isContainAttach((Part) part.getContent());
}
return attachflag;
}
/**
* 【保存附件】
*/
public void saveAttachMent(Part part) throws Exception {
String fileName = "";
if (part.isMimeType("multipart/*")) {
Multipart mp = (Multipart) part.getContent();
for (int i = 0; i < mp.getCount(); i++) {
BodyPart mpart = mp.getBodyPart(i);
String disposition = mpart.getDisposition();
if ((disposition != null)
&& ((disposition.equals(Part.ATTACHMENT)) || (disposition
.equals(Part.INLINE)))) {
fileName = mpart.getFileName();
if (fileName.toLowerCase().indexOf("gb2312") != -1) {
fileName = MimeUtility.decodeText(fileName);
}
saveFile(fileName, mpart.getInputStream());
} else if (mpart.isMimeType("multipart/*")) {
saveAttachMent(mpart);
} else {
fileName = mpart.getFileName();
if ((fileName != null)
&& (fileName.toLowerCase().indexOf("GB2312") != -1)) {
fileName = MimeUtility.decodeText(fileName);
saveFile(fileName, mpart.getInputStream());
}
}
}
} else if (part.isMimeType("message/rfc822")) {
saveAttachMent((Part) part.getContent());
}
}
/**
* 【设置附件存放路径】
*/
public void setAttachPath(String attachpath) {
this.saveAttachPath = attachpath;
}
/**
* 【设置日期显示格式】
*/
public void setDateFormat(String format) throws Exception {
this.dateformat = format;
}
/**
* 【获得附件存放路径】
*/
public String getAttachPath() {
return saveAttachPath;
}
/**
* 【真正的保存附件到指定目录里】
*/
private void saveFile(String fileName, InputStream in) throws Exception {
String osName = System.getProperty("os.name");
String storedir = getAttachPath();
String separator = "";
if (osName == null)
osName = "";
if (osName.toLowerCase().indexOf("win") != -1) {
separator = "//";
if (storedir == null || storedir.equals(""))
storedir = "c://tmp";
} else {
separator = "/";
storedir = "/tmp";
}
File storefile = new File(storedir + separator + fileName);
System.out.println("storefile's path: " + storefile.toString());
// for(int i=0;storefile.exists();i++){
// storefile = new File(storedir+separator+fileName+i);
// }
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(storefile));
bis = new BufferedInputStream(in);
int c;
while ((c = bis.read()) != -1) {
bos.write(c);
bos.flush();
}
} catch (Exception exception) {
exception.printStackTrace();
throw new Exception("文件保存失败!");
} finally {
bos.close();
bis.close();
}
}
/**
* PraseMimeMessage类测试
*/
public static void main(String args[]) throws Exception {
Properties props = System.getProperties();
props.put("mail.smtp.host", "smtp.163.com");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, null);
URLName urln = new URLName("pop3", "pop3.163.com", 110, null,
"xiangzhengyan", "pass");
Store store = session.getStore(urln);
store.connect();
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message[] = folder.getMessages();
System.out.println("Messages's length: " + message.length);
ReciveOneMail pmm = null;
for (int i = 0; i < message.length; i++) {
System.out.println("======================");
pmm = new ReciveOneMail((MimeMessage) message[i]);
System.out.println("Message " + i + " subject: " + pmm.getSubject());
System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());
System.out.println("Message " + i + " replysign: "+ pmm.getReplySign());
System.out.println("Message " + i + " hasRead: " + pmm.isNew());
System.out.println("Message " + i + " containAttachment: "+ pmm.isContainAttach((Part) message[i]));
System.out.println("Message " + i + " form: " + pmm.getFrom());
System.out.println("Message " + i + " to: "+ pmm.getMailAddress("to"));
System.out.println("Message " + i + " cc: "+ pmm.getMailAddress("cc"));
System.out.println("Message " + i + " bcc: "+ pmm.getMailAddress("bcc"));
pmm.setDateFormat("yy年MM月dd日 HH:mm");
System.out.println("Message " + i + " sentdate: "+ pmm.getSentDate());
System.out.println("Message " + i + " Message-ID: "+ pmm.getMessageId());
// 获得邮件内容===============
pmm.getMailContent((Part) message[i]);
System.out.println("Message " + i + " bodycontent: /r/n"
+ pmm.getBodyText());
pmm.setAttachPath("c://");
pmm.saveAttachMent((Part) message[i]);
}
}
}
发送邮件的代码
String host = "smtp.163.com"; //发件人使用发邮件的电子信箱服务器
String from = "你自己的电子信箱"; //发邮件的出发地(发件人的信箱)
String to = "收件人信箱"; //发邮件的目的地(收件人信箱)
Properties props = System.getProperties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.auth", "true"); //这样才能通过验证
MyAuthenticator myauth = new MyAuthenticator("你自己的电子信箱", "你自己的信箱密码");
Session session = Session.getDefaultInstance(props, myauth);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("11!");
message.setText("111111");
message.saveChanges();
Transport.send(message);
}
}
校验发信人权限的方法
package com.hyq.test;
import javax.mail.PasswordAuthentication;
class MyAuthenticator
extends javax.mail.Authenticator {
private String strUser;
private String strPwd;
public MyAuthenticator(String user, String password) {
this.strUser = user;
this.strPwd = password;
}
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(strUser, strPwd);
}
}
/**
* 解析邮件地址串序列为InternetAddress序列
* */
@SuppressWarnings("unchecked")
private InternetAddress[] parse(String mailSet) throws AddressException {
if (mailSet.trim() == null)
return null;
ArrayList list = new ArrayList();
StringTokenizer tokens = new StringTokenizer(mailSet, ",");
while (tokens.hasMoreTokens()) {
list.add(new InternetAddress(tokens.nextToken().trim()));
}
InternetAddress[] addressarray = new InternetAddress[list.size()];
list.toArray(addressarray);
return addressarray;
}
//发送附件的方法
if (!StringHelper.isEmpty(accessory)) {//判断附件是否为空
ArrayList attachlist=StringHelper.string2ArrayList(accessory,",");
for(int i=0;i<attachlist.size();i++) {
String id = attachlist.get(i).toString();
Attach attach = attachService.getAttach(id);
File thefile = new File(attach.getFiledir());
DataSource ds ;
if (attach.getIszip().intValue() == 1) {
ds = new ZipDataSource(thefile);
} else
ds =new FileDataSource(attach.getFiledir()) ;
DataHandler dh = new DataHandler(ds);
String fname = attach.getObjname();
String ffname = new String(fname.getBytes("gb2312"), "ISO8859-1");//处理文件名是中文的情况
MimeBodyPart part = new MimeBodyPart();// attach部分
part.setFileName(ffname);//可以和原文件名不一致,但最好一样
part.setDataHandler(dh);
multipart.addBodyPart(part);
}
发送邮件添加的SSL
if (sSSL == 1) { //需要SSL
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
}
Properties properties = System.getProperties();
if (sSSL == 1) { //需要SSL
properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
properties.setProperty("mail.smtp.socketFactory.fallback", "false");
}
收取邮件的添加的SSL
if (gssl == 1) {
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
}
if (gssl == 1) {
props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.pop3.socketFactory.fallback", "false");
props.setProperty("mail.pop3.port", port);
props.setProperty("mail.pop3.socketFactory.port", port);
}
收发邮件遇到的问题:
1.javax.mail.AuthenticationFailedException异常,
刚开始我以为是用户名和密码写错了 可是我检查了N遍没问题
我换了一个163的邮箱就可以了 那个邮箱申请的年限长些 在网上找了出现问题的可能是163不支持smtp协议 解决是把
现在申请的邮箱升级到3G好像就可以了 不过我没试 我直接就用了原先的邮箱(这问题找了N久才解决的 )
2.当你接收完了服务器上的邮件 要把服务器上的邮件删除 必须要设置的
1. folder.open(Folder.READ_WRITE);//打开一定要是READ_WRITE不能是READ_ONLY
2. mimeMessage.setFlag(Flags.Flag.DELETED, true);
3. folder.close(true);
3.//搜索大于latestSentDate的邮件
SearchTerm st = new SentDateTerm(SentDateTerm.GT, latestSentDate);
log.info("start searching mails after " + showSentDate() );
messages = folder.search(st);
4.oracle中不支持top语句
5.字符串转换成日期: SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); //字符串转换成日期
latestSentDate=df.parse(date);代码
6. 出现异常的原因是:553 authentication is required 没有设 properties.put("mail.smtp.auth", "true"); 而且 一定要为true因为里面有验证
7.java.io.IOException: Couldn't connect using "javax.net.ssl.SSLSocketFactory" socket factory to host, port: pop3.gmail.com, 995; Exception: java.lang.reflect.InvocationTargetException
解决是:服务器的协议(pop3) 是 pop.gmail.com而不是pop3.gmail.com
8.javamail 收取163 java.net.ConnectException: Connection refused: connect 出现异常的原因是 在收取的时候 Properties props = System.getProperties();
其中有SSL的验证 但收取163服务器上的邮件时 是不需要ssl验证的 所以你在使用之前 remove那些属性 props.remove("mail.pop3.socketFactory.class");
props.remove("mail.pop3.socketFactory.fallback");
props.remove("mail.pop3.port");
props.remove("mail.pop3.socketFactory.port");