1 / 50

In Lacture CSS-441 Advanced Programming using JAVA EE

In Lacture CSS-441 Advanced Programming using JAVA EE. Topic : JavaMail API Kaster Nurmukan. Agenda. Overview of JavaMail API Javax.mail.Session Javax.mail.Authenticator and PasswordAuthentication Javax.mail.Message Javax.mail.Part Javax.mail.Multipart and BodyPart

mhurlburt
Download Presentation

In Lacture CSS-441 Advanced Programming using JAVA EE

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. In LactureCSS-441Advanced Programming using JAVA EE Topic : JavaMail API Kaster Nurmukan

  2. Agenda • Overview of JavaMail API • Javax.mail.Session • Javax.mail.Authenticator and PasswordAuthentication • Javax.mail.Message • Javax.mail.Part • Javax.mail.Multipart and BodyPart • Javax.mail.internet.MimePart • javax.mail.Service • javax.mail.Transport

  3. 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

  4. 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.

  5. 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.

  6. 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.

  7. 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.

  8. 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);

  9. 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).

  10. 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.

  11. 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.

  12. 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 ();

  13. 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); } }

  14. 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

  15. 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:”.

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

  17. 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.

  18. 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.

  19. 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.

  20. 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.

  21. 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 ()

  22. 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.

  23. 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.

  24. 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.

  25. 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

  26. 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.

  27. 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.

  28. 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.

  29. 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.

  30. 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.

  31. 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 ();

  32. 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 (); }

  33. 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);

  34. 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.

  35. 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.

  36. 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 ();

  37. 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.

  38. 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)

  39. 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.

  40. 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); }

  41. 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.

  42. 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

  43. 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.

  44. Java.mail.Service • JavaMail API provides an abstraction for two types of services that sessions can create, Transports and Stores. The behavior common to both was extracted out into an even higher abstraction, the Service. • Behavior common to Transport and Store: • Require that a connection be established before messages can be sent or retrieved . • Support some optional authentication mechanism. • Services can optionally be identified by a URLName, e.g, a URLName designating a user’s POP3 account may look like: • pop3://username:password@hostname:port. • The URLName class represents a string that includes whatever information necessary in order to make a connection to some server.

  45. Java.mail.Service • Relative methods: • URLName getURLName() • Void connect () //Connect to the service using any suitably available default values for the host, port, and user. • Void connect (string host, string user, string password) //Using specified user and password for authentication. • Boolean isConnected () • Void close ()

  46. Javax.mail.Transport • Sending a message is achieved using a Transport. Sun’s JavaMail implementation comes with a fully functional SMTP transport that could be the only transport provider we need. • Transport class contains two static methods that make sending a message simple: • Static Transport.send (Message message) //Send the message using an appropriate transport for each of the message’s recipients’ address type. • Static Transport.send (Message message, Address[] recipients) // Ignore the message’s recipients and instead sending it to the specified recipients.

  47. Javax.mail.Transport • An example capable of sending a message to any user on the internet: • import java.util.*; • import java.mail.*; • import javax.mail.internet.*; • public class TransportSendExample { //Start here • // Initialize smtpHost, fromAddress, toAddress. • Properties properties = system.getProperties (); • properties.put (“mail.smtp.host”, smtpHost); • Session session = Session.getInstance (properties, null); • MimeMessage message = new MimeMessage (session); • //Set From and Recipients for message as we did in the previous example • message.setSubject (“Javemail example”); • message.setText (“…”); • Transport.send (message); }

  48. Javax.mail.Transport • Five different means by which the correct transport can be constructed and returned to the user: • Transport getTransport () // Return a transport that implements the protocol specified in the session’s mail.transport protocol property. • Transport getTransport (string protocol) // Return a transport implemented by the specified protocol. • Transport getTransport (Address address) // Return a transport capable of sending a message to the specified address type. • Transport getTransport (URLName url) //Return a transport that implements the protocol as found in the ‘scheme’ part of the specified URL name. • Transport getTransport (Provider provider) //Return a transport implemented by the specified provider.

  49. Reference • http://www.oracle.com

  50. Q&A

More Related