下面代码是利用Java邮件包封装了一个发送邮件的类
import java.io.File;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Properties;import javax.activation.DataHandler;import javax.activation.FileDataSource;import javax.mail.Message;import javax.mail.MessagingException;import javax.mail.Multipart;import javax.mail.Session;import javax.mail.Transport;import javax.mail.internet.AddressException;import javax.mail.internet.InternetAddress;import javax.mail.internet.MimeBodyPart;import javax.mail.internet.MimeMessage;import javax.mail.internet.mimemultipart; public类sendmail {私人静态最终字符串mail_address_regex =“^[// w // w // w //.=-=-=-=-=-=-+expry@///////w ///w //.-------------/-/--/-/ W/wr]私人字符串邮件服务器;私人字符串发件人;私有字符串[]接收器; public sendmail(){} public void setMailBasicInfo(字符串Mailserver,字符串发送器,字符串接收器){this.mailServer = mailServer; this.sender = sender; this.receiver = receiver.split(“,”); } public void setMailBasicInfo(字符串Mailserver,String Sender,String []用户){this.mailServer = mailServer; this.sender = sender; this.receiver =用户; } public void setMailBasicInfo(字符串MailServer,字符串发送者,List <String>用户){this.mailServer = mailServer; this.sender = sender; this.receiver = new String [users.size()]; users.toarray(this.receiver); } public boolean send(字符串主题,字符串内容,列表<string>文件名){object = object == null? content = content == null?”:“:content;属性props = new Properties(); props.put(“ mail.smtp.host”,mailserver); session session = session.getInstance(props,null);尝试{InternetAddress [] reveriver = getReceiverList(); if(reveriver.length == 0){system.out.println(“接收者为null”);返回false; } mimemessage msg = new Mimemessage(session); msg.setfrom(新InternetAddress(Sender)); msg.setRecipient(Message.RecipientType.to,接收器); msg.setsubject(主题); msg.setsentdate(new Date()); Multipart Container = new Mimemultipart(); MimeBodyPart TextBodyPart = new MimeBodyPart(); textbodypart.setContent(content.tostring(),“ text/html; charset = gbk”); container.addbodypart(textbodypart); doattachfile(容器,文件名); msg.setContent(容器); system.out.println(“开始发送邮件”); transport.send(msg); system.out.println(“发送邮件成功”); } catch(MessagingException E){System.out.println(“发送邮件失败”); system.out.println(e);返回false; } catch(异常e){返回false; }返回true; } public boolean send(字符串主题,字符串内容){返回发送(主题,内容,null); } public boolean send(字符串主题){返回send(主题,null); } private void doattachfile(多部分容器,列表<string>文件名)抛出MessagingException {if(filenames == null || || fileNames.size()== 0)return; for(字符串文件名:文件名){文件f = new File(fileName);如果(!f.file())继续; system.out.println(“附加文件为:”+filename); MimeBodyPart FileBodyPart = new MimeBodyPart(); filedatasource fds = new filedatasource(f); // filebodypart.setdatahandler(new datahandler(fds)); filebodypart.setFilename(fds.getName()); // container.addbodypart(filebodypart); }} private InternetAddress [] getReceiverList()抛出addressException {arrayList <InternetAddress> tolist = new ArrayList <InternetAddress>(); for(int i = 0; i <receiver.length; ++ i){if(reover [i] .matches(mail_address_regex)){tolist.add(new InternetAdadDress(regeiver [i])); }} return(InternetAddress [])tolist.toArray(new InternetAddress [tolist.size()]); }}}使用举例
字符串主机=“ 168.xx.xx.xx”; //邮件服务器的地址字符串主题=“发送邮件的主题”; string sender =“ [email protected]”; list <String>接收= new ArrayList <string>(); receivers.Add(“ [email protected]”); reveivers.Add(“ [email protected]”)接收器); sendmail.send(主题,内容,null); //没有附件
正文也可以是html内容,如
字符串content =“ <html>详细信息:<a href ='xxxx'> </a> </html>”;
我们再来看一个封装好的类
包com.message.base.email;导入com.message.base.spring.applicationhelper; import com.message.base.utils.tringutils; import com.message.base.base.utils.validateutils; import org.slf4j.logger; import; import; import org.slf4j.loggergerfactory;导入javax.mail。 /***发送邮件服务器。 * * @author sunhao([email protected]) * @version v1.0,13-3-25,6:19 */public class emailserver {私人静态最终logger logger = loggerfactory.getlogger(emailserver.class.class); // Spring中配置/**邮箱服务器配置**/私人列表<EmailConfig> config; / **是否开启debug调试模式**/私人布尔iSdebug = false; / **是否启用身份验证**/私人布尔isauth = true; / **验证类型**/私有字符串authtype =“ auth”; / ** *私有化默认构造器,使外部不可实例化 */ private emailserver(){}/ ** *单例,保证上下文中只有一个EmailServer * * @return emailserver */ public static emailserver getInstance() } / ** *发送普通邮件(单个接收人) * * @param用户名 * @param密码发件人密码collections.singletonList(接收器)); } / ** *发送普通邮件(多个接收人) * * @param用户名 * @param password发件人密码 * @param title邮件标题 * @param content邮件正文 * @param content邮件正文 * @param接收器多个接收人 * @return * / public boolean boolean sendtextmail(字符串用户名,username username,username,username,string,字符串,字符串,字符串密码,字符串<string> receivers <string> receivers) if(this.isauth()){//如果需要身份认证,则创建一个密码验证器} properties props = new Properties(); props.setProperty(“邮件.smtp.auth”,this.isauth()?“ true”:“ false”); props.setProperty(“邮件” transport.protocol”,“ auth”); emailconfig config = this.getEmailConfig(用户名); props.setProperty(“邮件” props.setProperty(“ mail.smtp.port”,config.getPort() +“”); //根据邮件会话属性和密码验证器构造一个发送邮件的会话会话= session.getDefaultInstance(props,auth); session.setdebug(this.isdebug);消息消息= this.maketextmail(会话,标题,内容,用户名,接收器,false);尝试{transport.send(message);返回true; } catch(MessagingException E){Logger.error(e.getMessage(),e);返回false; }}} / ** *发送html邮件(单个接收人) * * @param用户名 * @param密码发件人密码内容,collections.singletonList(接收器)); } / ** *发送html邮件(多个接收人) * * @param用户名 * @param密码发件人密码 * @param title @param title邮件标题 * @param content邮件正文 * @param接收机多个接收人if(this.isauth()){//如果需要身份认证,则创建一个密码验证器} properties props = new Properties(); props.setProperty(“邮件.smtp.auth”,this.isauth()?“ true”:“ false”); props.setProperty(“邮件” transport.protocol”,“ auth”); emailconfig config = this.getEmailConfig(用户名); props.setProperty(“邮件” props.setProperty(“ mail.smtp.port”,config.getPort() +“”); //根据邮件会话属性和密码验证器构造一个发送邮件的会话会话= session.getDefaultInstance(props,auth); session.setdebug(this.isdebug);消息消息= this.maketextmail(会话,标题,内容,用户名,接收器,true);尝试{transport.send(message);返回true; } catch(MessagingException E){Logger.error(e.getMessage(),e);返回false; }} / ** * * * * * @param电子邮件邮箱地址 * @return * / private emailconfig getemailConfig(字符串电子邮件){字符串mailservicedomainname = this.getMailServIceDomainName(email); for(emailconfig config:this.config){if(config.getName()。equals(mailServiceOmainName)){return config; }}返回null; } / ** *创建邮件消息 * * @param session根据配置获得的会话 * @param title邮件主题 * @param content邮件的内容 * @param from发件者 * @param接收器 @param ishtmlmlmail是否是Mimemessage(会话);尝试{ / **标题** / logger.info(“此邮件的标题为{}”,title); message.SetsUbject(title); / **内容**/ logger.info(“此邮件的内容为{}”,content); if(ishtmlmail){//是html邮件message.setContent(content,“ text/html; charset; charset = utf-8”); } else {//普通邮件message.setText(content); } / **发件者地址** / logger.info(“此邮件的发件人为{}”,来自); address = new InternetAddress(来自)的地址; message.setfrom(摘要); / **接收者地址**/地址[] for(int i = 0; i <recevivers.size(); i ++){字符串receiver = recevers.get(i); if(validateUtils.isemail(接收器)){tos [i] = new InternetAddress(regeiver); }} / **发件时间** / message.setsentdate(new Date()); message.setRecipient(message.RecipientType.to,tos); } catch(MessagingException E){Logger.error(e.getMessage(),e); e.printstacktrace(); }返回消息; } / ** * * * * * @param电子邮件邮箱 * @return * / private String getMailServIceDomainName(字符串电子邮件){if(strignutils.isempty(email)){返回“返回”; } else {int firstIndex = stringutils.indexof(email,“@”); int secondIndex = strignutils.lastIndexof(email,“。”);返回Stringutils.substring(电子邮件,firstIndex + 1,secondIndex); }} public List <EmailConfig> getConfig(){return config; } public void setConfig(list <EmailConfig> config){this.config = config; } public boolean isdebug(){返回isdebug; } public void setDebug(boolean debug){isdebug = debug; } public boolean isauth(){返回isauth; } public void setauth(boolean auth){isauth = auth; } public String getAuthType(){return authtype; } public void setauthtype(string authtype){this.authtype = authtype; }}}
调用方式如下
public boolean sendmail()抛出异常{list <string>接收= new ArrayList <string>();接收者.add(“ [email protected]”);接收者.add(“ [email protected]”); emailserver.getInstance()。sendhtmlmail(“ [email protected]”,“”,“”,“测试发送html邮件”,“ <span style ='color:red; font; font; font; font'> 20pt'> font'>测试发送html html </span> href </span> target ='_ blank'>链接到百度</a>”,接收器);返回emailserver.getInstance().sendtextmail(“ [email protected]”,“这里是密码”,“测试发送文本邮件”,“测试发送文本邮件测试发送文本邮件测试发送文本邮件”,接收器);};}ps:正在考虑扩展,如果把这几个类封在jar包中,如何进行邮件服务器配置的扩展。
如有不好之处,欢迎拍砖。