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

Slides:



Advertisements
Similar presentations
TOPIC : MIME (Multipurpose Internet Mail Extensions ) By: Cecilia Gomes COSC 541,DATA COMMUNICATION SYSTEMS & NETWORKS Instructor: Prof. Anvari (SEU)
Advertisements

Basic Communication on the Internet:
Ivan Maurits. Untuk mengirim menggunakan java anda harus memiliki JavaMail API dan Java Activation Framework (JAF) yang telah terinstall dalam komputer.
Topic : JavaMail API (1) Sending and Receiving s Kaster Nurmukan.
Basic Communication on the Internet: Integrated Browser Programs and Web-Based Services Tutorial 3.
1 Frameworks. 2 Framework Set of cooperating classes/interfaces –Structure essential mechanisms of a problem domain –Programmer can extend framework classes,
XP Browser and Basics1. XP Browser and Basics2 Learn about Web browser software and Web pages The Web is a collection of files that reside.
Chapter 29 Structure of Computer Names Domain Names Within an Organization The DNS Client-Server Model The DNS Server Hierarchy Resolving a Name Optimization.
J2EE JavaMail API Presented by Bartosz Sakowicz. Instalation Java Mail API: Java Activation Framework.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
TCP/IP Protocol Suite 1 Chapter 20 Upon completion you will be able to: Electronic Mail: SMTP, POP, and IMAP Understand four configurations of architecture.
JavaMail JavaMail Classes Sending a Message Using JavaMail (MessageSend.java) Sending a Message to Multiple Recipients (SendToMany.java) Installing JavaMail.
CPSC 441: FTP & SMTP1 Application Layer: FTP & Instructor: Carey Williamson Office: ICT Class.
Electronic Mail and SMTP
Chapter 30 Electronic Mail Representation & Transfer
Esimerkki: Sähköposti. Lappeenranta University of Technology / JP, PH, AH Electronic Mail Three major components: user agents mail servers simple mail.
CSCI 6962: Server-side Design and Programming Server Created .
Architecture of SMTP, POP, IMAP, MIME.
Introduction 1 Lecture 7 Application Layer (FTP, ) slides are modified from J. Kurose & K. Ross University of Nevada – Reno Computer Science & Engineering.
JAVA MAIL API. High level representation of the basic components of any mail system. The components are represented by abstract classes in the javax.mail.
Sending and Receiving s
Mail Server Fitri Setyorini. Content SMTP POP3 How mail server works IMAP.
» Explain the way that electronic mail ( ) works » Configure an client » Identify message components » Create and send messages.
Introduction 1-1 Chapter 2 FTP & Computer Networking: A Top Down Approach 6 th edition Jim Kurose, Keith Ross Addison-Wesley March 2012 IC322 Fall.
Electronic Mail (SMTP, POP, IMAP, MIME)
FALL 2005CSI 4118 – UNIVERSITY OF OTTAWA1 Part 4 Web technologies: HTTP, CGI, PHP,Java applets)
SMTP, POP3, IMAP.
1 Application Layer Lecture 5 Imran Ahmed University of Management & Technology.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Data Communications and Computer Networks Chapter 2 CS 3830 Lecture 9
CSE401N: Computer Networks Lecture-5 Electronic Mail S. M. Hasibul Haque Lecturer Dept. of CSE, BUET.
IT 424 Networks2 IT 424 Networks2 Ack.: Slides are adapted from the slides of the book: “Computer Networking” – J. Kurose, K. Ross Chapter 2: Application.
Intro to Computer Networks Bob Bradley The University of Tennessee at Martin.
Review: –How do we address “a network end-point”? –What services are provided by the Internet? –What is the network logical topology observed by a network.
Application Layer Protocols Simple Mail Transfer Protocol.
Computer Networking From LANs to WANs: Hardware, Software, and Security Chapter 12 Electronic Mail.
Application Protocols: ELECTRONIC MAIL (SMTP, POP) CSNB534 Semester 2, 2007/2008 Asma Shakil.
Electronic Mail Originally –Memo sent from one user to another Now –Memo sent to one or more mailboxes Mailbox –Destination point for messages.
A form of communication in which electronic messages are created and transferred between two or more devices connected to a network.
Telecooperation Technische Universität Darmstadt Copyrighted material; for TUD student use only Internet Standards: Julian Schröder-Bernhardi, Dirk.
1 Applications Electronic Mail. 2 Electronic Mail Many user applications use client-server architecture. Electronic mail client accepts mail.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Application Protocols: HTTP CSNB534 Semester 2, 2007/2008 Asma Shakil.
Simple Mail Transfer Protocol (SMTP)
XP New Perspectives on Browser and Basics Tutorial 1 1 Browser and Basics Tutorial 1.
An program As a simple example of socket programming we can implement a program that sends to a remote site As a simple example of socket.
Sending Topic 4, Chapters 9, 10 Network Programming Kansas State University at Salina.
1 Using Messages sent from machine to machine and stored for later reading. You will use a client to read –Type mail or pine in UNIX to read.
(or ?) Short for Electronic Mail The transmission of messages over networks.
The Internet 8th Edition Tutorial 2 Basic Communication on the Internet: .
What is and How Does it Work?  Electronic mail ( ) is the most popular use of the Internet. It is a fast and inexpensive way of sending messages.
File Transfer Protocol (FTP)
Topic : JavaMail API Kaster Nurmukan. Overview of JavaMail API Javax.mail.Session Javax.mail.Authenticator and PasswordAuthentication Javax.mail.Message.
Topics Sending an Multipart message Storing images Getting confirmation Session tracking using PHP Graphics Input Validators Cookies.
CS 3830 Day 9 Introduction 1-1. Announcements r Quiz #2 this Friday r Demo prog1 and prog2 together starting this Wednesday 2: Application Layer 2.
XP New Perspectives on The Internet, Sixth Edition— Comprehensive Tutorial 2 1 Evaluating an Program and a Web-Based Service Basic Communication.
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
CITA 310 Section 6 Providing Services (Textbook Chapter 8)
Slides based on Carey Williamson’s: FTP & SMTP1 File Transfer Protocol (FTP) r FTP client contacts FTP server at port 21, specifying TCP as transport protocol.
World Wide Web r Most Web pages consist of: m base HTML page, and m several referenced objects addressed by a URL r URL has two components: host name and.
COMP 431 Internet Services & Protocols
1 Kyung Hee University Chapter 22 Simple Mail Transfer Protocol (SMTP)
Simple Web Services. Internet Basics The Internet is based on a communication protocol named TCP (Transmission Control Protocol) TCP allows programs running.
Spring 2006 CPE : Application Layer_ 1 Special Topics in Computer Engineering Application layer: Some of these Slides are Based on Slides.
درس مهندسی اینترنت – مهدی عمادی مهندسی اینترنت برنامه‌نویسی در اینترنت 1 SMTP, FTP.
Networking Applications
Internet Business Associate v2.0
WEB SERVICES From Chapter 19, Distributed Systems
Chapter 7 Network Applications
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 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.Session Constructing 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.Session Constructing 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.Session Constructing 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.Session Session 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 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.Session Session 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 Java.mail.part Javax.mail.Message Javax.mail.internet.MimeMessage Javax.mail.internet.Mimepart Javax.mail.multipart Javax.mail.Bodypart Javax.mail.internet.Mim eMultipart Java.mail.internet.MimeBodypart

