下面代码是利用 Mail java 包封装了一个发送邮件的类
Importer java.io.file; import java.util.arraylist; import java.util.date; import java.util.list; import java.util.properties; importer javax.activation.datahandler; import javax.activation.filedatasource; importer javax.mail.Message; import javax.mail. javax.mail.multupart; import javax.mail.ession; import javax.mail.transport; import javax.mail.internet.addressException; import javax.mail.internnet.internetaddress; import javax.mail.internet.mimebodypart; import javax.mail.internet.Mimilet javax.mail.internet.mimemultupart; classe publique sendmail {private static final string mail_address_regex = "^ [// w //.=- lal+@_/// w //.- MailServer à chaîne privée; expéditeur de chaînes privées; chaîne privée [] récepteur; public sendmail () {} public void SetMailBasicInfo (String MailServer, String Sender, String Receiver) {this.mailServer = MailServer; this.Sender = Sender; this.receiver = receiver.split (","); } public void SetMailBasicInfo (String MailServer, String Sender, String [] Users) {this.mailServer = MailServer; this.Sender = Sender; this.receiver = utilisateurs; } public void SetMailBasicInfo (String MailServer, String Sender, liste <string> utilisateurs) {this.mailServer = MailServer; this.Sender = Sender; this.receiver = new String [users.size ()]; users.toArray (this.receiver); } public boolean send (String Subject, String Content, list <string> fileNames) {sujet = sujet == null? "": sujet; Content = content == null? "": Content; Properties props = news properties (); propuls.put ("mail.smtp.host", MailServer); Session session = session.getInstance (accessoires, null); essayez {InternetAddress [] récepteur = getReceiverList (); if (receiver.length == 0) {System.out.println ("Le récepteur est null"); retourne false; } MimeMessage msg = new mimeMessage (session); msg.setFrom (nouveau InternetAddress (expéditeur)); msg.setReccipients (message.recipentType.to, récepteur); MSG.SETSUBject (sujet); MSG.SETSentDate (new Date ()); Conteneur en multipar = new mimeMultuparting (); MIMEBODYPART TextBodyPart = new MimeBodyPart (); textBodyPart.setContent (content.toString (), "Text / html; charset = gbk"); contener.addbodyPart (TextBodyPart); DOATTACHFILE (conteneur, noms de fichiers); msg.setContent (conteneur); System.out.println ("Begin Send Mail"); Transport.send (msg); System.out.println ("Envoyer le succès du courrier"); } Catch (MessagedException e) {System.out.println ("Envoyer un courrier échoué"); System.out.println (e); retourne false; } catch (exception e) {return false; } return true; } public boolean send (String Subject, String Content) {return Send (Subject, Content, NULL); } public boolean send (String Subject) {return Send (sujet, null); } private void DOATTACHFILE (Multipart Container, list <string> fileNames) lève MessageSingException {if (fileNames == null || filenames.size () == 0) return; for (String FileName: fileNames) {file f = new File (nom de fichier); si (! F.isfile ()) Continuez; System.out.println ("Le fichier joint est:" + nom de fichier); MIMEBODYPART FileBodyPart = new MIMEBODYPART (); FiledAdAtaSource fds = new FiledAdAtaSource (f); // 要发送的附件地址 filebodyPart.setDatahandler (new Datahandler (fds)); fileBodyPart.setFileName (fds.getName ()); // 设置附件的名称 contener.adddbodyPart (fileBodyPart); }} private InternetAddress [] getReceiverList () lève AddressException {ArrayList <InternetAddress> Tolist = new ArrayList <InternetAddress> (); pour (int i = 0; i <récepteur.length; ++ i) {if (récepteur [i] .matches (mail_address_regex)) {tolist.add (new InternetAddress (récepteur [i])); }} return (InternetAddress []) Tolist.toArray (nouveau InternetAddress [Tolist.size ()]); }}使用举例
String host = "168.xx.xx.xx"; // 邮件服务器的地址 String Subject = "发送邮件的主题"; String Sender = "[email protected]"; list <string> récepteurs = new ArrayList <string> (); receivers.add ("[email protected]"); receivers.add ("[email protected]"); String Content = "邮件主题"; Sendmail Sendmail = New Sendmail (); récepteurs); sendmail.send (sujet, contenu, null); // 没有附件
正文也可以是 html 内容 , 如
String contenu = "<html> 详细信息 : <a href = 'xxxx'> 请点击查看! </a> </html>";
我们再来看一个封装好的类
package com.message.base.email; import com.sessage.base.spring.applicationhelper; import com.sessage.base.utils.stringutils; import com.sessage.base.utils.validateutils; import org.slf4j.logger; import org.slf4j.loggerfactory; Importer javax.mail. *; Importer javax.mail.internet.internetAddress; import javax.mail.internet.mimessage; import java.util.collections; import java.util.date; import java.util.list; import java.util.properties; / ** * 发送邮件服务器. * * @author sunhao ([email protected]) * @version v1.0, 13-3-25 上午 6:19 * / public class emailServer {private static final logger = loggerfactory.getLogger (e-mailserver.class); // printemps 中配置 / ** 邮箱服务器配置 ** / Liste privée <e-mailConfig> config; / ** 是否开启 Debug 调试模式 ** / booléen privé isdebug = false; / ** 是否启用身份验证 ** / private booléen isauth = true; / ** 验证类型 ** / private String authType = "Auth"; / ** * 私有化默认构造器, 使外部不可实例化 * / private e-mailServer () {} / ** * 单例, 保证上下文中只有一个 e-mailserver * * @return emailServer * / public static emailServer getInstance () {return applicationhelper.getInstance (). GetBean (e-mailserver.class); } / ** * 发送普通邮件 (单个接收人) * * @param nom d'utilisateur 发件人用户名 * @param mot de passe 发件人密码 * @param title 邮件标题 * @param contenu 邮件正文 * @param récepteur 单个接收人 * @return * / public booléen sendTextMail (String userName, chaîne mot de passe, chaîne title, contenu, title, contenu, contenu, contenu, collection); } / ** * 发送普通邮件 (多个接收人) * * @param nom d'utilisateur 发件人用户名 * @param mot de passe 发件人密码 * @param title 邮件标题 * @param contenu 邮件正文 * @param récepteurs 多个接收人 * @return * / public boolean sendTextMail (String username, string mot de passe, string title, String Content, list <String> récepteurs) {Authentication authenting = Null; if (this.isauth ()) {// 如果需要身份认证 , 则创建一个密码验证器 auth = new Authentication (nom d'utilisateur, mot de passe); } Properties props = new Properties (); props.setProperty ("mail.smtp.auth", this.isauth ()? "true": "false"); props.setProperty ("mail.transport.protocol", "auth"); EmailConfig config = this.getEmailConfig (nom d'utilisateur); props.setProperty ("mail.smtp.host", config.getsmtp ()); props.setProperty ("mail.smtp.port", config.getport () + ""); // 根据邮件会话属性和密码验证器构造一个发送邮件的 Session Session Session = session.getDefaultInstance (Props, Auth); session.setdebug (this.isdebug); Message Message = this.makeTextMail (session, titre, contenu, nom d'utilisateur, récepteurs, false); essayez {transport.send (message); Retour Vrai; } Catch (MessagedException e) {logger.Error (e.getMessage (), e); retourne false; }} / ** * 发送 html 邮件 (单个接收人) * * @param nom d'utilisateur 发件人用户名 * @param mot de passe 发件人密码 * @param title 邮件标题 * @param contenu 邮件正文 * @param récepteur 单个接收人 * @return * / public boolean sendhtmlmail (string username, chaîne mot de passe, title, contenu de chaîne, titulaire, récepteur, {return this.sendhtmlmail (username, title, title, {return this.sendhtMlmail (Username, title, title, {RETOUR Content, Collection.SingletonList (récepteur)); } / ** * 发送 html 邮件 (多个接收人) * * @param nom d'utilisateur 发件人用户名 * @param mot de passe 发件人密码 * @param title 邮件标题 * @param contenu 邮件正文 * @param récepteurs 多个接收人 * @return * / public boolean sendhtmlmail (Authentication username, string word, string title, string contenu, list> receivers) {Authentication Auth = null; if (this.isauth ()) {// 如果需要身份认证 , 则创建一个密码验证器 auth = new Authentication (nom d'utilisateur, mot de passe); } Properties props = new Properties (); props.setProperty ("mail.smtp.auth", this.isauth ()? "true": "false"); props.setProperty ("mail.transport.protocol", "auth"); EmailConfig config = this.getEmailConfig (nom d'utilisateur); props.setProperty ("mail.smtp.host", config.getsmtp ()); props.setProperty ("mail.smtp.port", config.getport () + ""); // 根据邮件会话属性和密码验证器构造一个发送邮件的 Session Session Session = session.getDefaultInstance (Props, Auth); session.setdebug (this.isdebug); Message Message = this.makeTextMail (session, titre, contenu, nom d'utilisateur, récepteurs, true); essayez {transport.send (message); Retour Vrai; } Catch (MessagedException e) {logger.Error (e.getMessage (), e); retourne false; }} / ** * 获取邮件服务器配置 * * @param e-mail 邮箱地址 * @return * / private e-mailconfig getEmailConfig (String e-mail) {String MailServiceDomainName = this.getMailServEvicedomainName (e-mail); for (emailConfig config: this.config) {if (config.getName (). equals (MailServEvicedomainName)) {return config; }} return null; } / ** * 创建邮件 Message * * @param Session 根据配置获得的 Session * @param title 邮件主题 * @param contenu 邮件的内容 * @param from 发件者 * @param récepteurs 收件者 * @param ishtmlmail 是否是 html 邮件 * / message privé maketextmail (session session, titre de chaîne, contenu de la chaîne, message de la line MimeMessage (session); essayez {/ ** 标题 ** / logger.info ("Le titre de ce courrier est {}", titre); Message.SetSubject (titre); / ** 内容 ** / logger.info ("Le contenu de ce courrier est {}", contenu); if (ishtmlmail) {// 是 html 邮件 message.setContent (contenu, "text / html; charset = utf-8"); } else {// 普通邮件 message.seTText (contenu); } / ** 发件者地址 ** / logger.info ("l'expéditeur de ce courrier est {}", de); Adresse FromAddress = new InternetAddress (From); Message.setFrom (FromAddress); / ** 接收者地址 ** / adresse [] tos = new InternetAddress [récepteurs.size ()]; for (int i = 0; i <receivers.size (); i ++) {String Receiver = Receivers.get (i); if (validerUtils.isemail (récepteur)) {tos [i] = new InternetAddress (récepteur); }} / ** 发件时间 ** / message.sesentDate (new Date ()); Message.SetRcipients (message.recipentType.to, TOS); } Catch (MessagedException e) {logger.Error (e.getMessage (), e); e.printStackTrace (); } retour du message; } / ** * 获取邮箱域名 * * @Param Email 邮箱 * @return * / private String getmailServicedomainName (String e-mail) {if (stringUtils.isempty (email)) {return ""; } else {int premierIndex = stringUtils.Indexof (e-mail, "@"); int secondIndex = stringUtils.lastIndexof (e-mail, "."); return StringUtils.SubString (e-mail, FirstIndex + 1, SecondIndex); }} public list <e-mailConfig> getConfig () {return config; } public void setConfig (list <mailConfig> config) {this.config = config; } public boolean isdebug () {return isdebug; } public void setDebug (boolean debug) {isdebug = debug; } public boolean isauth () {return isAuth; } public void setAuth (boolean auth) {Isauth = auth; } public String getAuthType () {return AuthType; } public void setAuthType (String AuthType) {this.authType = AuthType; }}
调用方式如下
public boolean sendmail () lève une exception {list <string> récepteurs = new ArrayList <string> (); récepteurs.add ("[email protected]"); récepteurs.add ("[email protected]"); EmailServer.getInstance (). Sendhtmlmail ("[email protected]", "这里是密码", "测试发送 html 邮件", "<span style = 'Color: Red; Font-Size: 20pt'> 测试发送 html 邮件 </span> <a href = 'http: //www.baidu.com' Target = '_ Blank'> 链接到百度 </a> ", récepteurs); renvoyer un e-mail.getInstance (). SendTextMail ("[email protected]", "这里是密码", "测试发送文本邮件", "测试发送文本邮件测试发送文本邮件测试发送文本邮件", récepteurs);}PS: 正在考虑扩展, 如果把这几个类封在 Jar 包中, 如何进行邮件服务器配置的扩展.
如有不好之处, 欢迎拍砖.