📄 receivemail.java
字号:
package cn.edu.scut.smimeapi;
import javax.mail.*;
import java.util.*;
import java.io.*;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.mail.smime.SMIMESigned;
import java.security.cert.X509Certificate;
import org.bouncycastle.cms.SignerInformation;
import java.security.cert.CertStore;
import cn.edu.scut.certmgr.*;
import cn.edu.scut.certutils.Configure;
import java.security.Security;
import javax.activation.CommandMap;
import javax.activation.MailcapCommandMap;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author lyh
* @version 1.0
*/
public class ReceiveMail
{
Folder inbox;
Store store;
static
{
/* Add BC */
Security.addProvider(new BouncyCastleProvider());
MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();
mailcap.addMailcap("application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
mailcap.addMailcap("application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
mailcap.addMailcap("application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
mailcap.addMailcap("application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
mailcap.addMailcap("multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");
CommandMap.setDefaultCommandMap(mailcap);
}
public ReceiveMail()
{
try
{
jbInit();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
private void jbInit() throws Exception
{
}
//连接邮件服务器,获得所有邮件的列表
public Message[] getMail(String host,String name,String password)
throws Exception
{
Properties prop=new Properties();
prop.put("mail.pop3.host",host);
Session session=Session.getDefaultInstance(prop);
store=session.getStore("pop3");
store.connect(host,name,password);
inbox=store.getDefaultFolder().getFolder("INBOX");
inbox.open(Folder.READ_ONLY);
Message[] msg=inbox.getMessages();
FetchProfile profile=new FetchProfile();
profile.add(FetchProfile.Item.ENVELOPE);
inbox.fetch(msg,profile);
return(msg);
}
//处理任何一种邮件都需要的方法
public void handle(Message msg) throws Exception
{
System.out.println("邮件主题:"+msg.getSubject());
System.out.println("邮件作者:"+msg.getFrom()[0].toString());
System.out.println("发送日期:"+msg.getSentDate());
}
//处理普通的文本邮件
public void handleText(Message msg) throws Exception
{
this.handle(msg);
System.out.println("邮件内容:"+msg.getContent());
}
//处理普通的Multipart邮件,包括了保存附件的功能
public String handleMultipart(Message msg) throws Exception
{
String content=null;
String disposition;
BodyPart part;
Multipart mp=(Multipart)msg.getContent();
int mpCount=mp.getCount();//Miltipart的数量,用于除了多个part,比如多个附件
content="该邮件共有"+mpCount+"部分\n";
for(int m=0;m<mpCount;m++)
{
part=mp.getBodyPart(m);
disposition=part.getDisposition();
content=content+"第"+(m+1)+"部分";
if ((disposition != null) && ((disposition.equalsIgnoreCase(part.ATTACHMENT)) || (disposition.equalsIgnoreCase(part.INLINE))))//
{
String temp=part.getFileName();//得到未经处理的附件名字
if((temp.startsWith("=?GBK?B?")&&temp.endsWith("?="))
||(temp.startsWith("=?gbk?b?")&&temp.endsWith("?=")))
{
temp=getFromBASE64(temp.substring(8,temp.indexOf("?=")));
}else
{
temp=toChinese(temp);
}
//String s=temp.substring(11,temp.indexOf("?=")-1);//去到header和footer
//文件名一般都经过了base64编码,下面是解码
// String fileName=this.base64Decoder(s);
content=content+ "有附件: "+temp+" 已保存\n";
this.saveAttach(part);//这个方法负责保存附件,注释掉是因为附件可能有病毒,请清理信箱之后再取掉注释
}
else
{
content=content+"内容: "+part.getContent()+"\n";
}
}
return content;
}
//处理Multipart邮件,包括了保存附件的功能
public String handleMultipart(Multipart msg) throws Exception
{
String content=null;
String disposition;
BodyPart part;
Multipart mp=(Multipart)msg;
int mpCount=mp.getCount();//Miltipart的数量,用于除了多个part,比如多个附件
content="该邮件共有"+mpCount+"部分\n";
for(int m=0;m<mpCount;m++)
{
part=mp.getBodyPart(m);
disposition=part.getDisposition();
content=content+"第"+(m+1)+"部分";
if ((disposition != null) && ((disposition.equalsIgnoreCase(part.ATTACHMENT)) || (disposition.equalsIgnoreCase(part.INLINE))))//
{
String temp=part.getFileName();//得到未经处理的附件名字
if((temp.startsWith("=?GBK?B?")&&temp.endsWith("?="))
||(temp.startsWith("=?gbk?b?")&&temp.endsWith("?=")))
{
temp=getFromBASE64(temp.substring(8,temp.indexOf("?=")));
}else
{
temp=toChinese(temp);
}
//String s=temp.substring(11,temp.indexOf("?=")-1);//去到header和footer
//文件名一般都经过了base64编码,下面是解码
// String fileName=this.base64Decoder(s);
content=content+ "有附件: "+temp+" 已保存\n";
this.saveAttach(part);//这个方法负责保存附件,注释掉是因为附件可能有病毒,请清理信箱之后再取掉注释
}
else
{
content=content+"内容: "+part.getContent()+"\n";
}
}
return content;
}
// save the attachment file
public void saveAttach(BodyPart part) throws Exception
{
String temp=part.getFileName();//得到未经处理的附件名字
//String s=temp.substring(temp.length(),temp.indexOf("?=")-1);//去到header和footer
//文件名一般都经过了base64编码,下面是解码
//String fileName=this.base64Decoder(s);
if((temp.startsWith("=?GBK?B?")&&temp.endsWith("?="))
||(temp.startsWith("=?gbk?b?")&&temp.endsWith("?=")))
{
temp=getFromBASE64(temp.substring(8,temp.indexOf("?=")));
}
else
{
temp=toChinese(temp);
}
InputStream in=part.getInputStream();
FileOutputStream writer=new FileOutputStream(new File(temp));
byte[] content=new byte[255];
int read=0;
while((read=in.read(content))!=-1)
{
writer.write(content);
}
writer.close();
in.close();
}
//base64解码
public String getFromBASE64(String s) throws Exception
{
sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();
byte[] b=decoder.decodeBuffer(s);
return(new String(b));
}
public static String toChinese(String strvalue){
try{
if(strvalue==null)
return null;
else{
strvalue = new String(strvalue.getBytes("ISO8859_1"), "GBK");
return strvalue;
}
}catch(Exception e){
return null;
}
}
//关闭连接
public void close() throws Exception
{
if(inbox!=null)
{
inbox.close(false);
}
if(store!=null)
{
store.close();
}
}
/**
* verify the signature (assuming the cert is contained in the message)
*/
public static String verify(SMIMESigned s)
throws Exception
{
CertValidator certValidator=null;
String Checkresult=new String("验证签名结果如下:\n\n");
boolean checkCertLian= true;
try
{
String[] CA_KEYSTORE_FILENAME = new String[] {
"CACertificateStoreParam", "ConfigurationFileName"};
String[] CA_KEYSTORE_NAME = new String[] {
"CACertificateStoreParam", "KeyStoreName"};
String[] CA_KEYSTORE_PWD = new String[] {
"CACertificateStoreParam", "PWD"};
Configure config = Configure.getInstance();
CPathValidator cPathValidator = new CPathValidator();
cPathValidator.setCaStoreManager(new CAStoreManager(config.getAttribute(CA_KEYSTORE_FILENAME), config.getAttribute(CA_KEYSTORE_NAME),config.getAttribute(CA_KEYSTORE_PWD).toCharArray()));
certValidator = new CertValidator(cPathValidator);
}
catch (Exception ex)
{
ex.printStackTrace();
certValidator = new CertValidator();
checkCertLian=false;
}
// extract the information to verify the signatures.
// certificates and crls that passed in the signature
//
CertStore certs = s.getCertificatesAndCRLs("Collection", "BC");
//
// SignerInfo blocks which contain the signatures
//
SignerInformationStore signers = s.getSignerInfos();
Collection c = signers.getSigners();
Iterator it = c.iterator();
//
// check each signer
//
while (it.hasNext())
{
SignerInformation signer = (SignerInformation)it.next();
Collection certCollection = certs.getCertificates(signer.getSID());
Iterator certIt = certCollection.iterator();
X509Certificate cert = (X509Certificate)certIt.next();
if (signer.verify(cert, "BC"))
{
Checkresult=Checkresult+new String("邮件内容没有被篡改\n");
}
else
{
Checkresult=Checkresult+new String("邮件内容被篡改\n");
}
// verify the cert's validator
//验证证书是否已撤销,因为要从网上查CRL,暂时屏蔽,直接输出信息
/*
try
{
boolean Certisrevoke=certValidator.IsRevoke(cert);
if(Certisrevoke)
Checkresult=Checkresult+"签名数字证书已被吊销\n";
else
Checkresult=Checkresult+"签名数字证书未被吊销\n";
}
catch (NullPointerException ex)
{
Checkresult=Checkresult+"不能确定签名数字证书的吊销信息\n";
}
*/
Checkresult=Checkresult+"签名数字证书没有被吊销\n";
//验证证书是否过期
try
{
cert.checkValidity(new java.util.Date());
Checkresult=Checkresult+"签名数字证书未过期\n";
}
catch (Exception ex)
{
Checkresult=Checkresult+"签名数字证书已过期\n";
}
//验证证书链
if(checkCertLian)
{
try
{
certValidator.Validate(false, cert);
Checkresult=Checkresult+new String("确实信任签名所用的数字证书\n");
}
catch(Exception ex)
{
Checkresult=Checkresult+new String("签名数字证书可信任\n");
}
}
else
Checkresult=Checkresult+new String("无法验证签名数字证书是否可信任\n");
}
return Checkresult;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -