たとえば、実際に使用すると、Taobaoで買い物をして払い戻しを申請すると、メールアドレスに払い戻しメールが表示されるか、アカウントを登録して、メール通知の確認などを申請します。これらはすべてメール送信です。ここでは、システムによる異常な電子メール伝送のケースを紹介します。
準備:
Eclipse4.5 64ビット
JDK1.7 64ビット
メールを送信するために必要な瓶:
Fastjson-1.1.24.jar、javax.mail-1.5.6.jar
クラス開発者:
列挙タイプ、送信者の名前、メールアドレス
パッケージメール; / *** *@class:developer *@descript:列挙タイプ、送信者の名前、電子メールアドレス *@日付:2016年10月26日午後8時7:50 pm *@著者Sanghaiqin *@バージョン:v1.0 */ public Enum Developer {Zhoujing( "Zhou Jing"、 "[email protected]")、peiusian yuxiang "、" [email protected] ")、yipeng(" ypeng "、" [email protected] ")、liuan(" liu an "、" [email protected] ")、chenyuhao(" chenyuhao "、" 631604198@q dong "、" [email protected] ")、sanghaiqin(" sang haiqin "、" [email protected] "); //送信者の名前プライベート文字列名。 //送信者メールプライベート文字列メール。 private developer(){} private developer(string name、string mail){this.name = name; this.mail = mail; } / *** @descript:送信者の名前を渡して送信者のメールを取得します* @param name name* @return* / public static string getmail(string name){for(developer c:developer.values()){if(c.getname()。equals(name)){return c.mail; }} nullを返します。 } public string getname(){return name; } public void setName(string name){this.name = name; } public string getMail(){return mail; } public void setmail(string mail){this.mail = mail; }}クラスの例外Info:送信者情報
パッケージメール; /** *@class:ExceptionInfo *@descript:送信者情報 *@日付:2016年10月26日8:11:27 PM *@著者Sanghaiqin *@バージョン:V1.0 */public class ExceptionInfo {// Sender Name Private String Developer; //送信者メソッドプライベート文字列メソッド。 //送信者URLプライベート文字列URL; //送信者は例外情報プライベート例外eをキャッチします。 / *** @param開発者送信者名* @paramメソッド送信者メソッド* @param url送信者URL* @param e送信者は例外情報をキャッチします*/ public ExceptionInfo(String Developer、String Method、String URL、Exception E){super(); this.developer = developer; this.method = method; this.url = url; this.e = e; } public string getDeveloper(){return developer; } public void setDeveloper(String Developer){this.developer = developer; } public string getMethod(){return method; } public void setMethod(string method){this.method = method; } public string geturl(){return url; } public void seturl(string url){this.url = url; } public Excetion gete(){return e; } public void sete(例外e){this.e = e; }} MailSenderInfo:電子メール情報を送信します
パッケージメール; java.util.propertiesをインポートします。 /** *@class:mailsenderinfo *@descript:電子メール情報を送信 *@日付:2016年10月26日8:14:22 pm *@著者Sanghaiqin *@バージョン:V1.0 */public Class MailSenderInfo {//メールを送信するサーバーのIPプライベート文字列MailServerHost; //メールを送信するサーバーのポートは25のプライベート文字列mailserverport = "25"です。 // Address Fromdressのメールの送信者のアドレス。 //メール受信者のアドレスプライベート文字列Toaddress; //メール送信サーバーのユーザー名プライベート文字列ユーザー名にログインします。 //サーバーのパスワードを送信するメールにログインしますプライベート文字列パスワード。 //認証が必要ですか?private boolean validate = false; //件名のプライベート文字列件名を電子メールで送信します。 //メールプライベート文字列コンテンツのテキストコンテンツ。 //メール添付ファイルのファイル名プライベート文字列[] AttachFileNames; 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(boolean validate){this.validate = validate; } public string [] getAttachFileNames(){return attachFileNames; } public void setattachfileNames(string [] filenames){this.attachfileNames = filenames; } public string getFromAddress(){return fromDdress; } public void setfromAddress(String fromDdress){this.fromAddress = fromDdress; } public string getPassWord(){パスワードを返します。 } public void setPassword(string password){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(string subject){this.subject = subject; } public string getContent(){return content; } public void setContent(String TextContent){this.content = textContent; } / *** @descript:get email Session Property* @return* / public Properties getProperties(){propertyUtil PropetitiL = new PropertyUtil();プロパティプロパティ= propertyutil.readproperties();返品プロパティ。 }}クラスmyAuthenticator:ユーザー認証者
パッケージメール; javax.mail.authenticatorをインポートします。 javax.mail.passwordauthenticationをインポートします。 /** *@class:myauthenticator *@descript:ユーザー検証 *@日付:2016年10月26日8:57:45 PM *@著者Sanghaiqin *@バージョン:V1.0 */public class myAuthenticator {// username文字列username = null; //パスワード文字列パスワード= null; public MyAuthenticator(){} public MyAuthenticator(string username、string password){this.username = username; this.password = password; } protected passwordAuthentication getPassWordAuthentication(){return new PasswordAuthentication(username、password); }}クラスPropertyUtil:プロパティファイルツールクラスを取得します
パッケージメール; java.io.fileinputStreamをインポートします。 java.io.filenotfoundexceptionをインポートします。 java.io.ioexceptionをインポートします。 java.io.inputStreamをインポートします。 java.util.propertiesをインポートします。 / ** *@class:propertyutil * @descript:プロパティファイルツールクラスの取得 * @日付:2016年10月26日午後8時20:10 * @著者sanghaiqin * @バージョン:v1.0 */ public class propertyutil {/ ** *@descript:リソースファイルの読み込み *@paramリソースファイル *@return *@throws filenotfoundexexperties inputstream = null;プロパティプロパティ= new Properties(); // inputstreamを使用してリソースファイルを取得してください{inputstream = new fileinputStream(resources); //構成ファイルProperties.load(inputStream)をロードします。 } catch(filenotfoundexception e){e.printstacktrace(); } catch(ioexception e){e.printstacktrace(); }最後に{if(inputstream!= null){try {inputstream.close(); } catch(ioexception e){e.printstacktrace(); }} return Properties; } / ** * @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( "Mail Sender username:"+mailsenderusername); // [email protected] String path = propertyutil.class.getClassoource( "prop.properties")。getPath(); System.out.println(path); // /g:/workspaces4.4/test/bin/prop.properties}}リソースファイルpro.properties:
#-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- #送信者のメールアドレスmail.sender.address = [email protected]
Javamailクラス:メールボックスを送信します
パッケージメール; java.io.printwriterをインポートします。 java.io.StringWriterをインポートします。 java.io.unsupportedencodingexceptionをインポートします。 java.net.inetAddressをインポートします。 java.net.unknownhostexceptionをインポートします。 Import Java.util.date; java.util.propertiesをインポートします。 javax.activation.datahandlerをインポートします。 javax.activation.datasourceをインポートします。 javax.activation.filedatasourceをインポートします。 javax.mail.addressをインポートします。 Javaxをインポートします。 javax.mail.bodypart; javax.mail.messageをインポートします。 javax.mail.messagingexceptionをインポートします。 javax.mail.multipartをインポートします。 javax.mail.sessionをインポートします。 javax.mail.transportをインポートします。 javax.mail.internet.internetaddressをインポートします。 javax.mail.internet.mimebodypartをインポートします。 javax.mail.internet.mimemessageをインポートします。 javax.mail.internet.mimemultipartをインポートします。 javax.mail.internet.mimeutilityをインポートします。 / ** *@class:javamail *@説明:情報送信に必要なJARパッケージメールボックス *: *Fastjson-1.1.24.jar *Javax.Mail-1.5.6.jar *@日付:2016年10月26日8:13:05 try {//送信者文字列mail = developer.getmail(info.getDeveloper())を介して送信者のメールを取得します。 if(mail!= null){mailsenderinfo mailinfo = new MailSenderInfo(); //メールMailInfo.setContentのテキストコンテンツを設定する( "責任:"+info.getDeveloper()+"==> server IP:"+inetAddress.getLocalHost()。gethostAddress()+"==>メソッド名:"+info.getmethod()+"==> "+getemessage(info.gete())); //電子メール受信者MailInfo.SettoAddress(メール)のアドレスを設定します。 //件名mailinfo.setsubject( "yika aitu例外通知"); //電子メールSendTextMail(MailInfo); }} catch(unknownhostexception e){e.printstacktrace(); }} /*** @descript:電子メールをテキスト形式で送信* @param:emailinfo embly of emailの情報送信* @return:送信後にtrueを送信します。障害後にfalseを返します */ public static boolean sendtextmail(mailsenderinfo mailinfo){//識別認証が必要かどうかを判断しますmyauthenticator authenticator = null; Properties Pro = MailInfo.getProperties(); try {if( "true" .trim()。 } //メールセッションのプロパティとパスワードに基づいてメールを送信するセッションを構築しますAuthenticator Sendmailsession = session.getDefaultInstance(Pro、Authenticator); //セッションメッセージに基づいてメールメッセージを作成するmailmessage = new Mimemessage(sendMailsession); // = new InternetAddress(pro.getProperty( "mail.sender.address")からメールメッセージアドレスの送信者を作成します。 //メールメッセージの送信者を設定mailmessage.setfrom(from); //メールメッセージの受信者アドレスを作成し、= new InternetAddress(MailInfo.getToAddress())にメールメッセージアドレスに設定します。 // message.recipientType.to属性は、受信者のタイプがmailmessage.setRecipient(message.recipientType.to、to)であることを示します。 //メールメッセージの件名を設定mailmessage.setsubject(mailinfo.getSubject()); //メールメッセージを送信する時間を設定mailmessage.setsentdate(new date()); //メールメッセージのメインコンテンツを設定mailmessage.settext(mailinfo.getContent()); //メールTransport.send(MailMessage)を送信します。 trueを返します。 } catch(messagingexception ex){ex.printstacktrace(); } falseを返します。 } /** * @descript:html formatでメールを送信 * @param mailinfo:送信するメールの情報false failed */ public static boolean sendhtmlmail(mailsenderinfo mailinfo、string [] attachment){//識別認証が必要かどうかを判断しますvyauthenticator authenticator = null; Properties Pro = MailInfo.getProperties(); try {// ID認証が必要な場合は、パスワードAuthenticatorを作成しますif( "true" .trim()。equals( "mail.smtp.auth")){// IDENTIUNCE認証が必要な場合は、パスワードAuthenticator = newを作成しますmyauthenticator(pro.getProperty( "mail.sender.username")、pro.getProperty( "mail.sender.password")); } //メールセッションのプロパティとパスワード認証器に基づいてメールを送信するセッションを作成します。 SESSION SENDMAILSESSION = SESSION.GETDEFAULTINSTANCE(Pro、Authenticator); //セッションメッセージに基づいてメールメッセージを作成するmailmessage = new Mimemessage(sendMailsession); //メール送信者アドレスを作成します。 //メールメッセージの送信者を設定mailmessage.setfrom(from); //メールメッセージの受信者アドレスを作成し、= new InternetAddress(MailInfo.getToAddress())にメールメッセージアドレスに設定します。 // message.recipientType.to属性は、受信者のタイプがmailmessage.setRecipient(message.recipientType.to、to)であることを示します。 //メールメッセージの件名を設定mailmessage.setsubject(mailinfo.getSubject()); //メールメッセージを送信する時間を設定mailmessage.setsentdate(new date()); // minimultipartクラスは、mimebodypartタイプMultipart mainpart = new Mimemultipart()のオブジェクトを含むコンテナクラスです。 // HTMLコンテンツボディパートHTML = new MimeBodyPart()を含む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(新しいDatahandler(Source)); {//オンラインで循環するメソッドは、filepart.setfileName(mimeutility.encodeword(source.getname()))を解くためにmimeutility.encodewordを使用するのに実際に非常に便利です。 } catch(unsupportedencodingexception e){e.printstacktrace(); } mainpart.addbodypart(filepart); }} // minimultipartオブジェクトをメールコンテンツmailmessage.setcontent(mainpart)に設定します。 // content mailmessage.savechanges(); // mailtransport.send(mailmessage)を送信します。 trueを返します。 } catch(messagingexception ex){ex.printstacktrace(); } falseを返します。 } / *** @descript:送信者メソッドに関する例外情報を取得*文字列を物理ノードの文字入力と出力ストリームとして使用します。つまり、StringReaderとStringWriter* Printwriter(Writer Out、Boolean Autoflush)の使用法を自動列のリフレッシュで新しいプリントライターを作成します。 // stringwriter出力例外情報stringwriter 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){//テスト1:テキスト形式でメールを送信してください{string s = ""; S.Substring(2); } catch(Exception e){e.printstacktrace(); system.out.println(getemessage(e)); sendexceptionmail(new ExceptionInfo(developer.sanghaiqin.getName()、 "get()"、 "123"、e)); } //テスト2:html形式でメールを送信mailsenderininfo mailinfo = new MailSenderInfo(); mailinfo.settoaddress( "[email protected]"); //受信者のメールアドレスを設定しますmailinfo.setsubject( "title"); MailInfo.setContent( "Content <h1> www.baidu.com </h1>"); string [] files = {"g:/upload/image/2016/10/28/147772845440.jpg"、 "g:/upload/image/2016/10/28/14777772845660.jpg"}; javamail.sendhtmlmail(mailinfo、files); // HTMLフォーマットSystem.out.printlnを送信( "SENCEFULLY"); }}スクリーンショットのテスト:
テスト1:テキスト形式でメールを送信します。
テスト2:HTML形式でメールを送信します。
プロジェクト構造のスクリーンショット:
上記はこの記事のすべての内容です。私はそれがすべての人の学習に役立つことを願っています、そして、私は誰もがwulin.comをもっとサポートすることを願っています。