22 Javax.mail.Message Constructing 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.Message Massage Header The source for an internet message: Message-ID: Date: Mon, 29 May :40:41 … From: To: 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.Message Message 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.Message Message 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.Message Message 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.Message Message 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.Message Message 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.Message Message 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.Message Message 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.Message Message 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.Message Message 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.Part Activation 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.Part Activation 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.Part Activation A higher and more useful level of abstraction: getContent () in DataHandler. 1. Return an actual Java instance that can be immediately downcast to the appropriate Java class. 2. Can be used directly by programmers by invoking whatever methods available in that class. 3. 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.Part Content 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.Part Content 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.Part Content 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.Part Part 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.Part Part 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: 1. Void setText (string text, string charset) //Set the content for this part to the specified text and encode it using specified charset. 2. 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. 3. String getContentID () //Return the value of the Content-ID. 4. Void setContentLanguage (string[] languages) 5. 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 message.setRecipient (Message.RecipientType.To, new InternetAddress 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: 1. void setSubType (string subtype); //Sets the subtype of this multipart to the specified string. This defaults to ‘mixed’. 2. 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.

51 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: 1. Require that a connection be established before messages can be sent or retrieved. 2. 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: The URLName class represents a string that includes whatever information necessary in order to make a connection to some server.

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

53 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: 1. Static Transport.send (Message message) //Send the message using an appropriate transport for each of the message’s recipients’ address type. 2. Static Transport.send (Message message, Address[] recipients) // Ignore the message’s recipients and instead sending it to the specified recipients.

54Javax.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 (“Jav example”); message.setText (“…”); Transport.send (message); }

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

56 ~The End~ Questions?