下面代码是利用 Java Mail 包封装了一个发送邮件的类
Импорт java.io.file; импорт java.util.arraylist; import java.util.date; импорт java.util.list; import java.util.properties; импорт javax.activation.datahandler; import javax.activation.filedatasource; импорт javax.message; importage.message. javax.mail.multipart; import javax.mail.session; импорт javax.mail.transport; импорт javax.mail.internet.addressexception; импорт javax.mail.internet.internetDdress; import javax.mail.Internet.mimebypart; импорт javax.mail.Memperte.memessAge.mail. javax.mail.internet.mimemultipart; public class sendmail {private static final String mail_address_regex = "^[// w //. Private String MailServer; Частный отправитель строк; частная строка [] приемник; public sendmail () {} public void setMailBasicinfo (String MailServer, String Sender, String Receiver) {this.mailserver = mailserver; this.sender = отправитель; this.receiver = приемник.split (","); } public void setMailBasicInfo (String Mailerver, String Sender, String [] users) {this.mailserver = mailserver; this.sender = отправитель; this.receiver = пользователи; } public void setMailBasicInfo (String Mailerver, String Sender, List <string> пользователи) {this.mailserver = mailserver; this.sender = отправитель; this.receiver = new String [users.size ()]; users.toarray (this.receiver); } public boolean send (строка субъекта, содержимое строки, список <string> filenames) {субъект = субъект == null? "": subject; content = content == null? "": content; Свойства реквизит = новые свойства (); props.put ("mail.smtp.host", mailerver); Session Session = session.getInstance (реквизит, null); try {InternetAddress [] receiver = getReceiverlist (); if (receiver.length == 0) {System.out.println ("приемник is null"); вернуть ложь; } Mimemessage msg = new mimemessage (session); msg.setfrom (new InternetAddress (отправитель)); msg.setrecipients (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 ("Отправить Mail Success"); } catch (messagingException e) {System.out.println ("Отправить почту Fail"); System.out.println (e); вернуть ложь; } catch (Exception e) {return false; } вернуть true; } public boolean send (строка субъекта, строка содержимого) {return send (субъект, контент, null); } public boolean send (строка субъекта) {return send (субъект, null); } private void doAttachfile (многокартовый контейнер, список <string> имена файлов) бросает MessagingException {if (filenames == null || filenames.size () == 0) return; for (String FileName: FileNames) {file f = новый файл (файл); if (! f.isfile ()) продолжить; System.out.println («Файл прикрепления:»+имя файла); Mimebodypart filebodypart = new MimeBodyPart (); FileDataSource fds = new FileDataSource (f); // 要发送的附件地址 fileBodyPart.SetDataHandler (New DataHandler (FDS)); filebodypart.setFilename (fds.getName ()); // 设置附件的名称 intainer.addbodypart (filebodypart); }} private InternetAddress [] getReceiverList () Throws AddersExcept {arraylist <InternetAddress> tolist = new ArrayList <InternetAddress> (); for (int i = 0; i <receiver.length; ++ i) {if (приемник [i] .matches (mail_address_regex)) {tolist.add (new InternetAddress (приемник [i])); }} return (InternetAddress []) tolist.toarray (new InternetAddress [tolist.size ()]); }}使用举例
String host = "168.xx.xx.xx"; // 邮件服务器的地址 string subject = "发送邮件的主题"; string sender = "[email protected]"; list <string> receivers = new arraylist <string> (); receivers.add ("[email protected]"); receivers.add ("[email protected]"); string content = "邮件主题"; sendmail = new sendmail (); приемники); sendmail.send (субъект, контент, null); // 没有附件
正文也可以是 html 内容 , 如
String content = "<html> 详细信息 : <a href = 'xxxx'> 请点击查看! </a> </html>";
我们再来看一个封装好的类
пакет com.message.base.email; Import com.message.base.spring.applicationHelper; import com.message.base.utils.stringutils; import com.message.base.utils.validateutils; import org.slf4j.logger; import.slf4j.loggerfactory; Импорт javax.mail.*; импорт javax.mail.internet.internetDdress; импорт javax.mail.internet.mimemessage; import java.util.collections; импорт java.util.date; импорт java.util.list; импорт java.util.properties; /*** 发送邮件服务器. * * @author sunhao ([email protected]) * @version v1.0, 13-3-25 上午 6:19 */public class emailserver {private Static Final Logger = loggerFactory.getLogger (emailserver.class); // Spring 中配置/** 邮箱服务器配置 **/Private List <EmakeConfig> config; / ** 是否开启 отладка 调试模式 **/ Частный логический isdebug = false; / ** 是否启用身份验证 **/ private boolean isauth = true; / ** 验证类型 **/ private String aitrype = "auth"; / ** * 私有化默认构造器, 使外部不可实例化 */ private emailServer () {}/ ** * 单例, 保证上下文中只有一个 electserver * * @return electserver */ public static emailserver getInstance () {return applicationHelper.getInstance (). GetBean (electserver.class); } / ** * 发送普通邮件 (单个接收人) * * @param username 发件人用户名 * @param Пароль 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param приемник 单个接收人 * @return * / public boolean sendtextmail (String username, String Password, Title String Content, String Receive) {return.sendTextMail (USERNAME, TITELLIGE, Contentiletor) {return This.sendTextmail (USERNAME, TITELLIGELISTLISTLISTLISTLISTLISTLISTELIST. } / ** * 发送普通邮件 (多个接收人) * * @param username 发件人用户名 * @param Пароль 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param приемники 多个接收人 * @return * / public boolean sendtextmail (String username, String Password, название строки, строка содержимого, список <string> приемники) {Authentication Auther atult; if (this.isauth ()) {// 如果需要身份认证 , 则创建一个密码验证器 auth = новая аутентификация (имя пользователя, пароль); } Свойства props = new Properties (); props.setproperty ("mail.smtp.auth", this.isauth ()? "true": "false"); props.setproperty ("mail.transport.protocol", "auth"); Emailconfig config = this.getemailconfig (имя пользователя); props.setproperty ("mail.smtp.host", config.getsmtp ()); props.setproperty ("mail.smtp.port", config.getport () + ""); // 根据邮件会话属性和密码验证器构造一个发送邮件的 Session Session = session.getDefaultInstance (over, auth); session.setdebug (this.isdebug); Сообщение сообщения = this.maketextmail (сеанс, заголовок, контент, имя пользователя, приемники, false); try {transport.send (сообщение); вернуть истину; } catch (messagingException e) {logger.error (e.getMessage (), e); вернуть ложь; }} / ** * 发送 html 邮件 (单个接收人) * * @param username 发件人用户名 * @param пароль 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param приемник 单个接收人 * @return * / public boolean sendhtmlmail (String username, String passwor Контент, Collections.singletonlist (приемник)); } / ** * 发送 html 邮件 (多个接收人) * * @param username 发件人用户名 * @param пароль 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param приемники 多个接收人 * @return * / public boolean sendhtmlmail (string username, строковое пароль, название строки, строковое содержимое, списки <string> execivers) {auttencation atute uthent uthent uthent uttretacation = nool; if (this.isauth ()) {// 如果需要身份认证 , 则创建一个密码验证器 auth = новая аутентификация (имя пользователя, пароль); } Свойства props = new Properties (); props.setproperty ("mail.smtp.auth", this.isauth ()? "true": "false"); props.setproperty ("mail.transport.protocol", "auth"); Emailconfig config = this.getemailconfig (имя пользователя); props.setproperty ("mail.smtp.host", config.getsmtp ()); props.setproperty ("mail.smtp.port", config.getport () + ""); // 根据邮件会话属性和密码验证器构造一个发送邮件的 Session Session = session.getDefaultInstance (over, auth); session.setdebug (this.isdebug); Сообщение сообщения = this.maketextmail (сеанс, заголовок, контент, имя пользователя, приемники, true); try {transport.send (сообщение); вернуть истину; } catch (messagingException e) {logger.error (e.getMessage (), e); вернуть ложь; }} / ** * 获取邮件服务器配置 * * @param Электронная почта 邮箱地址 * @return * / private emailconfig getemailConfig (string email) {string mailServiceDomainname = this.getMailServiceDomainName (электронная почта); для (emailconfig config: this.config) {if (config.getName (). equals (mailServiceMainName)) {return config; }} return null; } / ** * 创建邮件 Сообщение * * * @param session 根据配置获得的 session * @param title 邮件主题 * @param content 邮件的内容 * @param from 发件者 * @param приемники 收件者 * @param ishtmlmail 是否是 html 邮件 * / private maketextmail (сеанс сеанса, название строки, строка, строка от, строка <string> receivers, boolean ishtmail) Mimemessage (Session); try { / ** 标题 ** / logger.info ("Название этой почты {}", title); message.setsubject (заголовок); / ** 内容 **/ logger.info ("Содержимое этой почты {}", content); if (ishtmlmail) {// 是 html 邮件 message.setContent (content, "text/html; charset = utf-8"); } else {// 普通邮件 message.settext (content); } / ** 发件者地址 ** / logger.info ("Отправитель этой почты {}", из); Адрес fromaddress = new InternetAddress (от); message.setfrom (fromaddress); / ** 接收者地址 **/ address [] tos = new InternetAddress [receivers.size ()]; for (int i = 0; i <приемники.size (); i ++) {string receiver = приемники.get (i); if (validateutils.isemail (приемник)) {tos [i] = new InternetAddress (приемник); }} / ** 发件时间 ** / message.setsentDate (new Date ()); message.setRecipents (message.recipienttype.to, tos); } catch (messagingException e) {logger.error (e.getMessage (), e); e.printstacktrace (); } вернуть сообщение; } / ** * 获取邮箱域名 * * @param Электронная почта 邮箱 * @return * / private String getMailServiceDomainName (строка Email) {if (stringUtils.isempty (email)) {return ""; } else {int firstindex = stringUtils.Indexof (электронная почта, "@"); int secondIndex = stringUtils.lastIndexof (электронная почта, "."); return stringutils.substring (электронная почта, FirstIndex + 1, secondIndex); }} public List <ficeConfig> getConfig () {return config; } public void setConfig (list <EmakeConfig> 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 = aithtype; }}
调用方式如下
public boolean sendmail () throws exception {list <string> receivers = new ArrayList <string> (); приемники.add ("[email protected]"); приемники.add ("[email protected]"); EmailServer.getInstance (). Sendhtmlmail ("[email protected]", "这里是密码", "测试发送 html 邮件", "<span style = 'color: red; font-size: 20pt'> 测试发送 html 邮件 </span> <a href = 'http: //ww.baid target = '_ blank'> 链接到百度 </a> ", приемники); return electserver.getInstance (). SendTextMail ("[email protected]", "这里是密码", "测试发送文本邮件", "测试发送文本邮件测试发送文本邮件测试发送文本邮件", приемники);}PS: 正在考虑扩展, 如果把这几个类封在 jar 包中, 如何进行邮件服务器配置的扩展.
如有不好之处, 欢迎拍砖.