




版權說明:本文檔由用戶提供并上傳,收益歸屬內容提供方,若內容存在侵權,請進行舉報或認領
文檔簡介
電子郵件發件實驗電子郵件發件實驗1電子郵件流程用戶A用戶B服務器A服務器B1、用戶A通過郵件客戶端發送郵件到服務器A2、服務器A將郵件發送到服務器B3、用戶B接受服務器B上的郵件電子郵件流程用戶A用戶B服務器A服務器B1、用戶A通過郵件客2用戶A郵件發送過程用戶A客戶端首先和服務器A建立TCP連接確認之后,用戶A和服務器A之間采用SMTP協議發送郵件內容郵件內容傳輸完畢后,發送結束用戶A郵件發送過程用戶A客戶端首先和服務器A建立TCP連接3郵件客戶端JAVA程序該程序分為4部分,分別為mailclient、envelope、message、smtpconnectionMailcilent為客戶端主程序,包括使用界面、按鍵的定義,整個的發送流程中類的創建message為發送郵件的內容部分,包含有發件人、收件人等內容envelope為用于smtp協議的信息傳遞,包含發送接收信息以及message信息smtpconnection為發件過程中和smtp連接的建立以及關閉郵件客戶端JAVA程序該程序分為4部分,分別為mailcli4發送過程中使用的指令HELO250MAILFROM250RCPTTO250DATA354QUIT221發送過程中使用的指令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; }
/**確認發送者和接收者的郵件地址正確*/ 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 /**檢查信息的有效性,發送者和接受者的地址 *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; } /**檢查信息的有效性,發送者和接受者的地址 *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; }郵件客戶機分析要點課件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等.壓縮文件請下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯系上傳者。文件的所有權益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網頁內容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
- 4. 未經權益所有人同意不得將文件中的內容挪作商業或盈利用途。
- 5. 人人文庫網僅提供信息存儲空間,僅對用戶上傳內容的表現方式做保護處理,對用戶上傳分享的文檔內容本身不做任何修改或編輯,并不能對任何下載內容負責。
- 6. 下載文件中如有侵權或不適當內容,請與我們聯系,我們立即糾正。
- 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。
最新文檔
- 2025小型工程建筑合同(監控)
- 2025租房合同原件丟失怎么辦
- 2025電競科技有限公司股權轉讓合同示例
- 趣味學習激發幼兒探索欲計劃
- 2025年紡織品交易合同模板
- 農村橋梁建設合同標準文本
- 長形菜地規劃方案范本
- 急救培訓中心急救知識普及工作計劃
- 義齒業務合同樣本
- 企業資產收購合同標準文本
- 湖南省長沙市麓山國際實驗學校2024-2025學年高二下學期第一次學情檢測化學試卷(圖片版含答案)
- 2025-2030中國防火材料行業深度調研及投資前景預測研究報告
- 行政管理本科畢業論文-中國逆城市化現象的成因及啟示
- 2024年浙江錢江生物化學股份有限公司招聘筆試真題
- xx地塊房地產項目可行性研究報告(參考)
- 知識產權法自考考點
- 2024-2025學年第二學期天域全國名校協作體高三3月聯考 語文試卷(含答案)
- 2025光伏發電站綠色拆除技術規范
- 古建筑工程基礎知識單選題100道及答案
- 高中主題班會 遠離背后“蛐蛐”課件-高二下學期人際交往主題班會
- 愛眼護眼知識競賽題及答案
評論
0/150
提交評論