Java Mail Electronic Mail Concepts Java Mail Classes

  • Slides: 60
Download presentation
Java. Mail • • Electronic Mail Concepts Java. Mail Classes Examples of Sending Java.

Java. Mail • • Electronic Mail Concepts Java. Mail Classes Examples of Sending Java. Mail Java. Beans Activation Framework Multi-part Messages Example of Sending Attachments Other Java. Mail Classes Installing Java. Mail

Some Key Terms • Protocol: An agreed upon format for transmitting data between two

Some Key Terms • Protocol: An agreed upon format for transmitting data between two devices, including 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 • Content – Headers – Body Address:

Parts of an E-Mail Message • Envelope • Content – Headers – Body Address: user@host. network mm 6@andrew. cmu. edu

Envelope • Used by MTA to deliver messages • Contains source and destination addresses

Envelope • Used by MTA to deliver messages • Contains source and destination addresses • Example: MAIL From: mm 6@andrew. cmu. edu RCPT To: dmedvan@andrew. cmu. edu

Headers • Used by user-agent to describe message • Written in ASCII text •

Headers • Used by user-agent to describe message • Written in ASCII text • Each field contains a name followed 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

Common Headers • • • From Reply-To Date To CC Subject

Types of Message Bodies • One or more lines of NVT ASCII (7 -bit

Types of Message Bodies • One or more lines of NVT ASCII (7 -bit variant) text representing actual message • Multipurpose Internet Mail Extension (MIME): Common representation for emails sent in binary (attachments, embedded graphics, or non-ASCII characters)

MIME Content-Type Header most used MIME-specific header Examples • Text • Multipart • Message

MIME Content-Type Header most used MIME-specific header Examples • Text • Multipart • Message • Application • Image • Audio • Video

E-mail Protocols • Message Store Protocols: Read messages from a server – Internet Message

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 folder • Does

Disadvantages of POP • Only permits access to a single mail folder • 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 raddist. rad. com/networks/1998/smtp. htm

SMTP raddist. rad. com/networks/1998/smtp. htm

Overview of SMTP • Transfers mail from host-to-host over TCP, port 25 • Sends

Overview of SMTP • Transfers mail from host-to-host over TCP, port 25 • Sends commands in ASCII, terminated by newlines • Transmits requests and responses asymmetrically 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

Receiver-SMTP Responses • Sender-SMTP awaits reply to each message before progressing • SMTP supports spooling: message is placed on queue 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

SMTP Process • Sender-SMTP establishes transmission channel with a receiver-SMTP • Sender-SMTP transmits a MAIL command which identifies the sender • Receiver-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: Smith@Alpha. ARPA R: 250 OK Code 250

Example of SMTP Procedure S: MAIL FROM: Smith@Alpha. ARPA R: 250 OK Code 250 means everything is OK S: RCPT TO: Jones @Beta. ARPA R: 250 DOESN’T NEED TO SAY OK SINCE 3 DIGIT CODE IS KEY S: RCPT TO: Green@Beta. ARPA R: 550 No such user here S: R: S: S: S: R: DATA 354 Start mail input; end with <CRLF> Random content… More randome content <CRLF> 250 OK Couldn’t send message to Green@Beta. ARPA www. freesoft. org/CIE/RFC/821/4. htm

Java. util. Properties Class • Extends Hash. Map (basically another collection) • Designed to

Java. util. Properties Class • Extends Hash. Map (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 Hash. Map methods for handling Objects, use of the following is recommended to ensure that it contains Strings: – public Object set. Property(String key, String value) – public String get. Property(String key)

Classes to Send E-mail • Address: Abstract class representing an address • Message: Abstract

Classes to Send E-mail • Address: Abstract class representing an address • Message: Abstract class representing a message • Transport: Object representing a transport protocol that allows e-mail messages to be sent, implemented by a specific protocol • Session: Provides an interface between the email client and the network, supporting the creation of and access to Store and Transport objects

Message Representation

Message Representation

Javax. mail. Session • Class representing an individual mail session • Manages configuration of

Javax. mail. Session • Class 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 get. Default. Instance(Properties prop)

Session Properties Used to Send Mail at CMU

Session Properties Used to Send Mail at CMU

Javax. Mail. Transport • Abstract class modeling a message Transport • By using Session

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

Instantiating a Transport • Factory Methods of Session object public Transport get. Transport() public

Instantiating a Transport • Factory Methods of Session object public Transport get. Transport() public Transport get. Transport(String protocol) Uses Transport protocol in Session properties • Sending a Message method: public void save. Changes() Transport method: public void send. Message (Message msg, Address[] addresses) If you do not save a message before calling send. Message(), it will not work

Using Static send() Methods • Eliminates the need to instantiate a Transport object •

Using Static send() Methods • Eliminates the need to instantiate a Transport object • Eliminates the need to call the save. Message() method, since the static send() methods of Transport do that automatically – – public static send(Message msg) public static send(Message msg, Address[] addresses)

Address • Abstract class representing any electronic address • Most common implementation is for

Address • Abstract class representing any electronic address • Most common implementation is for e-mail addresses: javax. mail. internet. Internet. Address

Internet. Address Key Fields • String address: Represents the e-mail address • String personal:

Internet. Address Key Fields • String address: Represents the e-mail address • String personal: Represents the name of the addressee <mm 6@andrew. cmu. edu Michael Mc. Carthy>

Constructors • Internet. Address(String address) Internet. Address ia = new Internet. Address(“mm 6@andrew. cmu.

Constructors • Internet. Address(String address) Internet. Address ia = new Internet. Address(“mm 6@andrew. cmu. edu”); • Internet. Address(String address, String personal) Internet. Address ia = new Internet. Address(“mm 6@andrew. cmu. edu”, “Mike Mc. Carthy”);

Additional Factory Method static Internet. Address[] parse(String list. Of. Addresses, boolean strict) throws Address.

Additional Factory Method static Internet. Address[] parse(String list. Of. Addresses, boolean strict) throws Address. Exception • • • Static method Returns an array of Internet. Addresses list. Of. Addresses is a comma or space delimited list of e-mail addresses If strict is true, space delimited is prohibited Address. Exception indicates parsing failed Internet. Address. parse(“mm 6@andrew. cmu. edu, dmedvan@andrew. cmu. edu", false));

Standard Accessors and Mutators • • public void set. Address(String) public void set. Personal(String)

Standard Accessors and Mutators • • public void set. Address(String) public void set. Personal(String) public String get. Personal() public String get. Address()

E-Mail Message Classes • javax. mail. Message: Abstract class representing an e-mail message •

E-Mail Message Classes • javax. mail. Message: Abstract class representing an e-mail message • javax. mail. Part: Interface implemented by Message class defining properties and content of mail messages • Javax. mail. internet. Mime. Message: – Extends Message class and provides functionality to produce MIME messages – Most common constructor: Mime. Message(Session session)

Message. Recipient. Type • Innerclass of Message • Possible values: – TO – CC

Message. Recipient. Type • Innerclass of Message • Possible values: – TO – CC – BCC – NEWSGROUPS

Mime. Message Header Methods Setting Recipients • public void set. Recipient(Message. Recipient. Type type,

Mime. Message Header Methods Setting Recipients • public void set. Recipient(Message. Recipient. Type type, Address address) • public void set. Recipients(Message. Recipient. Type type, Address[] addresses) Adding Additional Recipients • public void add. Recipient(Message. Recipient. Type type, Address address) • public void addrecipients(Message. Recipient. Type type, Address[] addresses) Getting Recipients • public Address[] get. Recipients(Message. Recipient. Type type) • public Address[] get. All. Recipients()

Setting From Header • public void set. From() Sets from to default from property

Setting From Header • public void set. From() Sets from to default from property specified in Session properties • public void set. From(Address address) • Public void add. From(Address[] addresses) Adds one or more addresses to those already listed in the from header Getting From Header public Address[] get. From() Reply-To Header • public void set. Reply. To(Address[] addresses) • public Address[] get. Reply. To() Note that several methods use arrays of Addresses

Subject Header • public void set. Subject(String subject) • public String get. Subject() Sent

Subject Header • public void set. Subject(String subject) • public String get. Subject() Sent Date Header • public void set. Sent. Date(Date date) • public Date get. Sent. Date()

Content of a Single-Part Message • public void set. Text(String text) Defaults to ASCII

Content of a Single-Part Message • public void set. Text(String text) Defaults to ASCII • public void set. Text(String text, String charset) Used for non-ASCII messages or to improve performance if there is a lot of text

Example 1: Message. Send. java Sends an e-mail message from one person to another

Example 1: Message. Send. java Sends an e-mail message from one person to another import java. io. *; E-mail address class import java. net. Inet. Address; import java. util. Properties; import java. util. Date; import javax. mail. *; import javax. mail. internet. *; Properties class Directory containing abstract mail classes Internet e-mail classes

create. Session() public Session create. Session() { Gets the default system properties Properties p

create. Session() public Session create. Session() { Gets the default system properties Properties p = System. get. Properties(); Sets the transport protocol to SMTP and sets the appropriate SMTP host for CMU p. set. Property("mail. transport. protocol", "smtp"); p. set. Property("mail. smtp. host", “cyrus. andrew. cmu. edu");

Sets the store protocol to IMAP and sets the appropriate SMTP host for CMU

Sets the store protocol to IMAP and sets the appropriate SMTP host for CMU (not really needed unless the application will read e-mail) p. set. Property("mail. store. protocol", "imap"); p. set. Property("mail. imap. host", "cyrus. andrew. cmu. edu"); Session sess = Session. get. Default. Instance(p); return sess; } Instantiates a session using the new properties object

create. Message() public Message create. Message(Session sess) throws Messaging. Exception{ Base exception class for

create. Message() public Message create. Message(Session sess) throws Messaging. Exception{ Base exception class for Internet mail Message mess = new Mime. Message(sess); Default Constructor for a Mime. Message

mess. set. From(new Internet. Address("mm 6@andrew. cmu. edu")); set. Recipients(Message. Recipient. Type type, String

mess. set. From(new Internet. Address("mm 6@andrew. cmu. edu")); set. Recipients(Message. Recipient. Type type, String address) mess. set. Recipients(Message. Recipient. Type. TO, Internet. Address. parse("bob@andrew. cmu. edu", false)); mess. set. Subject("Test"); mess. set. Text("This is a test of Java. Mail's functionality. "); mess. set. Sent. Date(new Date()); return mess; }

main() public static void main(String[] args) { Message. Send send = new Message. Send();

main() public static void main(String[] args) { Message. Send send = new Message. Send(); Session sess = send. create. Session(); try { Message mess = send. create. Message(sess); Transport. send(mess); } A static method of the Transport class saves and sends a message catch(Messaging. Exception e) { System. out. println("Messaging Exception: "+e); } }

Example 2: Message. Send. To. Many Sends a message to a group of addresses

Example 2: Message. Send. To. Many Sends a message to a group of addresses import java. io. *; import java. net. Inet. Address; import java. util. Properties; import java. util. Date; import javax. mail. *; import javax. mail. internet. *; Almost everything is the same public class Message. Send. To. Each { public Session create. Session() { Properties p = System. get. Properties(); p. set. Property("mail. transport. protocol", "smtp"); p. set. Property("mail. smtp. host", “cyrus. andrew. cmu. edu"); p. set. Property("mail. store. protocol", "imap"); p. set. Property("mail. imap. host", "cyrus. andrew. cmu. edu"); Session sess = Session. get. Default. Instance(p); return sess; }

create. Message() public Message create. Message(Session sess)throws Messaging. Exception, Unsupported. Encoding. Exception { Message

create. Message() public Message create. Message(Session sess)throws Messaging. Exception, Unsupported. Encoding. Exception { Message mess = new Mime. Message(sess); Internet. Address[] recip = new Internet. Address[6]; Internet. Address[] reply = new Internet. Address[1]; Note the additional exception being thrown reply [0] = new Internet. Address("dmedvan@andrew. cmu. edu“, “Danielle Medvan”); This constructor of Internet. Address throws an Unsupported. Encoding. Exception if the email software does not support the character encoding in which the name is provided

recip[0]= new Internet. Address("garya@andrew. cmu. edu", "Gary"); recip[1]= new Internet. Address(“wtzuanta@andrew. cmu. edu”, “Tzuan-Ta");

recip[0]= new Internet. Address("garya@andrew. cmu. edu", "Gary"); recip[1]= new Internet. Address(“wtzuanta@andrew. cmu. edu”, “Tzuan-Ta"); recip[2]= new Internet. Address(“romoff@andrew. cmu. edu”, “Rebecca"); recip[3]= new Internet. Address(“marks 215@home. com”, “Mark"); recip[4]= new Internet. Address(“ginas@andrew. cmu. edu”, “Gina"); recip[5]= new Internet. Address(“cameronw@andrew. cmu. edu”, “Cameron"); mess. set. From(new Internet. Address("mm 6@andrew. cmu. edu"));

mess. set. Reply. To(reply); The “reply-to” address is set with set. Reply. To(Address[] addresses)

mess. set. Reply. To(reply); The “reply-to” address is set with set. Reply. To(Address[] addresses) mess. set. Recipients(Message. Recipient. Type. TO, recip); We saw the method to set a single recipient. Now we see the method to set multiple recipients mess. set. Subject("Test"); mess. set. Text("This is a test of Java. Mail's functionality. "); mess. set. Sent. Date(new Date()); return mess; }

Same main() public static void main(String[] args) { Message. Send. To. Many send =

Same main() public static void main(String[] args) { Message. Send. To. Many send = new Message. Send. To. Many(); Session sess = send. create. Session(); try { Message mess = send. create. Message(sess); Transport. send(mess); } catch(Messaging. Exception e) { System. out. println("Messaging Exception: "+e); } }

Java. Bean Activation Framework (JAF) • In multi-part messages, e-mail client needs to handle

Java. Bean Activation Framework (JAF) • In multi-part messages, e-mail client needs to handle a variety of file types with a consistent interface • JAF classes initialize appropriate beans • Used by Java. Mail clients to interact with messages – – Determine content type Discover commands supported on that content type Display messages Access data to enable execution of commands

Multi. Part Representation

Multi. Part Representation

javax. Activation. Data. Source • Interface that allows access to file type and to

javax. Activation. Data. Source • Interface that allows access to file type and to streams that can manipulate the file • public String get. Content. Type() returns the name of the MIME file type • Implemented by javax. Activation. File. Data. Source • Used by Java. Mail to create and retrieve e-mail attachments – Constructors • File. Data. Source(File file) • File. Data. Source(String filename)

javax. Activation. Data. Handler • Wrapper for Data. Source objects so that the user

javax. Activation. Data. Handler • Wrapper for Data. Source objects so that the user does not need to manipulate the bytes for each file • Constructors – Data. Handler(Data. Source ds) – Data. Handler(Object obj, String mime. Type) • Public Object get. Content() Returns the data as the object that represents its content type (ie runing this method on a text message returns a String)

javax. mail. Part Revisited • Allows manipulation of Data. Handlers – public void set.

javax. mail. Part Revisited • Allows manipulation of Data. Handlers – public void set. Data. Handler(Data. Handler dh) – Public Data. Handler(get. Data. Handler() • Other methods abstract user away from need to directly manipulate Data. Handler – public void set. Content(Object object, String content. Type) – public Object get. Content()

javax. mail. Mime. Body. Part • Implements the Part interface (indirectly through a few

javax. mail. Mime. Body. Part • 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 Data. Handler or streams • Key Methods – public void set. Text(String text): for text/plain content, makes a String into the message content – public void set. Data. Handler(Data. Handler dh) sets the content using a Data. Handler (which may be text or any other permitted content) – public void set. File. Name(String filename) sets the filename associated with the content, if the content represents a file

Javax. mail. Multipart • Container that holds multiple parts • Each part is indexed,

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 add. Body. Part(Body. Part part) – public void add. Body. Part(Body. Part part, int index) – public int get. Count() returns the number of Body. Part objects

Example 3: Send. Attachment. java Sends an e-mail address from one person to another

Example 3: Send. Attachment. java Sends an e-mail address from one person to another import java. io. *; import java. net. Inet. Address; import java. util. Properties; import java. util. Date; import javax. mail. *; import javax. mail. internet. *; Almost everything is the same public class Message. Send. To. Each { public Session create. Session() { Properties p = System. get. Properties(); p. set. Property("mail. transport. protocol", "smtp"); p. set. Property("mail. smtp. host", “cyrus. andrew. cmu. edu"); p. set. Property("mail. store. protocol", "imap"); p. set. Property("mail. imap. host", "cyrus. andrew. cmu. edu"); Session sess = Session. get. Default. Instance(p); return sess; }

create. Message() public Message create. Message(Session sess) throws Messaging. Exception{ Message mess = new

create. Message() public Message create. Message(Session sess) throws Messaging. Exception{ Message mess = new Mime. Message(sess); mess. set. From(new Internet. Address("mm 6@andrew. cmu. edu")); mess. set. Recipients(Message. Recipient. Type. TO, Internet. Address. parse(“bob@andrew. cmu. edu", false)); mess. set. Subject("Test"); Still the same mess. set. Sent. Date(new Date());

Instantiate a Mime. Body. Part to contain the text of the email message Mime.

Instantiate a Mime. Body. Part to contain the text of the email message Mime. Body. Part main. Message = new Mime. Body. Part(); main. Message. set. Text("This is a test of Java. Mail's functionality. "); Construct a File. Date. Source with the full path of the file it should contain (This will be the attachment) File. Data. Source source = new File. Data. Source("c: \autoexec. bat"); Mime. Body. Part attach = new Mime. Body. Part(); attach. set. Data. Handler(new Data. Handler(source)); attach. set. File. Name(source. get. Name()); Set the attachment’s file name to equal the name of the File. Data. Source Construct another Mime. Body. Part containing a new Data. Handler that contains the File. Data. Source

Multipart multi = new Mime. Multipart(); multi. add. Body. Part(main. Message); multi. add. Body.

Multipart multi = new Mime. Multipart(); multi. add. Body. Part(main. Message); multi. add. Body. Part(attach); mess. set. Content(multi); return mess; } Instantiate a Mime. Multipart Add the bodyparts (message and attachment) to the Mime. Multipart Assign the Mime. Multipart to be the content of the message

Same main() public static void main(String[] args) { Send. Attachment send = new Send.

Same main() public static void main(String[] args) { Send. Attachment send = new Send. Attachment(); Session sess = send. create. Session(); try { Message mess = send. create. Message(sess); Transport. send(mess); } catch(Messaging. Exception e) { System. out. println("Messaging Exception: "+e); } }

Other Java. Mail Classes • Store: Object representing database and access protocol for storing

Other Java. Mail Classes • Store: Object representing database and access protocol for storing and accessing messages and folders, implemented by a specific protocol (IMAP or POP 3) • Folder: Contains e-mail messages and subfolders and supports reading and deleting them • Mail. Event: Can be registered with event listeners to catch events generated by Transport, Store, and Folder objects (i. e. announce arrival of new e-mail) Note: Using Java. Mail in Netscape browsers requires you to download the Java Plug-in because of Netscape’s security restrictions

Installation Instructions Visit http: //java. sun. com/products/javamail 1. Download the Java. Mail API Implementation

Installation Instructions Visit http: //java. sun. com/products/javamail 1. Download the Java. Mail API Implementation Version 1. 3 ea 2. Download the Java. Beans Activation Framework 1. 0. 2 ea 3. Unzip both files. 4. Add the following files to your classpath: – mail. jar (Java. Mail) – activation. jar (JAF file)

For More Information • http: //raddist. rad. com/networks/1998/smtp/s mtp. htm • http: //www. freesoft.

For More Information • http: //raddist. rad. com/networks/1998/smtp/s mtp. htm • http: //www. freesoft. org/CIE • http: //cr. yp. to/smtp • Java Server Programming: J 2 EE Edition by Allamaraju et. al. , Wrox Publishing, © 2000