20

Click here to load reader

Lecture11 b

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Lecture11 b

JavaMail API Fundamentals

Page 2: Lecture11 b

JavaMail Setup

Add JAR filesmail.jar and activation.jar to CLASSPATH, to jre/lib/ext

Included with Java 2 platform, Enterprise Edition

Page 3: Lecture11 b

Core Classes

SessionMessage / MimeMessageInternetAddressAuthenticatorTransportStore

Page 4: Lecture11 b

Session

Represents a mail session with serverUses Properties to get things like mail host

mail.transport.defaultmail.smtp.host

Get session - no constructor

Properties props = new Properties();props.put(“mail.transport.default”, “smtp”);props.put(“mail.smtp.host”, “mail.cs.wmich.edu”);Session session = Session.getInstance(props, null); // null for AuthenticatorSession session = Session.getDefaultInstance(props, null);

Page 5: Lecture11 b

Message / MimeMessage

Represents a mail messageMessage abstract classimplements PartMimeMessage is MIME style email messageimplements MimePart

Get message from sessionMimeMessage message = new MimeMessage(session);

Set partsmessage.setContent() / mimeMessage.setText()

Page 6: Lecture11 b

InternetAddress

RFC822 AddressCreate:

new InternetAddress(“[email protected]");new InternetAddress(“[email protected] ", “Bill Someone");

For To, From, CC, BCCmessage.setFrom(address)message.addRecipient(type, address)Types

Message.RecipientType.TOMessage.RecipientType.CCMessage.RecipientType.BCC

Page 7: Lecture11 b

Authenticator

Permit mechanism to prompt for username and password

javax.mail.Authenticator != java.net.AuthenticatorExtend AuthenticatorOverride:public PasswordAuthentication getPasswordAuthentication(){

String username, password; // Then get them ...return new PasswordAuthentication(username, password);

}

Page 8: Lecture11 b

Transport

Message transport mechanismGet transport for session

Transport transport = session.getTransport("smtp");Connect

transport.connect(host, username, password);Act - repeat if necessary

transport.sendMessage(message, message.getAllRecipients());

Donetransport.close();

Page 9: Lecture11 b

Sending Mail

Need a working SMTP serverCan be written in Java using JavaMailAPI need from/to addresses, but don’t need to be valid, unless SMTP server includes some form of verification

Page 10: Lecture11 b

Sending Mail

import java.util.Properties;import javax.mail.*;import javax.mail.internet.*;

public class MailExample {public static void main (String args[]) throws Exception {String host = args[0];String from = args[1];String to = args[2];

// Get system propertiesProperties props = System.getProperties();

// Setup mail serverprops.put("mail.smtp.host", host);

Page 11: Lecture11 b

Sending Mail (contd.)

// Get sessionSession session = Session.getInstance(props, null);

// Define messageMimeMessage message = new MimeMessage(session);message.setFrom(new InternetAddress(from));message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

message.setSubject(“Test E-mail");message.setText(“Hello World!");

// Send messageTransport.send(message);

}}

Page 12: Lecture11 b

Getting Mail

There are mailbox store providers available (POP3 and IMAP).

Page 13: Lecture11 b

Getting Mail

import java.io.*;import java.util.Properties;import javax.mail.*;import javax.mail.internet.*;public class GetMessageExample {public static void main (String args[]) throws Exception {String host = args[0];String username = args[1];String password = args[2];

// Create empty propertiesProperties props = new Properties();

// Get sessionSession session = Session.getInstance(props, null);

Page 14: Lecture11 b

Getting Mail (contd.)

// Get the storeStore store = session.getStore("pop3");store.connect(host, username, password);

// Get folderFolder folder = store.getFolder("INBOX");folder.open(Folder.READ_ONLY);

BufferedReader reader = new BufferedReader (new InputStreamReader(System.in));

// Get directoryMessage message[] = folder.getMessages();for (int i=0, n=message.length; i<n; i++) {

Page 15: Lecture11 b

Getting Mail (contd.)

System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject());

System.out.println("Do you want to read message? [YES to read/QUIT to end]");String line = reader.readLine();if ("YES".equals(line)) {message[i].writeTo(System.out);

} else if ("QUIT".equals(line)) {break;

}}// Close connection folder.close(false);store.close();

}}

Page 16: Lecture11 b

Authenticator Usage

Put host in propertiesProperties props = new Properties();props.put("mail.host", host);

Setup authentication, get sessionAuthenticator auth = new PopupAuthenticator();Session session = Session.getInstance(props, auth);

Get the storeStore store = session.getStore("pop3");store.connect();

Page 17: Lecture11 b

Sending Attachments

Each attachment goes into a MimeBodyPart

DataHandler deals with reading in contents

Provide it with a URLDataSource or FileDataSource.

Page 18: Lecture11 b

Sending Attachments

// create mime message object and set the required parametersMimeMessage message = createMessage(to, cc, subject);

// create the message part MimeBodyPart messageBodyPart = new MimeBodyPart();

//fill messagemessageBodyPart.setText(msg);

Multipart multipart = new MimeMultipart();multipart.addBodyPart(messageBodyPart);

// fill the array of files to be attachedFile [] attachments = { .... }

Page 19: Lecture11 b

Sending Attachments (Contd.)

for( int i = 0; i < attachments.length; i++ ) {messageBodyPart = new MimeBodyPart();FileDataSource fileDataSource =new FileDataSource(attachments[i]);messageBodyPart.setDataHandler(new DataHandler(fileDataSource));messageBodyPart.setFileName(attachments[i].getName());multipart.addBodyPart(messageBodyPart);

}// add the Multipart to the messagemessage.setContent(multipart);

// SEND THE MESSAGETransport.send(message);

Page 20: Lecture11 b

Notification Events

Transport/Store/Folder.addConnectionListener()open, closed, disconnected

Folder.addFolderListener()created, deleted, renamed

Folder.addMessageCountListener()Find out when new messages are received

Folder.addMessageChangeListenerchanged

Store.addStoreListenernotification

Transport.addTransportListenermessage delivered, not delivered, partially delivered