下面代碼是利用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包中,如何進行郵件服務器配置的擴展。
如有不好之處,歡迎拍磚。