邮件客户机分析要点课件_第1页
邮件客户机分析要点课件_第2页
邮件客户机分析要点课件_第3页
邮件客户机分析要点课件_第4页
邮件客户机分析要点课件_第5页
已阅读5页,还剩36页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

电子邮件发件实验电子邮件发件实验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. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论