• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
Lecture11 b
 

Lecture11 b

on

  • 396 views

 

Statistics

Views

Total Views
396
Views on SlideShare
396
Embed Views
0

Actions

Likes
0
Downloads
1
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    Lecture11 b Lecture11 b Presentation Transcript

    • JavaMail APIFundamentals
    • JavaMail Setup Add JAR files mail.jar and activation.jar to CLASSPATH, to jre/lib/ext Included with Java 2 platform, Enterprise Edition
    • Core Classes Session Message / MimeMessage InternetAddress Authenticator Transport Store
    • Session Represents a mail session with server Uses Properties to get things like mail host mail.transport.default mail.smtp.host Get session - no constructorProperties 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);
    • Message / MimeMessage Represents a mail message Message abstract class implements Part MimeMessage is MIME style email message implements MimePart Get message from session MimeMessage message = new MimeMessage(session); Set parts message.setContent() / mimeMessage.setText()
    • InternetAddress RFC822 Address Create: new InternetAddress(“BillSomebody@wmich.edu"); new InternetAddress(“BillSomebody@wmich.edu ", “Bill Someone"); For To, From, CC, BCC message.setFrom(address) message.addRecipient(type, address) Types Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC
    • Authenticator Permit mechanism to prompt for username and password javax.mail.Authenticator != java.net.Authenticator Extend Authenticator Override: public PasswordAuthentication getPasswordAuthentication() { String username, password; // Then get them ... return new PasswordAuthentication(username, password); }
    • Transport Message transport mechanism Get transport for session Transport transport = session.getTransport("smtp"); Connect transport.connect(host, username, password); Act - repeat if necessary transport.sendMessage(message, message.getAllRecipients()); Done transport.close();
    • Sending Mail Need a working SMTP server Can be written in Java using JavaMail API need from/to addresses, but don’t need to be valid, unless SMTP server includes some form of verification
    • Sending Mailimport 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 properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host);
    • Sending Mail (contd.) // Get session Session session = Session.getInstance(props, null); // Define message MimeMessage 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 message Transport.send(message); }}
    • Getting Mail There are mailbox store providers available (POP3 and IMAP).
    • Getting Mailimport 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 properties Properties props = new Properties(); // Get session Session session = Session.getInstance(props, null);
    • Getting Mail (contd.) // Get the store Store store = session.getStore("pop3"); store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); BufferedReader reader = new BufferedReader ( new InputStreamReader(System.in)); // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; i<n; i++) {
    • 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(); }}
    • Authenticator Usage Put host in properties Properties props = new Properties(); props.put("mail.host", host); Setup authentication, get session Authenticator auth = new PopupAuthenticator(); Session session = Session.getInstance(props, auth); Get the store Store store = session.getStore("pop3"); store.connect();
    • Sending Attachments Each attachment goes into a MimeBodyPart DataHandler deals with reading in contents Provide it with a URLDataSource or FileDataSource.
    • Sending Attachments// create mime message object and set the required parametersMimeMessage message = createMessage(to, cc, subject);// create the message partMimeBodyPart messageBodyPart = new MimeBodyPart();//fill messagemessageBodyPart.setText(msg);Multipart multipart = new MimeMultipart();multipart.addBodyPart(messageBodyPart);// fill the array of files to be attachedFile [] attachments = { .... }
    • 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);
    • Notification Events Transport/Store/Folder.addConnectionListener() open, closed, disconnected Folder.addFolderListener() created, deleted, renamed Folder.addMessageCountListener() Find out when new messages are received Folder.addMessageChangeListener changed Store.addStoreListener notification Transport.addTransportListener message delivered, not delivered, partially delivered