Java使用JavaMail API发送和接收邮件的代码示例
使用Javamail发送邮件,必需的jar包(请下载javamail的源文件,官方下载页:http://www.oracle.com/technetwork/java/javamail/index-138643.html):
mailapi.jar。定义了收发邮件所使用到的接口API;
smtp.jar。包含了发送邮件使用到的类;
pop3.jar。包含了收邮件使用到的类;
我们通常发送邮件使用的协议是smtp协议,接受邮件使用的协议是pop3协议。或者,我们直接将mail.jar加入到工程,这个jar包里边包含了java收发邮件所有的接口和类。
常用的类:
- javax.mail.Session; -------->保存连接服务器所需要的信息;
- javax.mail.Message; -------->邮件体,保存邮件的内容;
- javax.mail.Transport; -------->发送邮件的载体
- javax.mail.internet.InternetAddress; -------->邮件的地址信息
发送邮件
下边,我先列出使用Java发送邮件的最简单的一个小测试示例:
importjava.util.Properties;
importjavax.mail.Address;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
/**
*
*QQ(mail.qq.com):POP3服务器(端口995)SMTP服务器(端口465或587)。
*
*/
publicclassDemo1{
/**
*@paramargs
*@throwsMessagingException
*/
publicstaticvoidmain(String[]args)throwsMessagingException{
StringsendUserName="wangxiangpan@126.com";
StringsendPassword="pwd";
Propertiesproperties=newProperties();
properties.setProperty("mail.smtp.auth","true");//服务器需要认证
properties.setProperty("mail.transport.protocol","smtp");//声明发送邮件使用的端口
Sessionsession=Session.getInstance(properties);
session.setDebug(true);//同意在当前线程的控制台打印与服务器对话信息
Messagemessage=newMimeMessage(session);//构建发送的信息
message.setText("你好,我是Champion.Wong!");//信息内容
message.setFrom(newInternetAddress("wangxiangpan@126.com"));//发件人
Transporttransport=session.getTransport();
transport.connect("smtp.126.com",25,sendUserName,sendPassword);//连接发件人使用发件的服务器
transport.sendMessage(message,newAddress[]{newInternetAddress("492134880@qq.com")});//接受邮件
transport.close();
}
}
一般的,我们使用Authenticator把用户名和密码封装起来,不透明!所以:
importjavax.mail.Authenticator;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.PasswordAuthentication;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.AddressException;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
importjunit.framework.TestCase;
/**
*javamail发送邮件
*@authorChampionWong
*Message.addRecipient(Message.Recipientrecipient,Addressaddress);发邮件的时候指定收件人和收件人的角色
*Message.RecipientType.TO收件人
*Message.RecipientType.CC抄送,即发邮件的时候顺便给另一个人抄一份,不用回复!但是,上边的收件人可以看到你都抄送给了谁
*Message.RecipientType.BCC暗送,也是发邮件的时候顺便给另一个人暗发一份,但是,不同于上边的是,收件人不能看到你都暗送给了谁
*
*/
publicclassDemo2extendsTestCase{
privatestaticfinalStringsendUserName="wangxiangpan@126.com";//发送邮件需要连接的服务器的用户名
privatestaticfinalStringsendPassword="pwd";//发送邮件需要连接的服务器的密码
privatestaticfinalStringsendProtocol="smtp";//发送邮件使用的端口
privatestaticfinalStringsendHostAddress="smtp.126.com";//发送邮件使用的服务器的地址
publicvoidtest()throwsAddressException,MessagingException{
Propertiesproperties=newProperties();
properties.setProperty("mail.smtp.auth","true");//服务器需要认证
properties.setProperty("mail.transport.protocol",sendProtocol);//声明发送邮件使用的端口
properties.setProperty("mail.host",sendHostAddress);//发送邮件的服务器地址
Sessionsession=Session.getInstance(properties,newAuthenticator(){
protectedPasswordAuthenticationgetPasswordAuthentication(){
returnnewPasswordAuthentication(sendUserName,sendPassword);
}
});
session.setDebug(true);//在后台打印发送邮件的实时信息
Messagemessage=newMimeMessage(session);
message.setFrom(newInternetAddress("wangxiangpan@126.com"));
message.setSubject("Demo2JavaCode发送邮件测试,采用Authenticator");//设置主题
message.setRecipients(Message.RecipientType.TO,InternetAddress
.parse("492134880@qq.com,wangxiangpan@126.com"));//发送
message.setRecipients(Message.RecipientType.CC,InternetAddress
.parse("msn_wangxiangpan@hotmail.com"));//抄送
message
.setContent(
"<spanstyle="font-size:20px;color:#FFCCFF"mce_style="font-size:20px;color:#FFCCFF">如果您看到,证明测试成功了!</span>",
"text/html;charset=gbk");
Transport.send(message);//发送邮件
}
}
我们发送一个比较复杂的邮件,包括附件,图文:
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.OutputStream;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.Authenticator;
importjavax.mail.MessagingException;
importjavax.mail.PasswordAuthentication;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.Message.RecipientType;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;
/**
*
*@authorAdministratorMrXP.Wang
*MimeMultipart一般电子邮件的容器是Multipart,定义了增加及删除电子邮件各部分内容的方法,
*但是其是抽象类,需要其子类MimeMultipart来时用MimeMessage对象
*MimeBodyPart是BodyPart具体用于mimeMessage的一个子类,MimeBodyPart对象代表一个
*mimeMultipart对象的每一个部分
*MimeUtility.encodeText(Stringcn)用于解决邮件中的头部信息中中文的乱码问题
*
*/
publicclassDemo3_test{
publicstaticvoidmain(String[]args)throwsException{
Propertiesproperties=newProperties();
properties.setProperty("mail.smtp.auth","true");//服务器需要认证
properties.setProperty("mail.transport.protocol","smtp");//声明发送邮件使用的端口
properties.setProperty("mail.host","smtp.126.com");//发送邮件的服务器地址
Sessionsession=Session.getInstance(properties,newAuthenticator(){
StringsendUserName="wangxiangpan@126.com";
StringsendPassword="pwd";
protectedPasswordAuthenticationgetPasswordAuthentication(){
returnnewPasswordAuthentication(sendUserName,
sendPassword);
}
});
session.setDebug(true);
MimeMessagemsg=newMimeMessage(session);//声明一个邮件体
msg.setFrom(newInternetAddress("/""+MimeUtility.encodeText("MrXP.Wang")+"/"<wangxiangpan@126.com>"));
msg.setSubject("这是我的第一份复杂邮件");//设置邮件主题
msg.setRecipients(MimeMessage.RecipientType.TO,InternetAddress.parse(MimeUtility.encodeText("王翔攀")+"<wangxiangpan@126.com>,"+MimeUtility.encodeText("三毛")+"<492134880@qq.com>"));
MimeMultipartmsgMultipart=newMimeMultipart("mixed");//标明邮件的组合关系,混合的关系
msg.setContent(msgMultipart);//设置邮件体
MimeBodyPartattch1=newMimeBodyPart();//附件1
MimeBodyPartattch2=newMimeBodyPart();//附件2
MimeBodyPartcontent=newMimeBodyPart();//邮件的正文,混合体(图片+文字)
//将附件和正文设置到这个邮件体中
msgMultipart.addBodyPart(attch1);
msgMultipart.addBodyPart(attch2);
msgMultipart.addBodyPart(content);
//设置第一个附件
DataSourceds1=newFileDataSource("F:/ACCP5.0/文件/ssh配置.txt");//指定附件的数据源
DataHandlerdh1=newDataHandler(ds1);//附件的信息
attch1.setDataHandler(dh1);//指定附件
attch1.setFileName("ssh.txt");
//设置第二个附件
DataSourceds2=newFileDataSource("resource/48.jpg");//指定附件的数据源
DataHandlerdh2=newDataHandler(ds2);//附件的信息
attch2.setDataHandler(dh2);//指定附件
attch2.setFileName("48.jpg");
//设置邮件的正文
MimeMultipartbodyMultipart=newMimeMultipart("related");//依赖关系
content.setContent(bodyMultipart);//指定正文
MimeBodyParthtmlPart=newMimeBodyPart();
MimeBodyPartgifPart=newMimeBodyPart();
bodyMultipart.addBodyPart(htmlPart);
bodyMultipart.addBodyPart(gifPart);
DataSourcegifds=newFileDataSource("resource/48.jpg");//正文的图片
DataHandlergifdh=newDataHandler(gifds);
gifPart.setHeader("Content-Location","http://mimg.126.net/logo/126logo.gif");
gifPart.setDataHandler(gifdh);//设置正文的图片
htmlPart.setContent("我只是来打酱油的,这是我的形象照!<imgsrc="/"mce_src="/""http://mimg.126.net/logo/126logo.gif/">","text/html;charset=gbk");//设置正文文字
msg.saveChanges();//保存邮件
//将邮件保存成文件
OutputStreamops=newFileOutputStream("C:/Users/Administrator/Desktop/test.eml");
msg.writeTo(ops);
ops.close();
Transport.send(msg);
}
}
收取邮件
示例:Rose收取最近一封邮件。
importjava.util.Date;
importjava.util.Properties;
importjavax.mail.Folder;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.NoSuchProviderException;
importjavax.mail.Session;
importjavax.mail.Store;
publicclassFetchMail{
publicstaticvoidmain(String[]args){
Stringprotocol="pop3";
booleanisSSL=true;
Stringhost="pop.163.com";
intport=995;
Stringusername="rose@163.com";
Stringpassword="rose";
Propertiesprops=newProperties();
props.put("mail.pop3.ssl.enable",isSSL);
props.put("mail.pop3.host",host);
props.put("mail.pop3.port",port);
Sessionsession=Session.getDefaultInstance(props);
Storestore=null;
Folderfolder=null;
try{
store=session.getStore(protocol);
store.connect(username,password);
folder=store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
intsize=folder.getMessageCount();
Messagemessage=folder.getMessage(size);
Stringfrom=message.getFrom()[0].toString();
Stringsubject=message.getSubject();
Datedate=message.getSentDate();
System.out.println("From:"+from);
System.out.println("Subject:"+subject);
System.out.println("Date:"+date);
}catch(NoSuchProviderExceptione){
e.printStackTrace();
}catch(MessagingExceptione){
e.printStackTrace();
}finally{
try{
if(folder!=null){
folder.close(false);
}
if(store!=null){
store.close();
}
}catch(MessagingExceptione){
e.printStackTrace();
}
}
System.out.println("接收完毕!");
}
}