Java发送邮件遇到的常见需求汇总
基于SMTP发送一个简单的邮件
首先,需要一个认证器:
packageNo001_基于SMTP的文本邮件;
importjavax.mail.Authenticator;
importjavax.mail.PasswordAuthentication;
publicclassSimpleAuthenticatorextendsAuthenticator{
privateStringusername;
privateStringpassword;
publicSimpleAuthenticator(Stringusername,Stringpassword){
super();
this.username=username;
this.password=password;
}
protectedPasswordAuthenticationgetPasswordAuthentication(){
returnnewPasswordAuthentication(username,password);
}
}
然后,书写简单的发送邮件程序:
packageNo001_基于SMTP的文本邮件;
importjava.util.Properties;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.AddressException;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
publicclassSMTPSimpleMail{
publicstaticvoidmain(String[]args)throwsAddressException,MessagingException{
/*必需的信息*/
StringSMTP_MAIL_HOST="smtp.163.com";//此邮件服务器地址,自行去所属邮件查询
StringEMAIL_USERNAME="example_email@163.com";
StringEMAIL_PASSWORD="mypassword";
StringTO_EMAIL_ADDRESS="example_email_too@qq.com";
/*服务器信息*/
Propertiesprops=newProperties();
props.put("mail.smtp.host",SMTP_MAIL_HOST);
props.put("mail.smtp.auth","true");
/*创建Session*/
Sessionsession=Session.getDefaultInstance(props,newSimpleAuthenticator(EMAIL_USERNAME,EMAIL_PASSWORD));
/*邮件信息*/
MimeMessagemessage=newMimeMessage(session);
message.setFrom(newInternetAddress(EMAIL_USERNAME));
message.addRecipient(Message.RecipientType.TO,newInternetAddress(TO_EMAIL_ADDRESS));
message.setSubject("howtousejavamailtosendemail.(Title)(001)");
message.setText("howtousejavamailtosendemail.(Content)");
//发送
Transport.send(message);
System.out.println("不是特别倒霉,你可以去查收邮件了。");
}
}
各种收件人、抄送人、秘密抄送人,怎么办
认证器沿用,略。
其实就是设置、追加多个收件人、抄送人、秘密抄送人:
packageNo002_各种发件人收件人抄送人怎么办;
importjava.io.UnsupportedEncodingException;
importjava.util.Properties;
importjavax.mail.Address;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.AddressException;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeMessage;
publicclassSendMailWithMultiPeople{
publicstaticvoidmain(String[]args)throwsAddressException,MessagingException,UnsupportedEncodingException{
/*必需的信息*/
StringSMTP_MAIL_HOST="smtp.163.com";//此邮件服务器地址,自行去所属邮件查询
StringEMAIL_USERNAME="example@163.com";
StringEMAIL_PASSWORD="mypassword";
StringTO_EMAIL_ADDRESS_1="example@163.com";
StringCC_EMAIL_ADDRESS_1="example@163.com";
StringBCC_EMAIL_ADDRESS_1="example@163.com";
/*服务器信息*/
Propertiesprops=newProperties();
props.put("mail.smtp.host",SMTP_MAIL_HOST);
props.put("mail.smtp.auth","true");
/*创建Session*/
Sessionsession=Session.getDefaultInstance(props,newSimpleAuthenticator(EMAIL_USERNAME,EMAIL_PASSWORD));
/*发件人*/
Address[]senderArray=newAddress[1];
senderArray[0]=newInternetAddress("example@163.com","NickHuang");
/*邮件信息*/
MimeMessagemessage=newMimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO,newInternetAddress(TO_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.TO,newInternetAddress(CC_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.CC,newInternetAddress(CC_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.CC,newInternetAddress(TO_EMAIL_ADDRESS_1));
message.addRecipient(Message.RecipientType.BCC,newInternetAddress(BCC_EMAIL_ADDRESS_1));
message.setSubject("我是一封学习JavaMail的邮件");
message.setText("我是一封学习JavaMail的邮件的内容,请邮件过滤器高抬贵手。");
//发送
Transport.send(message);
System.out.println("不是特别倒霉,你可以去查收邮件了。");
}
}
发送附件怎么办
认证器沿用,略。
发送附件demo:
packageNo003_发送附件怎么办;
importjava.io.File;
importjava.io.UnsupportedEncodingException;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.Address;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.AddressException;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
publicclassSendMailWithAttachment{
publicstaticvoidmain(String[]args)throwsAddressException,MessagingException,UnsupportedEncodingException{
/*必需的信息*/
StringSMTP_MAIL_HOST="smtp.163.com";//此邮件服务器地址,自行去所属邮件查询
StringEMAIL_USERNAME="example@163.com";
StringEMAIL_PASSWORD="password";
StringTO_EMAIL_ADDRESS_1="example@163.com";
/*服务器信息*/
Propertiesprops=newProperties();
props.put("mail.smtp.host",SMTP_MAIL_HOST);
props.put("mail.smtp.auth","true");
/*创建Session*/
Sessionsession=Session.getDefaultInstance(props,newSimpleAuthenticator(EMAIL_USERNAME,EMAIL_PASSWORD));
/*发件人*/
Address[]senderArray=newAddress[1];
senderArray[0]=newInternetAddress(EMAIL_USERNAME);
/*邮件信息*/
MimeMessagemessage=newMimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO,newInternetAddress(TO_EMAIL_ADDRESS_1));
message.setSubject("我是一封学习JavaMail的邮件");
BodyPartbodyPart=newMimeBodyPart();
bodyPart.setText("这是一封学习JavaMail的邮件的内容,请邮件过滤器高抬贵手。");
/*附件*/
BodyPartattachmentPart1=newMimeBodyPart();
DataSourcesource=newFileDataSource(newFile("D:/文件壹.txt"));
attachmentPart1.setDataHandler(newDataHandler(source));
attachmentPart1.setFileName("=?GBK?B?"+newsun.misc.BASE64Encoder().encode("文件壹.txt".getBytes())+"?=");
BodyPartattachmentPart2=newMimeBodyPart();
source=newFileDataSource(newFile("D:/文件贰.txt"));
attachmentPart2.setDataHandler(newDataHandler(source));
attachmentPart2.setFileName("=?GBK?B?"+newsun.misc.BASE64Encoder().encode("文件贰.txt".getBytes())+"?=");
Multipartmultipart=newMimeMultipart();
multipart.addBodyPart(bodyPart);
multipart.addBodyPart(attachmentPart1);
multipart.addBodyPart(attachmentPart2);
message.setContent(multipart);
//发送
Transport.send(message);
System.out.println("不是特别倒霉,你可以去查收邮件了。");
}
}
还有,发送HTML邮件
认证器沿用,略。
其实就是告诉收件客户端用HTML解析渲染:
packageNo004_发送HTML邮件;
importjava.io.UnsupportedEncodingException;
importjava.util.Properties;
importjavax.mail.Address;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.AddressException;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
publicclassHowToSendHTMLMail{
publicstaticvoidmain(String[]args)throwsAddressException,MessagingException,UnsupportedEncodingException{
/*必需的信息*/
StringSMTP_MAIL_HOST="smtp.163.com";//此邮件服务器地址,自行去所属邮件查询
StringEMAIL_USERNAME="example@163.com";
StringEMAIL_PASSWORD="password";
StringTO_EMAIL_ADDRESS_1="example@163.com";
/*服务器信息*/
Propertiesprops=newProperties();
props.put("mail.smtp.host",SMTP_MAIL_HOST);
props.put("mail.smtp.auth","true");
/*创建Session*/
Sessionsession=Session.getDefaultInstance(props,newSimpleAuthenticator(EMAIL_USERNAME,EMAIL_PASSWORD));
/*发件人*/
Address[]senderArray=newAddress[1];
senderArray[0]=newInternetAddress(EMAIL_USERNAME);
/*邮件信息*/
MimeMessagemessage=newMimeMessage(session);
message.addFrom(senderArray);
message.addRecipient(Message.RecipientType.TO,newInternetAddress(TO_EMAIL_ADDRESS_1));
message.setSubject("如何发送HTML的邮件");
/*正文*/
MimeBodyPartbodyPart=newMimeBodyPart();
bodyPart.setContent("<h1>lovingyou...</h2>","text/html;charset=gb2312");
/*封装邮件各部分信息*/
Multipartmultipart=newMimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
//发送
Transport.send(message);
System.out.println("不是特别倒霉,你可以去查收邮件了。");
}
}
要不,来个工具类?
认证器是一定的,沿用,略。
由于需要设置的属性多且繁杂,用个自己人简单易用的属性命名,所以来一个配置类
packageNo005_来一个工具类;
importjava.io.File;
importjava.util.ArrayList;
importjava.util.List;
publicclassMailSenderConfig{
privateStringSMTPMailHost;//支持SMTP协议的邮件服务器地址
/*用于登录邮件服务器*/
privateStringusername;
privateStringpassword;
privateStringsubject;//标题
privateStringcontent;//内容
privateStringfromMail;//显示从此邮箱发出邮件
privateList<String>toMails;//收件人
privateList<String>ccMails;//抄送人
privateList<String>bccMails;//秘密抄送人
privateList<File>attachments;//附件
publicMailSenderConfig(StringsMTPMailHost,Stringsubject,
Stringcontent,StringfromMail){
super();
SMTPMailHost=sMTPMailHost;
this.subject=subject;
this.content=content;
this.fromMail=fromMail;
}
publicStringgetSMTPMailHost(){
returnSMTPMailHost;
}
publicvoidsetSMTPMailHost(StringsMTPMailHost){
SMTPMailHost=sMTPMailHost;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
publicStringgetFromMail(){
returnfromMail;
}
publicvoidsetFromMail(StringfromMail){
this.fromMail=fromMail;
}
publicList<String>getToMails(){
returntoMails;
}
publicvoidsetToMails(List<String>toMails){
this.toMails=toMails;
}
publicList<String>getCcMails(){
returnccMails;
}
publicvoidsetCcMails(List<String>ccMails){
this.ccMails=ccMails;
}
publicList<String>getBccMails(){
returnbccMails;
}
publicvoidsetBccMails(List<String>bccMails){
this.bccMails=bccMails;
}
publicList<File>getAttachments(){
returnattachments;
}
publicvoidsetAttachments(List<File>attachments){
this.attachments=attachments;
}
publicStringgetSubject(){
returnsubject;
}
publicvoidsetSubject(Stringsubject){
this.subject=subject;
}
publicStringgetContent(){
returncontent;
}
publicvoidsetContent(Stringcontent){
this.content=content;
}
publicvoidaddToMail(Stringmail){
if(this.toMails==null){
this.toMails=newArrayList<String>();
}
this.toMails.add(mail);
}
publicvoidaddCcMail(Stringmail){
if(this.ccMails==null){
this.ccMails=newArrayList<String>();
}
this.ccMails.add(mail);
}
publicvoidaddBccMail(Stringmail){
if(this.bccMails==null){
this.bccMails=newArrayList<String>();
}
this.bccMails.add(mail);
}
publicvoidaddAttachment(Filef){
if(this.attachments==null){
this.attachments=newArrayList<File>();
}
this.attachments.add(f);
}
}
最后,就是工具类的部分,主要负责几个事情:按照JavaMail规则作些初始化动作、将自定义的属性配置类翻译并以JavaMail规则设置、发送邮件。
还有,需要提下的是,因为工具类所提供的代替设置的属性有限,更多的情况可能不满足需要,所以暴露出MimeMessage,在不满足需求的情况开发者可自行加工配置,而其他部分仍可沿用工具类。
packageNo005_来一个工具类;
importjava.io.File;
importjava.util.Properties;
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.Address;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importNo002_各种发件人收件人抄送人怎么办.SimpleAuthenticator;
publicclassMailSender{
privateMailSenderConfigc;
privateMimeMessagemessage;
publicMailSender(MailSenderConfigconfig)throwsException{
super();
this.c=config;
this.setConfig();
}
/**
*初始化
*@return
*/
privateSessioninitSession(){
Propertiesprops=newProperties();
if(c.getSMTPMailHost()!=null&&c.getSMTPMailHost().length()>0){
props.put("mail.smtp.host",c.getSMTPMailHost());
}
if(c.getUsername()!=null&&c.getUsername().length()>0&&
c.getPassword()!=null&&c.getPassword().length()>0){
props.put("mail.smtp.auth","true");
returnSession.getDefaultInstance(props,newSimpleAuthenticator(c.getUsername(),c.getPassword()));
}else{
props.put("mail.smtp.auth","false");
returnSession.getDefaultInstance(props);
}
}
/**
*设置JavaMail属性
*@throwsException
*/
privatevoidsetConfig()throwsException{
this.configValid();
Sessions=this.initSession();
message=newMimeMessage(s);
/*发件人*/
Address[]fromMailArray=newAddress[1];
fromMailArray[0]=newInternetAddress(c.getFromMail());
message.addFrom(fromMailArray);
if(c.getToMails()!=null&&c.getToMails().size()>0){
for(Stringmail:c.getToMails()){
message.addRecipient(Message.RecipientType.TO,newInternetAddress(mail));
}
}
if(c.getCcMails()!=null&&c.getCcMails().size()>0){
for(Stringmail:c.getCcMails()){
message.addRecipient(Message.RecipientType.CC,newInternetAddress(mail));
}
}
if(c.getToMails()!=null&&c.getToMails().size()>0){
for(Stringmail:c.getToMails()){
message.addRecipient(Message.RecipientType.BCC,newInternetAddress(mail));
}
}
//邮件标题
message.setSubject(c.getSubject());
/*正文*/
MimeBodyPartbodyPart=newMimeBodyPart();
bodyPart.setContent(c.getContent(),"text/html;charset=gb2312");
/*封装邮件各部分信息*/
Multipartmultipart=newMimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
BodyPartattachmentPart=null;
DataSourceds=null;
if(c.getAttachments()!=null&&c.getAttachments().size()>0){
for(Filef:c.getAttachments()){
attachmentPart=newMimeBodyPart();
ds=newFileDataSource(f);
attachmentPart.setDataHandler(newDataHandler(ds));
attachmentPart.setFileName("=?GBK?B?"+newsun.misc.BASE64Encoder().encode(f.getName().getBytes())+"?=");
multipart.addBodyPart(attachmentPart);
}
}
message.setContent(multipart);
}
/**
*配置校验
*@throwsException
*/
privatevoidconfigValid()throwsException{
if(c==null){
thrownewException("配置对象为空");
}
if(c.getSMTPMailHost()==null||c.getSMTPMailHost().length()==0){
thrownewException("SMTP服务器为空");
}
if(c.getFromMail()==null&&c.getFromMail().length()==0){
thrownewException("发件人邮件为空");
}
if(c.getToMails()==null||c.getToMails().size()<1){
thrownewException("收件人邮件为空");
}
if(c.getSubject()==null||c.getSubject().length()==0){
thrownewException("邮件标题为空");
}
if(c.getContent()==null||c.getContent().length()==0){
thrownewException("邮件内容为空");
}
}
/**
*发送邮件
*@throwsMessagingException
*/
publicvoidsend()throwsMessagingException{
Transport.send(message);
}
/**
*设置MimeMessage,暴露此对象以便于开发者自行设置个性化的属性
*@return
*/
publicMimeMessagegetMessage(){
returnmessage;
}
/**
*设置MimeMessage,暴露此对象以便于开发者自行设置个性化的属性
*@return
*/
publicvoidsetMessage(MimeMessagemessage){
this.message=message;
}
}
提供一个简单的测试类
packageNo005_来一个工具类;
importjava.io.File;
importjavax.mail.internet.MimeMessage;
publicclassTestCall{
publicstaticvoidmain(String[]args)throwsException{
/*必需的信息*/
StringSMTP_MAIL_HOST="smtp.163.com";//此邮件服务器地址,自行去所属邮件查询
StringEMAIL_USERNAME="example@163.com";
StringEMAIL_PASSWORD="password";
StringTO_EMAIL_ADDRESS_1="example@163.com";
StringTO_EMAIL_ADDRESS_2="example@163.com";
/*使用情况一,正常使用*/
/*
MailSenderConfigc=newMailSenderConfig(SMTP_MAIL_HOST,
"thisistestmailfortestjavamailframework3.","thisiscontent3.",EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(newFile("d:/1.txt"));
MailSenderms=newMailSender(c);
ms.send();
System.out.println("sent...");
*/
/*使用情况二,在更多情况下,工具类所作的设置并不满足需求,故将MimeMessage暴露并*/
MailSenderConfigc=newMailSenderConfig(SMTP_MAIL_HOST,
"thisistestmailfortestjavamailframework4.","thisiscontent4.",EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(newFile("d:/1.txt"));
MailSenderms=newMailSender(c);
MimeMessagemessage=ms.getMessage();
message.setContent("thisisthereplacedcontentbyMimeMessage4.","text/html;charset=utf-8");
ms.setMessage(message);
ms.send();
System.out.println("sent...");
}
}
升级下工具类
在实际使用中,发现在批量发送邮件情况下,工具类的支持不好,比如发送100封邮件,按照上述工具类的逻辑,每发送一封邮件就建立一个连接,那么,100封不就100次了吗?这样严重浪费啊。
于是,针对此点作些升级:
认证器是一定的,沿用,略。
配置类
importjava.util.ArrayList;
importjava.util.List;
publicclassMailSenderConfig{
privateStringSMTPMailHost;//支持SMTP协议的邮件服务器地址
/*用于登录邮件服务器*/
privateStringusername;
privateStringpassword;
privateStringsubject;//标题
privateStringcontent;//内容
privateStringfromMail;//显示从此邮箱发出邮件
privateList<String>toMails;//收件人
privateList<String>ccMails;//抄送人
privateList<String>bccMails;//秘密抄送人
privateList<Attachment>attachments;//附件
privateStringcontentType="text/html;charset=utf-8";
/**
*构造器
*@paramsMTPMailHostSMTP服务器
*@paramsubject标题
*@paramcontent内容(默认以“text/html;charset=utf-8”形式发送)
*@paramfromMail发送人地址
*/
publicMailSenderConfig(StringsMTPMailHost,Stringsubject,
Stringcontent,StringfromMail){
super();
SMTPMailHost=sMTPMailHost;
this.subject=subject;
this.content=content;
this.fromMail=fromMail;
}
/**
*构造器
*@paramsMTPMailHostSMTP服务器
*@paramusername邮件服务器用户名
*@parampassword邮件服务器密码
*@paramsubject标题
*@paramcontent内容(默认以“text/html;charset=utf-8”形式发送)
*@paramfromMail发送人地址
*/
publicMailSenderConfig(StringsMTPMailHost,Stringusername,
Stringpassword,Stringsubject,Stringcontent,StringfromMail){
super();
SMTPMailHost=sMTPMailHost;
this.username=username;
this.password=password;
this.subject=subject;
this.content=content;
this.fromMail=fromMail;
}
publicvoidaddToMail(Stringmail){
if(this.toMails==null){
this.toMails=newArrayList<String>();
}
this.toMails.add(mail);
}
publicvoidaddCcMail(Stringmail){
if(this.ccMails==null){
this.ccMails=newArrayList<String>();
}
this.ccMails.add(mail);
}
publicvoidaddBccMail(Stringmail){
if(this.bccMails==null){
this.bccMails=newArrayList<String>();
}
this.bccMails.add(mail);
}
publicvoidaddAttachment(Attachmenta){
if(this.attachments==null){
this.attachments=newArrayList<Attachment>();
}
this.attachments.add(a);
}
/*
*GetterandSetter
*/
publicStringgetSMTPMailHost(){
returnSMTPMailHost;
}
publicvoidsetSMTPMailHost(StringsMTPMailHost){
SMTPMailHost=sMTPMailHost;
}
publicStringgetUsername(){
returnusername;
}
publicvoidsetUsername(Stringusername){
this.username=username;
}
publicStringgetPassword(){
returnpassword;
}
publicvoidsetPassword(Stringpassword){
this.password=password;
}
publicStringgetFromMail(){
returnfromMail;
}
publicvoidsetFromMail(StringfromMail){
this.fromMail=fromMail;
}
publicList<String>getToMails(){
returntoMails;
}
publicvoidsetToMails(List<String>toMails){
this.toMails=toMails;
}
publicList<String>getCcMails(){
returnccMails;
}
publicvoidsetCcMails(List<String>ccMails){
this.ccMails=ccMails;
}
publicList<String>getBccMails(){
returnbccMails;
}
publicvoidsetBccMails(List<String>bccMails){
this.bccMails=bccMails;
}
publicList<Attachment>getAttachments(){
returnattachments;
}
publicvoidsetAttachments(List<Attachment>attachments){
this.attachments=attachments;
}
publicStringgetSubject(){
returnsubject;
}
publicvoidsetSubject(Stringsubject){
this.subject=subject;
}
publicStringgetContent(){
returncontent;
}
publicvoidsetContent(Stringcontent){
this.content=content;
}
publicStringgetContentType(){
returncontentType;
}
publicvoidsetContentType(StringcontentType){
this.contentType=contentType;
}
}
附件实体类
importjava.io.File;
/**
*邮件附件实体类
*/
publicclassAttachment{
privateFilefile;
privateStringfilename;
publicFilegetFile(){
returnfile;
}
publicvoidsetFile(Filefile){
this.file=file;
}
publicStringgetFilename(){
if(filename==null||filename.trim().length()==0){
returnfile.getName();
}
returnfilename;
}
publicvoidsetFilename(Stringfilename){
this.filename=filename;
}
publicAttachment(Filefile,Stringfilename){
super();
this.file=file;
this.filename=filename;
}
publicAttachment(Filefile){
super();
this.file=file;
}
}
抽象发送类
importjava.util.Properties;
importjavax.mail.Session;
publicabstractclassAbstractSessionMailSender{
protectedSessionsession;
/**
*初始化Session
*@return
*/
publicstaticSessioninitSession(MailSenderConfigc){
Propertiesprops=newProperties();
if(c.getSMTPMailHost()!=null&&c.getSMTPMailHost().length()>0){
props.put("mail.smtp.host",c.getSMTPMailHost());
}
if(c.getUsername()!=null&&c.getUsername().length()>0&&
c.getPassword()!=null&&c.getPassword().length()>0){
props.put("mail.smtp.auth","true");
returnSession.getDefaultInstance(props,newSimpleAuthenticator(c.getUsername(),c.getPassword()));
}else{
props.put("mail.smtp.auth","false");
returnSession.getDefaultInstance(props);
}
}
/**
*暴露Getter、Setter提供Session的可设置性,以支持批量发送邮件/发送多次邮件时,可缓存Session
*@return
*/
publicSessiongetSession(){
returnsession;
}
publicvoidsetSession(Sessionsession){
this.session=session;
}
}
发送类
importjavax.activation.DataHandler;
importjavax.activation.DataSource;
importjavax.activation.FileDataSource;
importjavax.mail.Address;
importjavax.mail.BodyPart;
importjavax.mail.Message;
importjavax.mail.MessagingException;
importjavax.mail.Multipart;
importjavax.mail.Session;
importjavax.mail.Transport;
importjavax.mail.internet.InternetAddress;
importjavax.mail.internet.MimeBodyPart;
importjavax.mail.internet.MimeMessage;
importjavax.mail.internet.MimeMultipart;
importjavax.mail.internet.MimeUtility;
publicclassMailSenderextendsAbstractSessionMailSender{
privateMailSenderConfigc;
privateMimeMessagemessage;
publicMailSender(MailSenderConfigconfig)throwsException{
super();
this.c=config;
this.setConfig();
}
publicMailSender(MailSenderConfigconfig,Sessionsession)throwsException{
super();
this.c=config;
this.setConfig();
super.setSession(session);
}
/**
*发送邮件
*@throwsMessagingException
*/
publicvoidsend()throwsMessagingException{
Transport.send(message);
}
/**
*获取MimeMessage,暴露此对象以便于开发者自行设置个性化的属性(此工具类不支持的方法可由开发人员自行设置,设置完毕设置回来)
*@return
*/
publicMimeMessagegetMessage(){
returnmessage;
}
/**
*设置MimeMessage,暴露此对象以便于开发者自行设置个性化的属性(此工具类不支持的方法可由开发人员自行设置,设置完毕设置回来)
*@return
*/
publicvoidsetMessage(MimeMessagemessage){
this.message=message;
}
/**
*设置JavaMail属性
*@throwsException
*/
privatevoidsetConfig()throwsException{
this.configValid();
if(session==null){
session=initSession(c);
}
message=newMimeMessage(session);
/*发件人*/
Address[]fromMailArray=newAddress[1];
fromMailArray[0]=newInternetAddress(c.getFromMail());
message.addFrom(fromMailArray);
if(c.getToMails()!=null&&c.getToMails().size()>0){
for(Stringmail:c.getToMails()){
message.addRecipient(Message.RecipientType.TO,newInternetAddress(mail));
}
}
if(c.getCcMails()!=null&&c.getCcMails().size()>0){
for(Stringmail:c.getCcMails()){
message.addRecipient(Message.RecipientType.CC,newInternetAddress(mail));
}
}
if(c.getToMails()!=null&&c.getToMails().size()>0){
for(Stringmail:c.getToMails()){
message.addRecipient(Message.RecipientType.BCC,newInternetAddress(mail));
}
}
//邮件标题
message.setSubject(c.getSubject());
/*正文*/
MimeBodyPartbodyPart=newMimeBodyPart();
bodyPart.setContent(c.getContent(),c.getContentType());
/*封装邮件各部分信息*/
Multipartmultipart=newMimeMultipart();
multipart.addBodyPart(bodyPart);
message.setContent(multipart);
/*附件*/
BodyPartattachmentPart=null;
DataSourceds=null;
if(c.getAttachments()!=null&&c.getAttachments().size()>0){
for(Attachmenta:c.getAttachments()){
attachmentPart=newMimeBodyPart();
ds=newFileDataSource(a.getFile());
attachmentPart.setDataHandler(newDataHandler(ds));
attachmentPart.setFileName(MimeUtility.encodeText(a.getFilename()));
multipart.addBodyPart(attachmentPart);
}
}
message.setContent(multipart);
}
/**
*配置校验
*@throwsException
*/
privatevoidconfigValid()throwsException{
if(c==null){
thrownewException("配置对象为空");
}
if(c.getSMTPMailHost()==null||c.getSMTPMailHost().length()==0){
thrownewException("SMTP服务器为空");
}
if(c.getFromMail()==null&&c.getFromMail().length()==0){
thrownewException("发件人邮件为空");
}
if(c.getToMails()==null||c.getToMails().size()<1){
thrownewException("收件人邮件为空");
}
if(c.getSubject()==null||c.getSubject().length()==0){
thrownewException("邮件标题为空");
}
if(c.getContent()==null||c.getContent().length()==0){
thrownewException("邮件内容为空");
}
}
}
一个Junit的测试类
importjava.io.File;
importjavax.mail.Session;
importjavax.mail.internet.MimeMessage;
importorg.junit.Test;
publicclassReadMe{
/*必需的信息*/
StringSMTP_MAIL_HOST="smtp.163.com";//此邮件服务器地址,自行去所属邮件服务器描述页查询
StringEMAIL_USERNAME="example@163.com";
StringEMAIL_PASSWORD="password";
StringTO_EMAIL_ADDRESS_1="example@163.com";
/*选填的信息*/
StringTO_EMAIL_ADDRESS_2="example@163.com";
@Test
publicvoidcase1()throwsException{
/*使用情况一,正常使用*/
MailSenderConfigc=newMailSenderConfig(SMTP_MAIL_HOST,
"thisisamailfortestjavamailframeworkincase1.","thisiscontent.",EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(newAttachment(newFile("d:/1.txt")));
MailSenderms=newMailSender(c);
ms.send();
System.out.println("sent...");
}
@Test
publicvoidcase2()throwsException{
/*使用情况二,在更多情况下,工具类所作的设置并不满足需求,故将MimeMessage暴露以便于开发者自行设置个性化的属性*/
MailSenderConfigc=newMailSenderConfig(SMTP_MAIL_HOST,
"thisisamailfortestjavamailframeworkincase2.","thisiscontent.",EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(newAttachment(newFile("d:/1.txt")));
MailSenderms=newMailSender(c);
MimeMessagemessage=ms.getMessage();
message.setContent("thisisthereplacedcontentbyMimeMessageincase2.","text/html;charset=utf-8");
ms.setMessage(message);
ms.send();
System.out.println("sent...");
}
@Test
publicvoidcase3()throwsException{
/*使用情况三,多次发送邮件,可缓存Session,使多次发送邮件均共享此Session,以减少重复创建Session
*同时需注意缓存的Session的时效性
*/
MailSenderConfigc=newMailSenderConfig(SMTP_MAIL_HOST,
"thisisthefirstmailfortestjavamailframeworktosharesessionincase3.","thisiscontent.",EMAIL_USERNAME);
c.setUsername(EMAIL_USERNAME);
c.setPassword(EMAIL_PASSWORD);
c.addToMail(TO_EMAIL_ADDRESS_1);
c.addToMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_2);
c.addCcMail(TO_EMAIL_ADDRESS_1);
c.addAttachment(newAttachment(newFile("d:/1.txt")));
Sessionsession=MailSender.initSession(c);
MailSenderms=newMailSender(c,session);
ms.send();
c.setSubject("thisisthesecondmailfortestjavamailframeworktosharesessionincase3.");
c.setContent("thisiscontent2.");
ms=newMailSender(c,session);
ms.send();
System.out.println("sent...");
}
}
总结
目前,我遇到的需求就是这么多,如日后遇见其他常见的需求并有时间,会进一步添加。
以上所述是小编给大家介绍的Java发送邮件遇到的常见需求汇总的全部叙述,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!