Lecture11 b


Published on

  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Lecture11 b

  1. 1. JavaMail APIFundamentals
  2. 2. JavaMail Setup Add JAR files mail.jar and activation.jar to CLASSPATH, to jre/lib/ext Included with Java 2 platform, Enterprise Edition
  3. 3. Core Classes Session Message / MimeMessage InternetAddress Authenticator Transport Store
  4. 4. 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);
  5. 5. 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()
  6. 6. 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
  7. 7. 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); }
  8. 8. 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();
  9. 9. 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
  10. 10. 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);
  11. 11. 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); }}
  12. 12. Getting Mail There are mailbox store providers available (POP3 and IMAP).
  13. 13. 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);
  14. 14. 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++) {
  15. 15. 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(); }}
  16. 16. 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();
  17. 17. Sending Attachments Each attachment goes into a MimeBodyPart DataHandler deals with reading in contents Provide it with a URLDataSource or FileDataSource.
  18. 18. 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 = { .... }
  19. 19. 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);
  20. 20. 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