版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
電子郵件發(fā)件實(shí)驗(yàn)電子郵件發(fā)件實(shí)驗(yàn)1電子郵件流程用戶A用戶B服務(wù)器A服務(wù)器B1、用戶A通過郵件客戶端發(fā)送郵件到服務(wù)器A2、服務(wù)器A將郵件發(fā)送到服務(wù)器B3、用戶B接受服務(wù)器B上的郵件電子郵件流程用戶A用戶B服務(wù)器A服務(wù)器B1、用戶A通過郵件客2用戶A郵件發(fā)送過程用戶A客戶端首先和服務(wù)器A建立TCP連接確認(rèn)之后,用戶A和服務(wù)器A之間采用SMTP協(xié)議發(fā)送郵件內(nèi)容郵件內(nèi)容傳輸完畢后,發(fā)送結(jié)束用戶A郵件發(fā)送過程用戶A客戶端首先和服務(wù)器A建立TCP連接3郵件客戶端JAVA程序該程序分為4部分,分別為mailclient、envelope、message、smtpconnectionMailcilent為客戶端主程序,包括使用界面、按鍵的定義,整個(gè)的發(fā)送流程中類的創(chuàng)建message為發(fā)送郵件的內(nèi)容部分,包含有發(fā)件人、收件人等內(nèi)容envelope為用于smtp協(xié)議的信息傳遞,包含發(fā)送接收信息以及message信息smtpconnection為發(fā)件過程中和smtp連接的建立以及關(guān)閉郵件客戶端JAVA程序該程序分為4部分,分別為mailcli4發(fā)送過程中使用的指令HELO250MAILFROM250RCPTTO250DATA354QUIT221發(fā)送過程中使用的指令HELO2505MailClientimportjava.io.*;import.*;importjava.awt.*;importjava.awt.event.*;publicclassMailClientextendsFrame{ privateButtonbtSend=newButton("Send"); privateButtonbtClear=newButton("Clear"); privateButtonbtQuit=newButton("Quit"); privateLabelserverLabel=newLabel("Localmailserver:"); privateTextFieldserverField=newTextField("",40); privateLabelfromLabel=newLabel("From:"); privateTextFieldfromField=newTextField("",40); privateLabeltoLabel=newLabel("To:"); privateTextFieldtoField=newTextField("",40); privateLabelsubjectLabel=newLabel("Subject:"); privateTextFieldsubjectField=newTextField("",40);MailClientimportjava.io.*;6 privateLabelmessageLabel=newLabel("Message:"); privateTextAreamessageText=newTextArea(10,40);
/** *CreateanewMailClientwindowwithfieldsforenteringalltherelevant *information(From,To,Subject,andmessage). */ publicMailClient(){ super("JavaMailClient");
PanelserverPanel=newPanel(newBorderLayout()); PanelfromPanel=newPanel(newBorderLayout()); PaneltoPanel=newPanel(newBorderLayout()); PanelsubjectPanel=newPanel(newBorderLayout()); PanelmessagePanel=newPanel(newBorderLayout()); serverPanel.add(serverLabel,BorderLayout.WEST); serverPanel.add(serverField,BorderLayout.CENTER); fromPanel.add(fromLabel,BorderLayout.WEST); fromPanel.add(fromField,BorderLayout.CENTER); toPanel.add(toLabel,BorderLayout.WEST); privateLabelmessageLabel=7 toPanel.add(toField,BorderLayout.CENTER); subjectPanel.add(subjectLabel,BorderLayout.WEST); subjectPanel.add(subjectField,BorderLayout.CENTER); messagePanel.add(messageLabel,BorderLayout.NORTH); messagePanel.add(messageText,BorderLayout.CENTER); PanelfieldPanel=newPanel(newGridLayout(0,1)); fieldPanel.add(serverPanel); fieldPanel.add(fromPanel); fieldPanel.add(toPanel); fieldPanel.add(subjectPanel);
/**Createapanelforthebuttonsandlistenerstothebuttons.*/ PanelbuttonPanel=newPanel(newGridLayout(1,0)); btSend.addActionListener(newSendListener()); btClear.addActionListener(newClearListener()); btQuit.addActionListener(newQuitListener()); buttonPanel.add(btSend); buttonPanel.add(btClear); buttonPanel.add(btQuit); toPanel.add(toField,BorderL8
/**Add,pack,andshow*/ add(fieldPanel,BorderLayout.NORTH); add(messagePanel,BorderLayout.CENTER); add(buttonPanel,BorderLayout.SOUTH); pack(); show(); }
staticpublicvoidmain(Stringargv[]){ newMailClient(); }
/**HandlerfortheSend-button.*/ classSendListenerimplementsActionListener{ publicvoidactionPerformed(ActionEventevent){ System.out.println("Sendingmail");
/**Checkthatwehavethelocalmailserver*/ if((serverField.getText()).equals("")){ System.out.println("Neednameoflocalmailserver!");
9 return; }
/**確認(rèn)發(fā)送者和接收者的郵件地址正確*/ if((fromField.getText()).equals("")){ System.out.println("Needsender!"); return; }
if((toField.getText()).equals("")){ System.out.println("Needrecipient!"); return; }
/**Createthemessage*/ MessagemailMessage=newMessage(fromField.getText(), toField.getText(), subjectField.getText(), messageText.getText());
return;10 /**Checkthatthemessageisvalid,i.e.,senderandrecipientaddressslookok.*/ if(!mailMessage.isValid()){ System.out.println("Mailisnotvalid!"); return; }
Envelopeenvelope; try { envelope=newEnvelope(mailMessage,serverField.getText()); }catch(UnknownHostExceptione){ /**Ifthereisanerror,donotgofurther*/ System.out.println("Unknownhost!"); return; }
/**Checkthatthemessagei11 try{ SMTPConnectionconnection=newSMTPConnection(envelope); connection.send(envelope); connection.close(); }catch(IOExceptionerror){ System.out.println("Sendingfailed:"+error); return; }
System.out.println("Mailsendsuccessfully!"); } } /**ClearthefieldsontheGUI.*/ classClearListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ System.out.println("Clearingfields"); fromField.setText(""); toField.setText(""); subjectField.setText(""); try{12 messageText.setText(""); } }
/*Quit*/ classQuitListenerimplementsActionListener{ publicvoidactionPerformed(ActionEvente){ System.exit(0); } }} messageText.setText("");13Messageimportjava.util.*;importjava.text.*;publicclassMessage{ publicStringHeaders; publicStringBody;
privateStringFrom; privateStringTo;
/**Tomakeitlooknicer*/ privatestaticfinalStringCRLF="\r\n";
/**CreatethemessageobjectbyinsertingtherequiredheadersfromRFC822(From,To,Date).*/ publicMessage(Stringfrom,Stringto,Stringsubject,Stringtext){ /**Removewhitespace*/Messageimportjava.util.*;14 From=from.trim(); To=to.trim(); Headers="From:"+From+CRLF; Headers+="To:"+To+CRLF; Headers+="Subject:"+subject.trim()+CRLF;
/**Acloseapproximationoftherequiredformat.UnfortunatelyonlyGMT.*/ SimpleDateFormatformat=newSimpleDateFormat("EEE,ddMMMyyyyHH:mm:ss'GMT'"); StringdateString=format.format(newDate()); Headers+="Date:"+dateString+CRLF; Body=text; }
/**Twofunctionstoaccessthesenderandrecipient.*/ publicStringgetFrom(){ returnFrom; }
publicStringgetTo(){ returnTo; }
From=from.trim();15 /**檢查信息的有效性,發(fā)送者和接受者的地址 *containsonlyone@-sign.*/ publicbooleanisValid(){ intfromat=From.indexOf('@'); inttoat=To.indexOf('@');
if(fromat<1||(From.length()-fromat)<=1){ System.out.println("Senderaddressisinvalid."); returnfalse; }
if(toat<1||(To.length()-toat)<=1){ System.out.println("Recipientaddressisinvalid."); returnfalse; }
if(fromat!=From.lastIndexOf('@')){ System.out.println("Senderaddressisinvalid."); returnfalse; } /**檢查信息的有效性,發(fā)送者和接受者的地址 *containsonlyone@-sign.*/ publicbooleanisValid(){ intfromat=From.indexOf('@'); inttoat=To.indexOf('@');
if(fromat<1||(From.length()-fromat)<=1){ System.out.println("Senderaddressisinvalid."); returnfalse; }
if(toat<1||(To.length()-toat)<=1){ System.out.println("Recipientaddressisinvalid."); returnfalse; }
if(fromat!=From.lastIndexOf('@')){ System.out.println("Senderaddressisinvalid."); returnfalse; }郵件客戶機(jī)分析要點(diǎn)課件16
if(toat!=To.lastIndexOf('@')){ System.out.println("Recipientaddressisinvalid."); returnfalse; }
returntrue; }
/**Forprintingthemessage.*/ publicStringtoString(){ Stringres;
res=Headers+CRLF; res+=Body; returnres; }}
17Envelopeimportjava.io.*;import.*;importjava.util.*;publicclassEnvelope{ publicStringSender;
/**SMTP-recipient,orcontentsofTo-header.*/ publicStringRecipient;
/**TargetMX-host*/ publicStringDestHost; publicInetAddressDestAddr;
/**Theactualmessage.*/ publicMessageMessage;
/**Createtheenvelope.*/ publicEnvelope(Messagemessage,StringlocalServer)throwsUnknownHostException{Envelopeimportjava.io.*;18 /**Getsenderandrecipient.*/ Sender=message.getFrom(); Recipient=message.getTo();
Message=escapeMessage(message);
/**TakethenameofthelocalmailserverandmapitintoanInetAddress*/ DestHost=localServer; try{ DestAddr=InetAddress.getByName(DestHost); }catch(UnknownHostExceptione){ System.out.println("UnknownHost:"+DestHost); System.out.println(e); throwe; } return; }
/**Getsenderandrecipient19
privateMessageescapeMessage(Messagemessage){ StringescapeBody=""; Stringtoken; StringTokenizerparser=newStringTokenizer(message.Body,"\n",true);
while(parser.hasMoreTokens()){ token=parser.nextToken(); if(token.startsWith(".")){ token="."+token; }
escapeBody+=token; }
message.Body=escapeBody; returnmessage; }
20 /**Forprintingtheenvelope.Onlyfordebug.*/ publicStringtoString(){ Stringres="Sender:"+Sender+"\n"; res+="Recipient:"+Recipient+"\n"; res+="MX-host:"+DestHost+",address:"+DestAddr+"\n"; res+="Message:"+"\n"; res+=Message.toString();
returnres; }} /**Forprintingtheenvelope21SMTPConnectionimport.*;importjava.io.*;importjava.util.*;publicclassSMTPConnection{ privateSocketconnection;
/**Streamsforreadingandwritingthesocket*/ privateBufferedReaderfromServer; privateDataOutputStreamtoServer;
privatestaticfinalintSMTP_PORT=25; privatestaticfinalStringCRLF="\r\n";
/**Areweconnected?Usedinclose()todeterminewhattodo.*/ privatebooleanisConnected=false;
SMTPConnectionimport.22 /**CreateanSMTPConnectionobject.Createthesocketandtheassociatedstreams.Initialize *SMTPconnection. */ publicSMTPConnection(Envelopeenvelope)throwsIOException{ connection=newSocket(envelope.DestAddr,SMTP_PORT); fromServer=newBufferedReader(newInputStreamReader(connection.getInputStream())); toServer=newDataOutputStream(connection.getOutputStream());
/**Readalinefromserverandcheckthatthereplycodeis220.Ifnot,throwanIOException.*/ Stringreply=fromServer.readLine(); if(reply.startsWith("220")){
}else{ thrownewIOException("Serverreply"+reply); }
/**CreateanSMTPConnection23 /**SMTPhandshake.Weneedthenameofthelocalmachine. *SendtheappropriateSMTPhandshakecommand.*/ Stringlocalhost=envelope.DestHost; try{ sendCommand("HELO"+localhost,250); }catch(IOExceptionerror){ System.out.println(error); System.exit(1); }catch(Exceptione){ System.out.println(e); System.exit(1); }
isConnected=true; }
/**Sendthemessage.WritethecorrectSMTP-commandsinthecorrectorder.Nocheckingforerrors, *justthrowthemtothecaller. */ publicvoidsend(Envelopeenvelope)throwsIOException{ /**SMTPhandshake.Weneed24 /**Sendallthenecessarycommandstosendamessage.CallsendCommand()todothedirty *work.Do_not_catchtheexceptionthrownfromsendCommand(). */ sendCommand("MAILFROM:"+envelope.Sender+CRLF,250); sendCommand("RCPTTO:"+envelope.Recipient+CRLF,250); sendCommand("DATA"+CRLF+envelope.Message.Headers+envelope.Message.Body+CRLF+"."+CRLF,354); }
/**Closetheconnection.First,terminateonSMTPlevel,thenclosethesocket.*/ publicvoidclose(){ isConnected=false; try{ /** sendCommand("QUIT",221);*/ sendCommand("QUIT",250); connection.close(); } /**Sendallthenecessaryc25catch(IOExceptione){ System.out.println("Unabletocloseconnection:"+e); isConnected=true; } }
/**SendanSMTPcommandtotheserver.Checkthatthereplycodeiswhatisissupposedtobe *accordingtoRFC821. */ privatevoidsendCommand(Stringcommand,intrc)throwsIOException{ Stringreply;
toServer.writeBytes(command); toServer.writeBytes(CRLF); System.out.println("Me:"+command+'\n'); reply=fromServer.readLine(); System.out.println("Server:"+reply+'\n'); if(!reply.startsWith(String.valueOf(rc))){ thrownewIOException("Serverreply:"+reply); }
catch(IOExceptione){26 /** if(rc!=parseReply(reply)){ thrownewIOException("Serverreply"+reply); }*/ /** if((command.equalsIgnoreCase("HELO")&&rc!=250)
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 感恩節(jié)活動(dòng)總結(jié) 15篇
- 感恩老師的發(fā)言稿集合15篇
- 律師執(zhí)業(yè)年度工作總結(jié)
- 供電工程施工方案(技術(shù)標(biāo))
- 年會(huì)代表團(tuán)隊(duì)發(fā)言稿范文(10篇)
- 湖南省株洲市高三教學(xué)質(zhì)量統(tǒng)一檢測(cè)(一) 語文試題(含答案)
- 2025版汽車零部件銷售訂購(gòu)合同(年度版)
- 二零二五版淘寶年度合作運(yùn)營(yíng)效果跟蹤協(xié)議3篇
- 精細(xì)化人力資源管理的月度工作計(jì)劃
- 金屬非金屬公司話務(wù)員工作總結(jié)
- 勵(lì)志課件-如何做好本職工作
- 2024年山東省濟(jì)南市中考英語試題卷(含答案解析)
- 靜脈治療護(hù)理技術(shù)操作標(biāo)準(zhǔn)(2023版)解讀 2
- 2024年全國(guó)各地中考試題分類匯編(一):現(xiàn)代文閱讀含答案
- GB/T 30306-2024家用和類似用途飲用水處理濾芯
- 武強(qiáng)縣華浩數(shù)控設(shè)備科技有限公司年產(chǎn)9000把(只)提琴、吉他、薩克斯等樂器及80臺(tái)(套)數(shù)控雕刻設(shè)備項(xiàng)目環(huán)評(píng)報(bào)告
- 安全生產(chǎn)法律法規(guī)匯編(2024年4月)
- DB11∕T 882-2023 房屋建筑安全評(píng)估技術(shù)規(guī)程
- 華為員工股權(quán)激勵(lì)方案
- 衛(wèi)生院安全生產(chǎn)知識(shí)培訓(xùn)課件
- 兒童尿道黏膜脫垂介紹演示培訓(xùn)課件
評(píng)論
0/150
提交評(píng)論