收藏 分享(赏)

javamail.ppt

上传人:kpmy5893 文档编号:8409251 上传时间:2019-06-25 格式:PPT 页数:61 大小:119.50KB
下载 相关 举报
javamail.ppt_第1页
第1页 / 共61页
javamail.ppt_第2页
第2页 / 共61页
javamail.ppt_第3页
第3页 / 共61页
javamail.ppt_第4页
第4页 / 共61页
javamail.ppt_第5页
第5页 / 共61页
点击查看更多>>
资源描述

1、JavaMail,Electronic Mail Concepts JavaMail Classes Examples of Sending JavaMail JavaBeans Activation Framework Multi-part Messages Example of Sending Attachments Other JavaMail Classes Installing JavaMail,Some Key Terms,Protocol: An agreed upon format for transmitting data between two devices, inclu

2、ding codes for indicating completion of transmission and acknowledgement of data receipt User-Agent: E-mail client that allows user to create e-mail to be sent or view e-mail that has been received Mail Transfer Agent (MTA): Performs exchange of e-mail over TCP,Parts of an E-Mail Message,Envelope Co

3、ntent Headers BodyAddress: workmm6andrew.cmu.edu,Envelope,Used by MTA to deliver messages Contains source and destination addresses Example:MAIL From:mm6andrew.cmu.eduRCPT To:dmedvanandrew.cmu.edu,Headers,Used by user-agent to describe message Written in ASCII text Each field contains a name followe

4、d by a colon, followed by the field value Whitespace may only appear at the beginning of a line that continues a field from a prior line A blank line indicates the end of the headers,Common Headers,From Reply-To Date To CC Subject,Types of Message Bodies,One or more lines of NVT ASCII (7-bit variant

5、) text representing actual message Multipurpose Internet Mail Extension (MIME): Common representation for e-mails sent in binary (attachments, embedded graphics, or non-ASCII characters),MIME Content-Type Header most used MIME-specific header,Examples Text Multipart Message Application Image Audio V

