1 / 56

JavaMail (1)

JavaMail (1). Presented by: Ke Duan Instructor: Dr. V. “Juggy” Jagannathan. Background. Internet’s most used service: electronic mail. Technologies: various protocols & multiple APIs involved.

zan
Download Presentation

JavaMail (1)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JavaMail (1) Presented by: Ke Duan Instructor: Dr. V. “Juggy” Jagannathan

  2. Background • Internet’s most used service: electronic mail. • Technologies: various protocols & multiple APIs involved. • JavaMail specification: provides a collection of abstract classes that define the common objects and their interfaces for any general mail system. By defining the interfaces for mail sessions, massages, transports, and stores, Sun has given Java programmers an easy and extensible object-oriented view of the many existing protocols currently in use.

  3. Background • Interfaces & abstract classes are not directly usable  JavaMail providers implement the API  provide concrete functionality needed to communicate using specific protocols.

  4. Background • Essential protocols and specification: Simple Mail Transfer Protocol (SMTP) Internet Massage Access Protocol (IMAP) Multipurpose Internet Mail Extensions (MIME) Post Office Protocols 3 (POP3)

  5. Background • Two basic types of protocols that providers can implement: * Transport: Sun’s term for a service that has the capability to send messages to their destination. (SMTP) * Store: a service you would connect to in order to retrieve messages that have been delivered to your mailbox. (POP3 & IMAP)

  6. Setup Instructions • Both JavaMail API and Java Activation Framework are included in the Enterprise Edition of the Java 2 Platform. No separate download is necessary. • Download the reference implementation from Sun’s JavaMail site at http://java.sun.com/products/javamail/ extract the archive’s contents, and ensure the included mail.jar file is available to the java Virtual Machine (by adding its path to the CLASSPATH environmental variable).

  7. The Provider Registry • New protocols were developed.  Providers for those protocols could be added to a system and be immediately usable by any of the pre-existing JavaMail enabled applications with little changes. The way in which these applications detect which providers are available to them is done through the Provider Registry.

  8. Provider Registry • A program that can list the available providers on your system: Import javax.mail. *; Class ListProviders { public static void main (String[] args) { Session session = session.getInstance (System.getProperties (), null); Provider[] providers = session.getProviders (); for ( int I = 0; I < provider.length; ++I ) { System.out.printin ( providers[I] ); }} }

  9. JavaMail API • We are going to cover the following topics in JavaMail API: • java.mail.Session • javax.mail.Authenticator and PasswordAuthentication • javax.mail.Message • javax.mail.Part • javax.mail.Multipart and BodyPart • javax.mail.internet.MimePart and MimeMessage • javax.mail.internet.MimeMultipart and MimeBodyPart • javax.mail.Service • javax.mail.Transport

  10. We have only 3 minutes on each sub-topic !!

  11. Javax.mail.Session • Acts as a factory for the installed Transport and Store implementations. • Responsible for managing a user’s mail configuration settings and handling authentication for the individual services used during the session. • A way to associate providers with a particular set of user properties and an authentication mechanism.

  12. Javax.mail.Session • Can be stored as an object in the servlet’s session so that the appropriate relationship can be maintained. • The application will be retrieving the correct Transport and Store objects based on the current user’s settings by interacting with the session. • Server-side applications will likely be creating a session for each connected client.

  13. Javax.mail.SessionConstructing a Session • JavaMail session class does not implement public constructors. • Potential clients are expected to use the one of the following public static methods to acquire session reference: • Static Session getInstance (Properties prope, Authenticator authenticator) //constructs and returns a new unshared Session instance with the specified Properties and Authenticator. • Static Session getDefaultInstance (Properties prope, Authenticator authenticator) //returns the default (shared) Session instance.

  14. Javax.mail.SessionConstructing a Session • GetInstance () method returns a new instance with each invocation. • getDefaultInstance () repeatedly returns the same instance, as long as the specified Authenticator is a reference to the same instance passed in when the default session was initially created.  useful when developing single-user applications.

  15. Javax.mail.SessionConstructing a Session • Java.util.Properties object that is passed into both of these two methods is usually obtained by invoking the system.getProperties method.JavaMail-specific properties can then be added: Properties props = system.getProperties (); props.put (“mail.transport.protocol”, “smtp”); props.put (“mail.smtp.host”, “mail.foo.com”); Session session = Session.getInstance (props, null);

  16. Javax.mail.SessionSession Properties • Mail.transport.protocol the default transport protocol, implemented by Transport class returned from Session.getTransport (). • Mail.store.protocol the default store protocol, implemented by Store class returned from Session.getStore (). • Mail.host the default host for both Store and Transport protocol. • Mail.user the default user name for both Store and Transport protocol. • Mail.from  the user’s return e-mail address • Mail.protocol.host  the host specific to a particular protocol. • Mail.protocol.user  the default user name specific to a particular protocol. • Mail. Debug the default debug setting for sessions. This can be overridden with setDebug (boolean).

  17. Javax.mail.SessionSession Properties * Properties getProperties (); //return the properties collection specified when constructing the session. * String getProperties (string name); //return the value of the specified property or null if it does not exist. * void setDebug (boolean debug); //set the debug setting for this session. If it set true, debug massage will be output to the console by both the session and its providers. * boolean getDebug (); //return the debug setting for this session. Can be used to determine whether debug message should be output.

  18. Javax.mail.Authenticator and PasswordAuthentication * Javax.mail.passwordAuthentication getPasswordAuthentication (); //Invoked by a Session when password authentication is needed. Any number of implementations is possible as long as a PasswordAuthentication instance is returned. * PasswordAuthentication (String username, String password); //Returning a PasswordAuthentication instance is simple a matter of invoking this constructor. This should be constructed and returned in the client’s implementation of getPasswordAuthentication.

  19. Javax.mail.Authenticator and PasswordAuthentication • The Authenicator class also includes several protected methods that provide access to the typical properties that would enable building a reasonable explicit prompt for the user: protected String getRequestingProtocol (); protected int getRequestingPort (); protected InetAddress getRequestingSite (); protected String getRequestingPrompt (); protected String getDefaultUserName ();

  20. Javax.mail.Authenticator and PasswordAuthentication • Fully functional Authenticator: Import javax.mail. *; Import javax.swing. *; Public class MyAuthenticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication (); { string password = JOptionPane.showInputDialog ( “Connecting to” + getRequestingProtocol() + “mail service on host” + getRequestingSite() + “, port” + getRequestingPort() + “as user” + getDefaultUserName () + “.\n” + getRequestingPrompt (); if (password == null) return null; else return new PasswordAuthentication (getDefaultUsername(), password); } }

  21. Javax.mail.Message <interface> Java.mail.part Javax.mail.multipart Javax.mail.Message Javax.mail.Bodypart <interface> Javax.mail.internet.Mimepart Javax.mail.internet.MimeMultipart Java.mail.internet.MimeBodypart Javax.mail.internet.MimeMessage

  22. Javax.mail.MessageConstructing a Message • Two most common ways for a Message implementation to be constructed: • MimeMessage (Session session); //Constructs a new and empty (of headers, content, and flags) MimeMessage in the specified session. • Message reply (boolean replyToAll); //Returns a new Message with headers suitable to be used as a reply to this message. The subject is automatically prefixed with the string “Re:”.

  23. Javax.mail.MessageMassage Header • The source for an internet message: Message-ID: <…> Date: Mon, 29 May 2000 11:40:41 … From: jason@injectilo.org To: craigb@wrox.com Subject: … Mime-Version: 1.0 Content-Type: text/plain; charset=ascii Content-Transfer-Encoding: 7bit I have several contact with the outside world…

  24. Javax.mail.MessageMessage Headers • Original standard for messages is problemetic in sending arbitrarily sized binary attachments. • MIME (Multipurpose Internet Mail Extensions) extends the capabilities of Internet messages while maintaining compatibility with the previous standard. • JavaMail API exposes the headers as standard getters and setters. • In the most prevelent message formats, the documentation for the Message methods will often refer to the headers that are set or retrieved by its most common subclass, MimeMessage. The Message class, however, was designed as an abstract interface to any possible implementation.

  25. Javax.mail.MessageMessage Headers • The From: Header • Void setFrom (); //The no parameter form sets the From header to the address specified in the Session’s mail.user property or if not present, user.name. • Void setFrom (Address address); //Set the from header to the spedified address by passing an Address object. • Void addFrom (Address [] addresses); //If multiple address • Address[] getFrom (); //Implemented by a getter, returns an array of the Addresses in the From header.

  26. Javax.mail.MessageMessage Headers • The Reply-To: Header • Void setReplyTo (Address[] addresses); //Sets the Reply-To header to the specified addresses. These addresses are automatically set as recipients when constructing a message using the reply () method. • Address[] getReplyTo (); //Gets an array of addresses that replies should be sent to or null if this can not be determined. • The MimeMessage implementation checks for the existence of a Reply-To header first.

  27. Javax.mail.MessageMessage Headers The To:, Cc; and Bcc: Headers • To: normal recipients cc: carbon copied recipients Bcc: blind carbon copied recipients • Void setRecipient (Message.RecipientType type, Address address) Void setRecipients (Message.RecipientType type, Address[] addresses) // Set the To, Cc, or Bcc header to the specified address(es). • Void addRecipient (Message.RecipientType type, Address address) //Add the specified address to any of the existing To, Cc, or Bcc headers. • Address[] getRecipients (Message.RecipientType type) or Address[] getRecipients () // Return the addresses of the recipients.

  28. Javax.mail.MessageMessage Headers • The Subject: Header In Message class: void setSubject (string subject) string getSubject () • The Date: Header void setSentDate (Date date) Date getSentDate () Date getReceivedDate ()

  29. Javax.mail.MessageMessage Headers • Folder and Message Number • Messages that are persisted in some Store are organized into folders. Each message within a folder is temporarily assigned a unique (within the Folder) number to help identify it to the Store provider. • Folder getFolder (); //Gets the Folder that contains this Message or null if this is either a new or nested Message. • Int getMessageNumber (); //Returns the message number corresponding to this message.

  30. Javax.mail.MessageMessage Flags • Why Flags? • Not all providers support flagging messages but there is a mechanism by which a client can determine what flags can be set. Some advanced implementations make it possible to set user-defined flags (usually represented as arbitrary strings of the user or user agent’s choosing )on a message.

  31. Javax.mail.MessageMessage Flags • Inorder to support both the typical flagging of messages using the typical static final constants and the user defined flagging using strings, the JavaMail provides a fairly clever approch that centers on the Flags class: Outer class:Flags  acts like a container for these Flag instance as well as for arbitrary String instances. Inner class:Flag  Defines several static instances of itself to represent the standard set of flags.

  32. Javax.mail.MessageMessage Flags In Flag class: • Void add (flags.flag flag); //Add the specified system flag. • Void add (string flag); //Add the specified user flag. • Boolean contains (flags.flag flag); //Test for system flag (flag). • Boolean contains (string flag); //Test for user flag (flag). • Void remove (flags.flag flag); //… • Void remove (string flag); • Flag.flag[] getSystemFlags (); • String[] getUserFlags (); In Message class: • Void setFlag (flags.flag flag, boolean set); //Set or clear individual flag • Void setFlags (Flags flag, boolean set); //Set or clear all of the individual flags in specified flag object (inner class). • Some system flags: ANSWERED DELETED DRAFT FLAGGED RECENT SEEN USER • Please see details and more methods on Page 823.

  33. Javax.mail.Part • This defines the methods used for storing and retrieving the content of a message or part of one, as in Multipart and MimeMultipart classes. • It also defines the standard properties that both whole messages and body parts have in common.

  34. Javax.mail.PartActivation • JavaBeans Activation Framework (JAF) is a little known API. The JavaMail API is one of the few products that make use of the JAF. • What is the main purpose of JAF? • After the advent of the MIME extensions, JavaMail leverages the functionality provided by the JAF in order to provide a simple and consistent interface to any number of disparate data sources. Javax.activation.DataHandler class provides this interface. It is simply a convenient wrapper around some implementation of the javax.activation.DataSource interface. Two useful such implementations, javax.activation.FileDataSource and URLDataSource, are provided by part of the JAF.

  35. Javax.mail.PartActivation • DataSource and its encapsulating DataHandler can provide access to the raw bytes of a data type with their getInputStream (), and getOutputStream () methods. • The DataSource is responsible for providing the streams. • The Message implementation uses these streams to transmit and retrieve a part’s content, regardless of what type it really is.

  36. Javax.mail.PartActivation • A higher and more useful level of abstraction: getContent () in DataHandler. • Return an actual Java instance that can be immediately downcast to the appropriate Java class. • Can be used directly by programmers by invoking whatever methods available in that class. • If the MIME type for the content has a registered javax.activation.DataContentHandler implementation, an object specific to that type will be returned. Otherwise, in InputStream is returned.

  37. Javax.mail.PartContent • Void setDataHandler (javax.activation.DataHandler dh) //Set the part’s content to the specified DataHandler. • Javax.activation.DataHandler getDataHandler (); //Return the DataHandler for the content. • Void setContent (java.lang.object object, string type); //Set the content for this part based on the specified type. • Void setText (string text); //Set the content for this part to the specified string with a content type of ‘text/plain’. • Void setContent (multipart mp); //Set the content for this part to the specified Multipart object. The content will be set to multipart/mixed. • Java.lang.Object getContent (); //Return the content for this part, which can be downcast to an appropriate object based on the content type or InputStream if the content type does not have a registered DataContentHandler.

  38. Javax.mail.PartContent One simple example: • How to set a part’s content to some plain text: part.setDataHandler (new DataHandler (text, “text/plain”)); or part.setContent (text, “text/plain”); or part.setText (text); • Retrieving a part’s content always uses the getContent () method. How to retrieve the plain text as a string object: String text = (String) part.getContent ();

  39. Javax.mail.PartContent • If the part’s type were not registered content type, the resulting object would have been an InputStream that can be used to retrieve the raw bytes of the content. • Example: save unregistered content to disk so that the user can use a separate application to process the data: object content = part.getContent (); if (content instanceof InputStream) { InputStream is = (InputStream) content; OutputStream os = new FileOutputStream (“content”); int n; byte buffer[] = new byte [1024]; while ( ( n = is.read (buffer) ) > 0) { os.write(buffer, 0, n); } is.close (); }

  40. Javax.mail.PartPart Headers • The Part interface exposes the necessary functionality for setting and retrieving any imaginable header’s value. • Like the Message class, if the part is in a modifiable state, the following methods can modify the part’s headers: void addHeader (String headerName, string headerValue); void setHeader (String headerName, string headerValue); void removeHeader (string headerName); String[] getHeader (string headerName); java.util.Enumeration getAllHeaders (); java.util.Enumeration getMatchingHeaders (sting [] headernames); java.util.Enumeration getNonMatchingHeaders (sting [] headernames);

  41. Javax.mail.PartPart Headers • A part’s description, disposition, and file name can be specified using the following methods: void setDescription (string description); void setDisposition (string disposition); //User should use either one of the Part interface constrains, ATTACHMENT or INLINE. string getDisposition (); string setFilename (string filename); string getFilename (); • Several other methods: int getLineCount (); int getSize (); //Return the size of the part’s content in bytes. void writeTo (OutputStream os); //Write this part to the specified output stream.

  42. Javax.mail.Multipart and BodyPart • Multipart messages are composed of one or more body parts. • The abstract Multipart class defines the methods necessary for collecting these body parts. • Each component in a multipart message needs its own set of headers and content. Then BodyPart class needs the functionality exposed by the Part interface. • To, From, Date, Subject, etc, are specified at the message level, not on a part-by-part level.

  43. Javax.mail.Multipart and BodyPart Some relative methods: Void addBodyPart (BodyPart part); Void addBodyPart (BodyPart part, int index); Boolean removeBodyPart (BodyPart part); Void removeBodyPart (int index); Int getCount (); //Return the number of body parts comprising this multipart. BodyPart getBodyPart (int index); String getContentType (); Void setParent (Part parent); //set the parent part Part getParent ();

  44. Javax.mail.internet.MimePart • The MimePart interface extends Part with several MIME-specific methods including some that provide lower-level access to the message headers: • Void setText (string text, string charset) //Set the content for this part to the specified text and encode it using specified charset. • String getEncoding () //Return the value of the Content-Transfer-Encoding header. This header is appropriately set when saveChanged () is invoked on a message containing this part. • String getContentID () //Return the value of the Content-ID. • Void setContentLanguage (string[] languages) • Void setContentMD5 (string md5) //Set Content-MD5 header, to ensure that a part’s content has not been altered during transit.

  45. Javax.mail.internet.MimePart Some other methods: • String getHeader (string headerName, string delimiter) //Return all the values for a given header in a single string separated by the specified delimiter. • Enumeration getAllHeaderLines () //Return an enumeration of the raw header lines in the part. • Enumeration getMatchingHeaderLines (string[] names) • Enumeration getNonMatchingHeaderLines (string[] names)

  46. Javax.mail.internet.MimeMessage • MimeMessage class is the only Sun-provided concrete implementation of Message. • MimeMessage implements all of the abstract methods defined in Message as well as those defined in both Part and MimePart.

  47. Javax.mail.internet.MimeMessage • An example: complete application that opens a session, constructs a message, and outputs it to the screen: import java.io.*; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; public class MimeMessageExample { // starts here // create a new session instance; MimeMessage message = new MimeMessage (session); message.setFrom (new InternetAddress (jason@injektilo.org)); message.setRecipient (Message.RecipientType.To, new InternetAddress (craigo@wrox.com)); message.setSubject (“No mail at all”); string text = “I have several contact with the outside world\r\n”+”I have food so don’t worry\r\n”; message.setText (text); message.saveChanges (); message.writeTo(System.out); }

  48. Javax.mail.internet.MimeMultipart and MimeBodyPart • Like MimeMessage, MimeMultipart and MimeBodyPart are the concrete implementations that most clients will be using when constructing multipart messages. • MimeMultipart introduces some methods as: • void setSubType (string subtype); //Sets the subtype of this multipart to the specified string. This defaults to ‘mixed’. • BodyPart getBodypart (string contentID); //Returns the body part with the specified content ID or null if not found.

  49. Javax.mail.internet.MimeMultipart and MimeBodyPart • An example: how a MimeMuiltipart is constructed and given two MimeBodyParts (analogous to ‘attaching’ a file to a message): import java.io.* … // Import the same classes as previous one. public class MimeMultipartExample { //Start here //Create a new session instance. Message message = new MimeMessage (session); message.setFrom(new InternetAddress (“…@…”)); message.setRecipient (message.RecipientType.To, new InternetAddress (“…@…”)); message.setSubject (fileName); //Text part BodyPart bodyPart1 = new MimeBodyPart (); bodyPart1.setText (“…”); //File part BodyPart bodyPart2 = new MimeBodyPart (); FileDataSource fileDataSource = new FileDataSource (fileName); //set DataHandler and Filename for bodyPart2

  50. Javax.mail.internet.MimeMultipart and MimeBodyPart • Example continued: multipart multipart = new MimeMultipart (); multipart.addBodyPart (bodyPart1); multipart.addBodyPart (bodyPart2); message.setContent (multipart); message.saveChanges (); message.writeTo (system.out); } //End of the program.

More Related