예를 들어, 실제로 사용하면 Taobao에 쇼핑을하고 환불을 신청하는 경우 이메일 주소에 환불 이메일이 표시되거나 계정을 등록하거나 이메일 알림 확인 등을 신청합니다. 모두 이메일 전송입니다. 다음은 시스템 별 비정상적인 이메일 전송 사례를 소개합니다.
준비:
Eclipse4.5 64 비트
JDK1.7 64 비트
메일을 보내기 위해 필요한 항아리 :
Fastjson-1.1.24.jar, javax.mail-1.5.6.jar
클래스 개발자 :
열거 유형, 발신자 이름 및 이메일 주소
패키지 메일; / ** *@class : Developer *@Descript : 열거 유형, 발신자 이름 및 이메일 주소 *@Date : 2016 년 10 월 26 일 오후 8시 50 분. yuxiang ","[email protected] "), yipeng ("ypeng ","[email protected] "), liuan ("liu an ","[email protected] "), chenyuhao ("Chen Yuhao ","Wangdong ", wangdong Dong ","[email protected] "), Sanghaiqin ("Sang Haiqin ","[email protected] "); // 발신자 이름 개인 문자열 이름; // 발신자 이메일 개인 문자열 메일; 개인 개발자 () {} 개인 개발자 (문자열 이름, 문자열 메일) {this.name = name; this.mail = 메일; } / *** @descript : 발신자 이름을 전달하여 발신자의 이메일을 받으려면* @param name 발신자 이름* @return* / public static string getmail (string name) {for (developer c : developer.values ()) {if (c.getName (). equals (name)) {return c.mail; }} return null; } public String getName () {return name; } public void setName (문자열 이름) {this.name = 이름; } public String getMail () {return mail; } public void setmail (문자열 메일) {this.mail = mail; }}
클래스 ExceptionInfo : 발신자 정보
패키지 메일; /** *@class : exceptioninfo *@descript : 발신자 정보 *@날짜 : 2016 년 10 월 26 일 오후 8시 11 분 오후 *@저자 sanghaiqin *@버전 : v1.0 */public class exceptioninfo {// sender name private String developer; // Sender 메소드 개인 문자열 메서드; // Sender URL 개인 문자열 URL; // 발신자는 예외 정보를 잡습니다 프리즈 예외 e; / *** @param 개발자 발신자 이름* @param 메소드 발신자 메소드* @param url 발신자 url* @param e reception information*/ public ExceptionInfo (문자열 개발자, 문자열 메서드, 예외 e) {super (); this.developer = 개발자; this.method = 메소드; this.url = url; this.e = e; } public String getDeveloper () {return Developer; } public void setDeveloper (String Developer) {this.developer = 개발자; } public String getMethod () {return 메소드; } public void setMethod (문자열 메서드) {this.Method = 메소드; } public String getUrl () {return url; } public void seturl (String URL) {this.url = url; } 공개 예외 gete () {return e; } public void sete (예외 e) {this.e = e; }} MailSenderInfo : 이메일 정보를 보냅니다
패키지 메일; java.util.properties import; /** *@class : MailSenderInfo *@descript : 이메일 보내기 *@date : 2016 년 10 월 26 일 오후 8시 14 분 22 초 *@저자 Sanghaiqin *@version : v1.0 */public class mailsenderinfo {// 메일을 보내는 서버의 IP 비공개 문자열 MailServerHost; // 메일을 보내는 서버의 포트는 25 개인 문자열 MailServerport = "25"입니다. // 메일 개인 문자열 발신자의 주소는 AdDdress; // 메일 수신자의 주소 개인 문자열 toaddress; // 메일 보내기 서버의 사용자 이름 개인 문자열 사용자 이름으로 로그인합니다. // 메일 보내기 서버의 비밀번호 비밀번호 비밀번호 비밀번호에 로그인합니다. // 인증 개인 부울 validate = false가 필요합니까? // 이메일 주제 개인 문자열 주제; // 메일 개인 문자열 내용의 텍스트 내용; // 메일 첨부 파일의 파일 이름 개인 문자열 [] att public mailsenderinfo () {super (); } public String getMailServerHost () {return MailServerHost; } public void setMailServerHost (String MailServerHost) {this.MailServerHost = MailServerHost; } public String getMailServerport () {return mailserverport; } public void setmailserverport (String MailServerport) {this.mailserverport = mailserverport; } public boolean isvalidate () {return validate; } public void setValidate (부울 검증) {this.validate = validate; } public String [] getAttAchFilenames () {return att } public void setattachfilenames (string [] filenames) {this.attachfilenames = filenames; } public String getFromAddress () {return fromAddress; } public void setfromAddress (string fromAddress) {this.fromAddress = fromAddress; } public String getPassword () {return password; } public void setpassword (문자열 비밀번호) {this.password = password; } public String getToaddress () {return toaddress; } public void settoaddress (String toaddress) {this.toaddress = toaddress; } public String getUserName () {return username; } public void setusername (String username) {this.username = username; } public string getSubject () {return subject; } public void setSubject (문자열 주제) {this.subject = subject; } public String getContent () {return 컨텐츠; } public void setContent (String TextContent) {this.content = textContent; } / *** @descript : 이메일 세션을 가져옵니다. 속성 속성 = propertyutil.readproperties (); 반환 속성; }} 클래스 myauthenticator : 사용자 인증 자
패키지 메일; import javax.mail.authenticator; Javax.mail.Passwordauthentication import; /** *@class : myauthenticator *@descript : 사용자 확인 *@date : 2016 년 10 월 26 일 오후 8시 57 분 45 초 *@저자 sanghaiqin *@version : v1.0 */public class myauthenticator authenticator {// username string username = null; // 비밀번호 문자열 비밀번호 = null; public myauthenticator () {} public myauthenticator (문자열 사용자 이름, 문자열 암호) {this.username = username; this.password = 비밀번호; } 보호 된 passwordAuthentication getPasswordAuthentication () {return new passwordAuthentication (username, password); }} Class PropertyUtil : 속성 파일 도구 클래스를 얻습니다
패키지 메일; import java.io.fileInputStream; import java.io.filenotfoundException; import java.io.ioexception; import java.io.inputstream; java.util.properties import; / ** *@class : propertyUtil * @descript : 속성 획득 파일 도구 클래스 * @날짜 : 2016 년 10 월 26 일 오후 8시 20 분 10 분 * @저자 Sanghaiqin * @version : v1.0 */ public class propertyutil {/ ** *@descript : 자원 파일로드 *@param 리소스 파일 *@return *@Throws filenot exception */ privection frut). inputStream inputStream = null; 속성 속성 = 새로운 속성 (); // inputStream을 사용하여 리소스 파일을 가져옵니다. {inputStream = new FileInputStream (resources); // 구성 파일 속성을로드 (inputStream); } catch (filenotfoundException e) {e.printstacktrace (); } catch (ioexception e) {e.printstacktrace (); } 마침내 {if (inputStream! = null) {try {inputStream.close (); } catch (ioexception e) {e.printstacktrace (); }} 반환 속성; } / ** * @descript : 속성 파일 읽기 * @return * @throws filenotfoundException * / public properties readProperties () {String Resources = propertyUtil.class.getClassLoader (). getResource ( "prop.Properties"). getPath (); 속성 속성 = LoadProperties (자원); 반환 속성; } / *** @descript : test* @param args* / public static void main (string [] args) {propertyutil p = new PropertyUtil (); 속성 pro = p.readproperties (); String MailSenderUserName = (String) pro.get ( "mail.sender.username"); System.out.println ( "메일 발신자 사용자 이름 :"+mailsenderusername); // [email protected] String Path = PropertyUtil.class.getClassLoader (). getResource ( "prop.Properties"). getPath (); System.out.println (Path); // /g:/workspaces4.4/test/bin/prop.properties}} 리소스 파일 프로.
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #Sender의 이메일 주소 [email protected]
Javamail 클래스 : 사서함을 보내십시오
패키지 메일; import java.io.printwriter; import java.io.stringwriter; java.io.unsupportedencodingException 가져 오기; import java.net.inetAddress; import java.net.unknownhostexception; import java.util.date; java.util.properties import; javax.activation.datahandler import; javax.activation.datasource import; import javax.activation.filedatasource; import javax.mail.address; Javax 가져 오기. javax.mail.bodypart; javax.mail.message import; javax.mail.messagingException import; import javax.mail.multipart; javax.mail.session import; import javax.mail.transport; import javax.mail.internet.internetAddress; import javax.mail.internet.mimebodypart; javax.mail.internet.mimemessage import; import javax.mail.internet.mimemultipart; javax.mail.internet.mimeutility import; / ** *@class : javamail *@descript : 정보 사서함을 보내는 데 필요한 JAR 패키지 *: *fastjson-1.1.24.jar *javax.mail-1.5.6.jar *@date : 2016 년 10 월 26 일 오후 8시 13 분. // 발신자 문자열을 통해 발신자의 이메일을 가져옵니다. if (mail! = null) {mailsenderInfo mailinfo = new MailSenderInfo (); // 이메일의 텍스트 내용을 SetContent ( "책임 :"+info.getDeveloper ()+"==> 서버 IP :"+inetAddress.getLocalHost (). getHostAddress ()+"==> 메소드 이름 :"+info.getMethod ()+"==> 주소 :"+info.getUrl ()+"+"+"+"+" "+getEmessage (info.gete ()); // 이메일 수신자 MailInfo.setOrodDress (Mail)의 주소를 설정합니다. // 이메일 주제 mailinfo.setSubject ( "Yika aitu Exception Notification"); // 이메일 보내기 SendTextMail (MailInfo); }} catch (unknownHostException e) {e.printstacktrace (); }} /*** @descript : 텍스트 형식으로 이메일 보내기* @param : 전송 할 이메일의 MailInfo 정보* @return : 성공한 후 TRUE를 보내십시오. 실패 후 거짓을 반환 */ public static boolean sendtextmail (mailsenderinfo mailinfo) {// 신원 인증이 필요한지 결정 myauthenticator authenticator = null; 속성 pro = mailinfo.getProperties (); try {if ( "true".trim (). equals (pro.getProperty ( "mail.smtp.auth")) {// 인증이 필요한 경우 Authenticator Authenticator = New MyAuthenticator (pro.getProperty ( "Mail.Sender.username"), pro.getProperty ( "Mail.Senden } // 메일 세션 속성 및 비밀번호 인증 자 SendMailSession = Session.GetDefaultInstance (Pro, Authenticator)를 기반으로 메일을 보내는 세션을 구성합니다. // 세션 메시지를 기반으로 메일 메시지를 만듭니다. mailmessage = new Mimemessage (sendmailsession); // new InternetAddress에서 메일 메시지 주소의 발신자를 만듭니다 (pro.getProperty ( "mail.sender.address")); // 메일 메시지의 발신자를 MailMessage.setfrom (from); // 메일 메시지의 수신자 주소를 작성하여 메일 메시지 주소로 설정하십시오. // message.recipientType.to 속성 수신자의 유형이 mailmessage.setRecipient (message.recipientType.to, to)에 대한 것임을 나타냅니다. // 메일 메시지의 주제를 설정합니다. // 메일 메시지를 보내는 시간을 설정합니다 MailMessage.setSentDate (새 날짜 ()); // 메일 메시지의 기본 내용을 MailMessage.settext (mailInfo.getContent ()); // 메일 전송 전송 .send (MailMessage); 진실을 반환하십시오. } catch (MessagingException ex) {ex.printstacktrace (); } false를 반환합니다. } /** * @descript : html 형식으로 메일 보내기 * @param mailinfo : 전송 될 메일 정보 * @param 첨부 파일 : 첨부 내용 * @return : 성공적으로 전송 될 때; 실패한 경우 false */ public static boolean sendhtmlmail (mailsenderinfo mailinfo, string [] 첨부 파일) {// 신분증 인증이 필요한지 결정 myauthenticator authenticator = null; 속성 pro = mailinfo.getProperties (); {// ID 인증이 필요한 경우 비밀번호 인증기를 작성하십시오. if ( "true".trim (). Equals (pro.getProperty ( "mail.smtp.auth"))) {// ID 인증이 필요한 경우 비밀번호 Authenticator = new를 작성하십시오. myauthenticator (pro.getProperty ( "mail.sender.username"), pro.getProperty ( "mail.sender.password")); } // 메일 세션 속성 및 비밀번호 인증자를 기반으로 메일을 보내는 세션을 구성합니다. 세션 sendmailsession = session.getDefaultInstance (Pro, Authenticator); // 세션 메시지를 기반으로 메일 메시지를 만듭니다. mailmessage = new Mimemessage (sendmailsession); // 메일 발신자 주소 주소를 생성 = new InternetAddress (pro.getProperty ( "mail.sender.address")); // 메일 메시지의 발신자를 MailMessage.setfrom (from); // 메일 메시지의 수신자 주소를 작성하여 메일 메시지 주소로 설정하십시오. // message.recipientType.to 속성 수신자의 유형이 mailmessage.setRecipient (message.recipientType.to, to)에 대한 것임을 나타냅니다. // 메일 메시지의 주제를 설정합니다. // 메일 메시지를 보내는 시간을 설정합니다. // minimultipart 클래스는 mimebodypart 유형의 객체를 포함하는 컨테이너 클래스입니다. mainpart = new mimemultipart (); // html 컨텐츠를 포함하는 MimebodyPart를 만듭니다. bodypart html = new MimebodyPart (); // HTML 컨텐츠 설정 html.setContent (mailInfo.getContent (), "text/html; charset = utf-8"); // html 컨텐츠 추가 mimebodypart mainpart.addbodypart (html); // (첨부 파일! = null) {for (string filepath : attachment) {mimebodyPart filePart = new MimeBodyPart (); DataSource Source = New FileDatasource (Filepath); filepart.setdatahandler (New Datahandler (Source)); 시도 {// garbled 파일 이름을 해결하기 위해 온라인으로 순환하는 메소드는 실제로 mimeutility.encodeword를 사용하여 filepart.setfilename (mimeutility.encodeword (source.getname ()))을 해결하는 것이 매우 편리합니다. } catch (UnsupportedEncodingException e) {e.printstacktrace (); } mainPart.AddBodyPart (FilePart); }} // MINIMULTIPART 객체를 메일 컨텐츠 MailMessage.SetContent (MainPart)로 설정합니다. // 컨텐츠 MailMessage.seveChanges ()를 유지합니다. // MailTransport.Send (MailMessage)를 보내십시오. 진실을 반환하십시오. } catch (MessagingException ex) {ex.printstacktrace (); } false를 반환합니다. } / *** @descript : 발신자 메소드에 대한 예외 정보 가져 오기* 문자열 사용 문자열을 문자 입력 및 물리적 노드의 출력 스트림으로 사용합니다. // StringWriter 출력 예외 정보 stritwriter sw = new StringWriter (); printwriter pw = new printwriter (SW, True); E.printstacktrace (PW); pw.flush (); Sw.flush (); 반환 sw.tostring (); } /*** @descript : test* @param args* /public static void main (string [] args) {// test 1 : 텍스트 형식으로 이메일 보내기 {String s = ""; s.substring (2); } catch (예외 e) {e.printstacktrace (); System.out.println (geteMessage (e)); sendExceptionMail (new ExceptionInfo (developer.sanghaiqin.getname (), "get ()", "123", e); } // 테스트 2 : html 형식으로 이메일 보내기 mailsenderinfo mailinfo = new MailSenderInfo (); MailInfo.SetOdDress ( "[email protected]"); // 수신자의 이메일 주소를 설정합니다 MailInfo.setSubject ( "title"); MailInfo.SetContent ( "내용 <H1> www.baidu.com </h1>"); 문자열 [] files = { "g : /upload/image/2016/10/1477372844440.jpg", "g : /upload/image/2016/10/28/147737372845660.jpg"}; javamail.sendhtmlmail (mailinfo, 파일); // html format system.out.println을 보내십시오 ( "성공적으로 보내기"); }}테스트 스크린 샷 :
테스트 1 : 텍스트 형식으로 이메일 보내기 :
테스트 2 : HTML 형식으로 이메일 보내기 :
프로젝트 구조 스크린 샷 :
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.