6、ideo,E-mail Protocols,Message Store Protocols: Read messages from a server Internet Message Access Protocol (IMAP) Post Office Protocol (POP) Message Transport Protocols: Send messages to a server (i.e. Simple Mail Transfer Protocol (SMTP),Disadvantages of POP,Only permits access to a single mail fo

7、lder Does not include flags for identifying new and unseen messages Does not include a “Received Date” Does not update new messages while inbox is open,SMTP, of SMTP,Transfers mail from host-to-host over TCP, port 25 Sends commands in ASCII, terminated by newlines Transmits requests and responses as

8、ymmetrically between a Sender-SMTP and a Recipient-SMTP Recipient may be destination host or intermediary, relay SMTP-server Commands and replies are not case sensitive,Receiver-SMTP Responses,Sender-SMTP awaits reply to each message before progressing SMTP supports spooling: message is placed on qu

9、eue and held if there is a delivery problem Reply Format Three ASCII digits Hyphen (space on the last line) Zero or more bytes of text Closing code,SMTP Process,Sender-SMTP establishes transmission channel with a receiver-SMTP Sender-SMTP transmits a MAIL command which identifies the sender Receiver

10、-SMTP responds If ok, Sender-SMTP transmits an RCPT command identifying one or more recipients, one at a time Receiver-SMTP responds for each recipient If ok, Sender-SMTP sends data terminated by a special character SMTP-receiver responds,Example of SMTP Procedure,S: MAIL FROM:SmithAlpha.ARPA R: 250

11、 OKS: RCPT TO:Jones Beta.ARPA R: 250 DOESNT NEED TO SAY OK SINCE 3 DIGIT CODE IS KEYS: RCPT TO:GreenBeta.ARPA R: 550 No such user hereS: DATA R: 354 Start mail input; end with . S: Random content S: More randome content S: . R: 250 OK,Code 250 means everything is OK,www.freesoft.org/CIE/RFC/821/4.ht

12、m,Couldnt send message to GreenBeta.ARPA,Java.util.Properties Class,Extends HashMap (basically another collection) Designed to contain a persistent set of properties that may be saved to or loaded from a stream All keys and values must be Strings Although it supports HashMap methods for handling Obj

13、ects, use of the following is recommended to ensure that it contains Strings: public Object setProperty(String key, String value) public String getProperty(String key),Classes to Send E-mail,Address: Abstract class representing an address Message: Abstract class representing a message Transport: Obj

14、ect representing a transport protocol that allows e-mail messages to be sent, implemented by a specific protocol Session: Provides an interface between the e-mail client and the network, supporting the creation of and access to Store and Transport objects,Message Representation,Javax.mail.Session,Cl

15、ass representing an individual mail session Manages configuration of e-mail system Handles authentication (usually needed for receiving rather than sending mail) Acts as a factory for Transport and Store objects Session has no public constructor Create a session with: public Session getDefaultInstan

16、ce(Properties prop),Session Properties Used to Send Mail at CMU,Javax.Mail.Transport,Abstract class modeling a message Transport By using Session to create a Transport object or to access static Transport methods, the user is abstracted from identifying the appropriate implementing subclass,Instanti

17、ating a Transport,Factory Methods of Session objectpublic Transport getTransport()public Transport getTransport(String protocol) Sending a MessageMessage method: public void saveChanges()Transport method: public void sendMessage(Message msg, Address addresses),Uses Transport protocol in Session prop

18、erties,If you do not save a message before calling sendMessage(), it will not work,Using Static send() Methods,Eliminates the need to instantiate a Transport object Eliminates the need to call the saveMessage() method, since the static send() methods of Transport do that automaticallypublic static s

19、end(Message msg)public static send(Message msg, Address addresses),Address,Abstract class representing any electronic address Most common implementation is for e-mail addresses: javax.mail.internet.InternetAddress,InternetAddress Key Fields,String address: Represents the e-mail address String person

20、al: Represents the name of the addressee,Constructors,InternetAddress(String address)InternetAddress ia = new InternetAddress(“mm6andrew.cmu.edu”);InternetAddress(String address,String personal)InternetAddress ia = new InternetAddress(“mm6andrew.cmu.edu”, “Mike McCarthy”);,Additional Factory Method,

21、static InternetAddress parse(String listOfAddresses, boolean strict) throws AddressException Static method Returns an array of InternetAddresses listOfAddresses is a comma or space delimited list of e-mail addresses If strict is true, space delimited is prohibited AddressException indicates parsing

22、failedInternetAddress.parse(“mm6andrew.cmu.edu, dmedvanandrew.cmu.edu“, false);,Standard Accessors and Mutators,public void setAddress(String) public void setPersonal(String) public String getPersonal() public String getAddress(),E-Mail Message Classes,javax.mail.Message: Abstract class representing

23、 an e-mail message javax.mail.Part: Interface implemented by Message class defining properties and content of mail messages Javax.mail.internet.MimeMessage: Extends Message class and provides functionality to produce MIME messages Most common constructor:MimeMessage(Session session),Message.Recipien

24、tType,Innerclass of Message Possible values: TO CC BCC NEWSGROUPS,MimeMessage Header Methods,Setting Recipients public void setRecipient(Message.RecipientType type, Address address) public void setRecipients(Message.RecipientType type, Address addresses) Adding Additional Recipients public void addR

25、ecipient(Message.RecipientType type, Address address) public void addrecipients(Message.RecipientType type, Address addresses) Getting Recipients public Address getRecipients(Message.RecipientType type) public Address getAllRecipients(),Setting From Header public void setFrom() Sets from to default

26、from property specified in Session properties public void setFrom(Address address) Public void addFrom(Address addresses) Adds one or more addresses to those already listed in the from header Getting From Header public Address getFrom() Reply-To Header public void setReplyTo(Address addresses) publi

27、c Address getReplyTo()Note that several methods use arrays of Addresses,Subject Header public void setSubject(String subject) public String getSubject() Sent Date Header public void setSentDate(Date date) public Date getSentDate(),Content of a Single-Part Message,public void setText(String text) Def

28、aults to ASCII public void setText(String text, String charset) Used for non-ASCII messages or to improve performance if there is a lot of text,Note About Examples,As always, you are encouraged to experiment with the examples that are provided. However, you must make sure that you use your own addre

29、ss in the from, reply-to, and to headers so as not to “spam” anyone.,Example 1: MessageSend.java Sends an e-mail message from one person to another,import java.io.*; import .InetAddress; import java.util.Properties; import java.util.Date; import javax.mail.*; import javax.mail.internet.*;,E-mail add

30、ress class,Properties class,Directory containing abstract mail classes,Internet e-mail classes,createSession(),public Session createSession() Properties p = System.getProperties();p.setProperty(“mail.transport.protocol“, “smtp“);p.setProperty(“mail.smtp.host“,“andrew.cmu.edu“);,Gets the default syst

31、em properties,Sets the transport protocol to SMTP and sets the appropriate SMTP host for CMU,p.setProperty(“mail.store.protocol“,“imap“);p.setProperty(“mail.imap.host“,“cyrus.andrew.cmu.edu“);Session sess = Session.getDefaultInstance(p);return sess; ,Instantiates a session using the new properties o

32、bject,Sets the store protocol to IMAP and sets the appropriate SMTP host for CMU (not really needed unless the application will read e-mail),createMessage(),public Message createMessage(Session sess) throws MessagingExceptionMessage mess = new MimeMessage(sess);,Base exception class for Internet mai

33、l,Default Constructor for a MimeMessage,mess.setFrom(new InternetAddress(“mm6andrew.cmu.edu“);mess.setRecipients(Message.RecipientType.TO,InternetAddress.parse(“bobandrew.cmu.edu“, false);mess.setSubject(“Test“);mess.setText(“This is a test of JavaMails functionality.“);mess.setSentDate(new Date();r

34、eturn mess; ,setRecipients(MessageRecipientType type, String address),main(),public static void main(String args) MessageSend send = new MessageSend();Session sess = send.createSession();try Message mess = send.createMessage(sess);Transport.send(mess); catch(MessagingException e) System.out.println(

35、“Messaging Exception: “+e); ,A static method of the Transport class saves and sends a message,Example 2:MessageSendToMany Sends a message to a group of addresses,import java.io.*; import .InetAddress; import java.util.Properties; import java.util.Date; import javax.mail.*; import javax.mail.internet

36、.*;public class MessageSendToEach public Session createSession() Properties p = System.getProperties(); p.setProperty(“mail.transport.protocol“, “smtp“); p.setProperty(“mail.smtp.host“,“andrew.cmu.edu“); p.setProperty(“mail.store.protocol“,“imap“); p.setProperty(“mail.imap.host“,“cyrus.andrew.cmu.ed

37、u“);Session sess = Session.getDefaultInstance(p);return sess;,Almost everything is the same,createMessage(),public Message createMessage(Session sess)throws MessagingException, UnsupportedEncodingException Message mess = new MimeMessage(sess);InternetAddress recip = new InternetAddress6;InternetAddr

38、ess reply = new InternetAddress1;reply 0 = new InternetAddress(“dmedvanandrew.cmu.edu“,“Danielle Medvan”);,Note the additional exception being thrown,This constructor of InternetAddress throws an UnsupportedEncodingException if the e-mail software does not support the character encoding in which the

39、 name is provided,recip0= new InternetAddress(“garyaandrew.cmu.edu“,“Gary“);recip1= new InternetAddress(“wtzuantaandrew.cmu.edu”,“Tzuan-Ta“);recip2= new InternetAddress(“romoffandrew.cmu.edu”,“Rebecca“);recip3= new InternetAddress(“”,“Mark“);recip4= new InternetAddress(“ginasandrew.cmu.edu”,“Gina“);

40、recip5= new InternetAddress(“cameronwandrew.cmu.edu”,“Cameron“);mess.setFrom(new InternetAddress(“mm6andrew.cmu.edu“);,mess.setReplyTo(reply);mess.setRecipients(Message.RecipientType.TO,recip);mess.setSubject(“Test“);mess.setText(“This is a test of JavaMails functionality.“);mess.setSentDate(new Dat

41、e();return mess; ,The “reply-to” address is set with setReplyTo(Address addresses),We saw the method to set a single recipient. Now we see the method to set multiple recipients,Same main(),public static void main(String args) MessageSendToMany send = new MessageSendToMany();Session sess = send.creat

42、eSession();try Message mess = send.createMessage(sess);Transport.send(mess); catch(MessagingException e) System.out.println(“Messaging Exception: “+e); ,JavaBean Activation Framework (JAF),In multi-part messages, e-mail client needs to handle a variety of file types with a consistent interface JAF c

43、lasses initialize appropriate beans Used by JavaMail clients to interact with messages Determine content type Discover commands supported on that content type Display messages Access data to enable execution of commands,MultiPart Representation,javax.Activation.DataSource,Interface that allows acces

44、s to file type and to streams that can manipulate the file public String getContentType() returns the name of the MIME file type Implemented by javax.Activation.FileDataSource Used by JavaMail to create and retrieve e-mail attachments Constructors FileDataSource(File file) FileDataSource(String file

45、name),javax.Activation.DataHandler,Wrapper for DataSource objects so that the user does not need to manipulate the bytes for each file Constructors DataHandler(DataSource ds) DataHandler(Object obj, String mimeType) Public Object getContent() Returns the data as the object that represents its conten

46、t type (ie runing this method on a text message returns a String),javax.mail.Part Revisited,Allows manipulation of DataHandlers public void setDataHandler(DataHandler dh) Public DataHandler(getDataHandler() Other methods abstract user away from need to directly manipulate DataHandler public void set

47、Content(Object object, String contentType) public Object getContent(),javax.mail.MimeBodyPart,Implements the Part interface (indirectly through a few abstract classes) Contains the content for a single part of an e-mail message Uses several methods to manipulate content directly or through DataHandl

48、er or streams Key Methods public void setText(String text): for text/plain content, makes a String into the message content public void setDataHandler(DataHandler dh) sets the content using a DataHandler (which may be text or any other permitted content) public void setFileName(String filename) sets

49、 the filename associated with the content, if the content represents a file,Javax.mail.Multipart,Container that holds multiple parts Each part is indexed, starting with 0 A Multipart object may be a part within another Multipart object Key Methods public void addBodyPart(BodyPart part) public void addBodyPart(BodyPart part, int index) public int getCount() returns the number of BodyPart objects,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 企业管理 > 管理学资料

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报