下面代码是利用 Java 메일 av
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; javax.mail.multipart; import javax.mail.session; import javax.mail.transport; import javax.mail.internet.addressexception; import javax.mail.internetaddress; import javax.mail.internet.mimebodypart; import javax.mail.mimestege; javax.mail.internet.mimemultipart; public class sendmail {private static final string mail_address_regex = "^[// w //.=-] +@=///.- w //-] +/. 9] {2,3} $"; 개인 문자열 MailServer; 개인 문자열 발신자; 개인 문자열 [] 수신기; public sendmail () {} public void setmailbasicinfo (문자열 메일 서버, 문자열 발신자, 문자열 수신기) {this.mailserver = mailserver; this.sender = 발신자; this.receiver = receiver.split ( ","); } public void setMailBasicInfo (String MailServer, String Sender, String [] users) {this.MailServer = MailServer; this.sender = 발신자; this.receiver = 사용자; } public void setMailBasicInfo (String MailServer, String Sender, List <string> 사용자) {this.mailserver = MailServer; this.sender = 발신자; this.receiver = new String [users.size ()]; user.toarray (this.receiver); } public boolean send (문자열 주제, 문자열 내용, list <string> filenames) {subject = subject == null? ": 주제; content = content == null? "": 내용; 속성 propss = 새로운 속성 (); props.put ( "mail.smtp.host", mailserver); 세션 세션 = 세션 .getInstance (props, null); {interctaddress [] 수신기 = getReceiverList (); if (수신기 .length == 0) {System.out.println ( "수신기는 null"); 거짓을 반환합니다. } mimemessage msg = 새로운 mimemessage (세션); msg.setfrom (new InternetAddress (sender)); msg.setRecipients (message.recipienttype.to, 수신기); msg.setsubject (주제); msg.setsentDate (새 날짜 ()); 멀티 파트 컨테이너 = 새로운 mimemultipart (); MimeBodyPart TextBodyPart = New MimeBodyPart (); TextBodyPart.setContent (content.toString (), "text/html; charset = gbk"); 컨테이너 .addbodyPart (TextBodyPart); doattachfile (컨테이너, 파일 이름); msg.setContent (컨테이너); System.out.println ( "메일 보내기 시작"); 운송 .send (MSG); System.out.println ( "메일 성공 보내기"); } catch (MessagingException e) {System.out.println ( "Mail 실패 보내기"); System.out.println (e); 거짓을 반환합니다. } catch (예외 e) {return false; } true를 반환합니다. } public boolean send (문자열 주제, 문자열 내용) {return send (주제, 내용, null); } public boolean send (문자열 주제) {return send (주제, null); } private void doattachfile (Multipart 컨테이너, 목록 <string> filenames)은 메시징 지출을 던집니다 (filenames == null || filenames.size.size () == 0) return; for (string filename : filenames) {file f = 새 파일 (filename); if (! f.isfile ()) 계속; System.out.println ( "첨부 파일은 :"+filename); MimeBodyPart FileBodyPart = New MimeBodyPart (); FileDatasource FDS = New FileDatasource (F); // 要发送的附件地址 FileBodyPart.SetDataHandler (New Datahandler (FDS)); fileBodyPart.setFileName (fds.getName ()); // 设置附件的名称 컨테이너 .addbodyPart (FileBodyPart); }} private InternetAdDress [] getReceiverList ()는 jusderException {arrayList <NettertAddress> tolist = new ArrayList <NogultAddress> (); 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 ()]); }}使用举例
문자열 호스트 = "168.xx.xx.xx"; // 邮件服务器的地址 string subject = "发送邮件的主题"; String sender = "[email protected]"; list <string> receivers = new Arraylist <string> (); receers.add ( "[email protected]"); receers.add ( "[email protected]"); String content = "邮件主题"; sendmail sendmail = new sendmail (); 수신기); sendmail.send (주제, 내용, null); // 没有附件
Html t t, 如
문자열 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 org.slf4j.loggerfactory; Javax.mail. /*** 发送邮件服务器. * * @author sunhao ([email protected]) * @version v1.0, 13-3-25 上午 6:19 */public class emailserver {private static final logger = loggerfactory.getLogger (emailserver.class); // 스프링*/** 邮箱服务器配置 **/개인 목록 <AildentConfig> 구성; / ** ug Debug 调试模式 **/ private boolean isdebug = false; / *****/ private boolean isauth = true; / *****/ 개인 문자열 authtype = "auth"; / ** * 私有化默认构造器, 使外部不可实例化 */ private emailserver () {}/ ** * 单例, 保证上下文中只有一个 emailserver * * @return emailserver */ public static emailserver getInstance () {return applicationHelper.getInstance (). getBean (emailserver.class); } / ** * * * * (单个接收人) * * @param username 发件人用户名 * @param password 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param 수신기 单个接收人 * @return * / public boolean sendTextMail (문자열 암호, 문자열 제목, 문자열 내용, 문자열 수신기) {return this.sendTextMail (username, 컨텐츠, 제목, 제목, Collections.SingletonList (수신기)); } / ** * * (多个接收人) * * @param username 发件人用户名 * @param password 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param receivers 多个接收人 * @return * / public boolean sendTextMail (문자열 암호, 문자열 제목, 문자열 컨텐츠, 목록 <문자열> 수신기) {인증 인증 인증 인증 = null; if (this.isauth ()) {// 如果需要身份认证, auth = new Authentication (username, password); } 속성 소품 = 새로운 속성 (); 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 () + ""); // 根据邮件会话属性和密码验证器构造一个发送邮件的 세션 세션 세션 = 세션 .getDefaultInstance (props, auth); session.setdebug (this.isdebug); 메시지 메시지 = this.maketextMail (세션, 제목, 내용, 사용자 이름, 수신기, 거짓); try {송신 .send (메시지); 진실을 반환하십시오. } catch (messagingException e) {logger.error (e.getMessage (), e); 거짓을 반환합니다. }} / ** * 发送 html 邮件 (单个接收人 单个接收人) * * @param username 发件人用户名 * @param password 发件人密码 * @param title 邮件标题 * @param content 邮件正文 * @param 수신기 单个接收人 * @return * / public boolean sendhtmlmlml (문자열 사용자 이름, 문자열 제목, 문자열 내용, String, String) {return this.sendhtmmail, user, 내용, collections.singletonlist (수신기)); } / ** * * html 邮件 (多个接收人 多个接收人) * * @param username 发件人用户名 * @param password 发件人密码 * @param title 邮件标题 * @param 컨텐츠 邮件正文 * @param 수신기 多个接收人 * @return * / public boolean sendhtmlmlmail (문자열 사용자 이름, 문자열 제목, 문자열 내용, 목록 <문자열> 수신기) {aure earl earth = null; if (this.isauth ()) {// 如果需要身份认证, auth = new Authentication (username, password); } 속성 소품 = 새로운 속성 (); 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 () + ""); // 根据邮件会话属性和密码验证器构造一个发送邮件的 세션 세션 세션 = 세션 .getDefaultInstance (props, auth); session.setdebug (this.isdebug); Message Message = this.maketextMail (세션, 제목, 내용, 사용자 이름, 수신기, true); try {송신 .send (메시지); 진실을 반환하십시오. } catch (messagingException e) {logger.error (e.getMessage (), e); 거짓을 반환합니다. }} / ** * * * * @param email 邮箱地址 * @return * / private emailconfig getEmailConfig (문자열 이메일) {String MailServicedOmainName = this.GetMailServicedOmainName (이메일); for (emailconfig config : this.config) {if (config.getName (). equals (mailServicedOmainName)) {return config; }} return null; } / ** * 메시지 * * @param 세션 根据配置获得的 세션 * @param title 邮件主题 * @param content 邮件的内容 * @param from 发件者 * @param recevers 发件者 * @param ishtmlmail 是否是 html 邮件 * / private message maketextmail (세션 세션, 문자열 내용, 문자열, list <string>) Mimemessage (세션); 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 ( "이 메일 발신자는 {}", from); ADDRESS의 주소 = 새로운 InternetAdDress (From); message.setfrom (fromAddress); / *****/ address [] tos = new InternetAddress [receivers.size ()]; for (int i = 0; i <receivers.size (); i ++) {문자열 수신기 = 수신기.get (i); if (validateUtils.isemail (수신기)) {tos [i] = new InternetAddress (수신기); }} / ** 发件时间 ** / message.setSentDate (new date ()); message.setRecipients (message.recipienttype.to, tos); } catch (messagingException e) {logger.error (e.getMessage (), e); e.printstacktrace (); } 반환 메시지; } / ** * * * @param email 邮箱 * @return * / private String getMailServicedOmainName (String email) {if (stringUtils.isempty (email)) {return ""; } else {int firstIndex = stringUtils.IndExOf (이메일, "@"); int secondIndex = stringUtils.lastIndexOf (이메일, "."); Return StringUtils.substring (이메일, FirstIndex + 1, SecondIndex); }} public list <emailconfig> getConfig () {return config; } public void setconfig (list <emailconfig> config) {this.config = config; } public boolean isdebug () {return isdebug; } public void setDebug (부울 디버그) {isdebug = 디버그; } public boolean isauth () {return isauth; } public void setauth (부울 인증) {isauth = auth; } public String getAuthType () {return AuthType; } public void setauthtype (String authtype) {this.authtype = authtype; }}
调用方式如下
public boolean sendmail ()는 예외를 던져 {list <string> 수신기 = new Arraylist <string> (); receivers.add ( "[email protected]"); 수신기 .add ( "[email protected]"); emailserver.getInstance (). sendhtmlmail ( "[email protected]", "这里是密码", "测试发送 html 邮件", "<span style = 'color : 빨간색; font-size : 20pt'> 测试发送 html </span> <http = 'http : //www.baidu.com' 대상 = '_ blank'> 链接到百度 </a> ", 수신기); return emailserver.getInstance (). sendTextMail ( "[email protected]", "这里是密码", "测试发送文本邮件", "测试发送文本邮件测试发送文本邮件测试发送文本邮件", 수신기);}추신 : 正在考虑扩展, 正在考虑扩展 jar 包中, 如何进行邮件服务器配置的扩展.
如有不好之处, 欢迎拍砖.