java中javamail发送带附件的邮件实现方法
本文实例讲述了java中javamail发送带附件的邮件实现方法。分享给大家供大家参考。具体分析如下:
JavaMail,顾名思义,提供给开发者处理电子邮件相关的编程接口。它是Sun发布的用来处理email的API。它可以方便地执行一些常用的邮件传输,JavaMail是可选包,因此如果需要使用的话你需要首先从java官网上下载。目前最新版本是JavaMail1.5.0,下面我们来看看javamail发送带附件的邮件实例
mail.java代码:
packagemail;
importjava.util.*;
importjava.io.*;
importjavax.mail.*;
importjavax.mail.internet.*;
importjavax.activation.*;
publicclassMail{
//定义发件人、收件人、SMTP服务器、用户名、密码、主题、内容等
privateStringdisplayName;
privateStringto;
privateStringfrom;
privateStringsmtpServer;
privateStringusername;
privateStringpassword;
privateStringsubject;
privateStringcontent;
privatebooleanifAuth;//服务器是否要身份认证
privateStringfilename="";
privateVectorfile=newVector();//用于保存发送附件的文件名的集合
/**
*设置SMTP服务器地址
*/
publicvoidsetSmtpServer(StringsmtpServer){
this.smtpServer=smtpServer;
}
/**
*设置发件人的地址
*/
publicvoidsetFrom(Stringfrom){
this.from=from;
}
/**
*设置显示的名称
*/
publicvoidsetDisplayName(StringdisplayName){
this.displayName=displayName;
}
/**
*设置服务器是否需要身份认证
*/
publicvoidsetIfAuth(booleanifAuth){
this.ifAuth=ifAuth;
}
/**
*设置E-mail用户名
*/
publicvoidsetUserName(Stringusername){
this.username=username;
}
/**
*设置E-mail密码
*/
publicvoidsetPassword(Stringpassword){
this.password=password;
}
/**
*设置接收者
*/
publicvoidsetTo(Stringto){
this.to=to;
}
/**
*设置主题
*/
publicvoidsetSubject(Stringsubject){
this.subject=subject;
}
/**
*设置主体内容
*/
publicvoidsetContent(Stringcontent){
this.content=content;
}
/**
*该方法用于收集附件名
*/
publicvoidaddAttachfile(Stringfname){
file.addElement(fname);
}
publicMail(){
}
/**
*初始化SMTP服务器地址、发送者E-mail地址、用户名、密码、接收者、主题、内容
*/
publicMail(StringsmtpServer,Stringfrom,StringdisplayName,Stringusername,Stringpassword,Stringto,Stringsubject,Stringcontent){
this.smtpServer=smtpServer;
this.from=from;
this.displayName=displayName;
this.ifAuth=true;
this.username=username;
this.password=password;
this.to=to;
this.subject=subject;
this.content=content;
}
/**
*初始化SMTP服务器地址、发送者E-mail地址、接收者、主题、内容
*/
publicMail(StringsmtpServer,Stringfrom,StringdisplayName,Stringto,Stringsubject,Stringcontent){
this.smtpServer=smtpServer;
this.from=from;
this.displayName=displayName;
this.ifAuth=false;
this.to=to;
this.subject=subject;
this.content=content;
}
/**
*发送邮件
*/
publicHashMapsend(){
HashMapmap=newHashMap();
map.put("state","success");
Stringmessage="邮件发送成功!";
Sessionsession=null;
Propertiesprops=System.getProperties();
props.put("mail.smtp.host",smtpServer);
if(ifAuth){//服务器需要身份认证
props.put("mail.smtp.auth","true");
SmtpAuthsmtpAuth=newSmtpAuth(username,password);
session=Session.getDefaultInstance(props,smtpAuth);
}else{
props.put("mail.smtp.auth","false");
session=Session.getDefaultInstance(props,null);
}
session.setDebug(true);
Transporttrans=null;
try{
Messagemsg=newMimeMessage(session);
try{
Addressfrom_address=newInternetAddress(from,displayName);
msg.setFrom(from_address);
}catch(java.io.UnsupportedEncodingExceptione){
e.printStackTrace();
}
InternetAddress[]address={newInternetAddress(to)};
msg.setRecipients(Message.RecipientType.TO,address);
msg.setSubject(subject);
Multipartmp=newMimeMultipart();
MimeBodyPartmbp=newMimeBodyPart();
mbp.setContent(content.toString(),"text/html;charset=gb2312");
mp.addBodyPart(mbp);
if(!file.isEmpty()){//有附件
Enumerationefile=file.elements();
while(efile.hasMoreElements()){
mbp=newMimeBodyPart();
filename=efile.nextElement().toString();//选择出每一个附件名
FileDataSourcefds=newFileDataSource(filename);//得到数据源
mbp.setDataHandler(newDataHandler(fds));//得到附件本身并至入BodyPart
mbp.setFileName(fds.getName()); //得到文件名同样至入BodyPart
mp.addBodyPart(mbp);
}
file.removeAllElements();
}
msg.setContent(mp);//Multipart加入到信件
msg.setSentDate(newDate()); //设置信件头的发送日期
//发送信件
msg.saveChanges();
trans=session.getTransport("smtp");
trans.connect(smtpServer,username,password);
trans.sendMessage(msg,msg.getAllRecipients());
trans.close();
}catch(AuthenticationFailedExceptione){
map.put("state","failed");
message="邮件发送失败!错误原因:\n"+"身份验证错误!";
e.printStackTrace();
}catch(MessagingExceptione){
message="邮件发送失败!错误原因:\n"+e.getMessage();
map.put("state","failed");
e.printStackTrace();
Exceptionex=null;
if((ex=e.getNextException())!=null){
System.out.println(ex.toString());
ex.printStackTrace();
}
}
//System.out.println("\n提示信息:"+message);
map.put("message",message);
returnmap;
}
}SmtpAuth.java代码:
packagemail;
publicclassSmtpAuthextendsjavax.mail.Authenticator{
privateStringusername,password;
publicSmtpAuth(Stringusername,Stringpassword){
this.username=username;
this.password=password;
}
protectedjavax.mail.PasswordAuthenticationgetPasswordAuthentication(){
returnnewjavax.mail.PasswordAuthentication(username,password);
}
}
存在的问题就是发送到163的邮件全部都带有一个附件的符号,不管有没有发送附件,感兴趣的朋友可以对此加以改进和完善。
希望本文所述对大家的Java程序设计有所帮助。