SlideShare a Scribd company logo
JavaMail API Fundamentals John Zukowski - jaz@zukowski.net JZ Ventures, Inc.
Agenda Getting Started Core Classes Getting Mail Sending Mail Attachments Searching Q&A
Getting Started Without (Pre?) JavaMail With JavaMail http://java.sun.com/products/javamail/
Without JavaMail Read RFC 821 for SMTP http://www.cis.ohio-state.edu/htbin/rfc/rfc821.html Other RFC describe things like attachments RFC 822:  Text Messages, RFC 2045-7: MIME, RFC 1939: POP3, RFC 2060: IMAP, ... Open socket connection to port 25 HELO sending host MAIL FROM: sender email RCPT TO: recipient email DATA ... the email message... ... any number of lines ... . QUIT
SmtpClient import sun.net.smtp.SmtpClient;  import java.io.PrintStream; public class SmtpClientExample { public static void main (String args[]) throws Exception { String host = args[0]; String from = args[1]; String to = args[2]; SmtpClient smtp = new SmtpClient(host); smtp.from(from); smtp.to(to); PrintStream msg = smtp.startMessage(); msg.println("To: " + to); msg.println("Subject: Hello SmtpClient"); msg.println();  // blank line between headers and message msg.println("This is a test message."); smtp.closeServer(); } }
Without JavaMail Take 3 Just use a URL Open a mailto: URL Write to opened URLConnection Need to set mail.host System property Be sure to end lines with \r\n Don’t use println()
Mail Through URL import java.io.*; import java.net.*; public class MailTo { public static void main(String args[]) throws Exception { System.getProperties().put("mail.host", args[0]); URL url  = new URL("mailto:jaz@jguru.com"); URLConnection conn = url.openConnection(); PrintStream out = new  PrintStream(conn.getOutputStream(), true); out.print("From: jguru-fan@yourisp.com"+"\r\n"); out.print("Subject: Works Great!"+"\r\n"); out.print("Thanks!"+"\r\n"); out.close(); System.out.println("Message Sent"); } }
With JavaMail API Latest Version 1.2 December 5, 2000 release Sun includes IMAP, POP, and SMTP service providers Version 1.1.3 (2/22/2000) most popular one used Need to get JavaBeans Activation Framework http://java.sun.com/beans/glasgow/jaf.html See demo directory for many examples
JavaMail Setup Add JAR files to CLASSPATH, to jre/lib/ext Applets can use: javax.* Won’t work in Netscape though without Plug-in Will work in Internet Explorer / HotJava JavaMail mail.jar (280K) Separate JAR files available if only using parts Activation Framework activation.jar (45K)
JDK Requirements Works with JDK 1.1.6+ Works with Java 2 platform, Standard Edition, versions 1.2 / 1.3 Included with Java 2 platform, Enterprise Edition
Core Classes Session Message / MimeMessage InternetAddress Authenticator Transport
Session Represents a mail session Uses Properties to get things like mail host mail.host mail.smtp.host Get session - no constructor Session session = Session.getInstance(props, null); // null for Authenticator Session 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("jaz@zukowski.net"); new InternetAddress("jaz@zukowski.net ", "John Zukowski"); 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, but irrelevant Need from/to addresses, but don’t need to be valid, unless SMTP server includes some form of verification To run example: java MailExample smtp.mailserver from@from.com to@to.com
Hello World 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 properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host);
Hello World/2 // 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("Hello JavaMail"); message.setText("Welcome to JavaMail"); // Send message Transport.send(message); } }
Getting Mail POP3 provider doesn’t provide local data storage There are mailbox store providers available Need to get/install POP3 provider Part of JavaMail 1.2 release NOT part of basic JavaMail 1.1 API implementation
Reading Hello World 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 properties Properties props = new Properties(); // Get session Session session = Session.getInstance(props, null);
Reading Hello World/2 // Get the store Store store = session.getStore(&quot;pop3&quot;); store.connect(host, username, password); // Get folder Folder folder = store.getFolder(&quot;INBOX&quot;); 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++) {
Reading Hello World/3 System.out.println(i + &quot;: &quot; + message[i].getFrom()[0]  + &quot;\t&quot; + message[i].getSubject()); System.out.println(&quot;Do you want to read message? [YES to read/QUIT to end]&quot;); String line = reader.readLine(); if (&quot;YES&quot;.equals(line)) { message[i].writeTo(System.out); } else if (&quot;QUIT&quot;.equals(line)) { break; } } // Close connection  folder.close(false); store.close(); } }
Authenticator Usage Put host in properties Properties props = new Properties(); props.put(&quot;mail.host&quot;, host); Setup authentication, get session Authenticator auth = new PopupAuthenticator(); Session session = Session.getInstance(props, auth); Get the store Store store = session.getStore(&quot;pop3&quot;); store.connect();
Saving Messages To save copy locally: Get/create appropriate provider Knife - http://www.dog.net.uk/knife/ mimeMessage.writeTo(outputStream)
Replying Use Message.reply(boolean) Sets up message with proper headers boolean of true indicates reply to all vs. reply to sender only Does NOT setup message contents
Deleting Messages Set message flag to deleted: message.setFlag(Flags.Flag.DELETED, true); Be sure folder opened read-write: folder.open(Folder.READ_WRITE); Deleted when folder closed: folder.close(true);  // true = expunge Expunge / Permanently Deletes folder.expunge() NOT always implemented
Including Attachments Each attachment goes into a MimeBodyPart DataHandler deals with reading in contents Provide it with a DataSource Either URLDataSource or FileDataSource
Sending Attachments // create mime message object and set the required parameters MimeMessage message = createMessage(to, cc, subject); // create the message part  MimeBodyPart messageBodyPart = new MimeBodyPart(); //fill message messageBodyPart.setText(msg); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // fill the array of files to be attached File [] attachments = { .... }
Sending Attachments/2 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 message message.setContent(multipart); // SEND THE MESSAGE Transport.send(message);
Sending HTML Attachment Don’t use setText() Use setDataHandler() String htmlText = &quot;<H1>Hello</H1><H2>World</H2>&quot;; message.setContent(htmlText, &quot;text/html&quot;));
Including HTML Images Inline Specify Image source with cid: URL <IMG SRC=cid:23abc@pc27> Set Content-ID in header of image attachment part.setHeader(&quot;Content-ID&quot;,&quot;23abc@pc27&quot;); Complete example: http://www.jguru.com/jguru/faq/view.jsp?EID=97371
Getting Attachments from Client You want to create a web-based email system Your user wants to include file from their system as attachment Use an HTML Form Use Servlet to read stream Use MultipartRequest class from O’Reilly servlets book – www.servlets.com
HTML Form <FORM ENCTYPE=&quot;multipart/form-data&quot; method=post action=&quot;/myservlet&quot;>  <INPUT TYPE=&quot;file&quot; NAME=&quot;mptest&quot;> <INPUT TYPE=&quot;submit&quot; VALUE=&quot;upload&quot;> </FORM>
Getting Attachments For each part of Multipart, process part Attachments can be inline or not String disposition = part.getDisposition(); if (disposition.equals(Part.INLINE)) if (disposition.equals(Part.ATTACHMENT))
Save Attachments public static void handleMultipart(Multipart multipart)  throws MessagingException, IOException { for (int i=0, n=multipart.getCount(); i<n; i++) { handlePart(multipart.getBodyPart(i)); } } Following code doesn’t deal with Multipart in Multipart left as exercise for reader  
Save Attachments/2 public static void handlePart(Part part)  throws MessagingException, IOException { String disposition = part.getDisposition(); String contentType = part.getContentType(); if (disposition == null) { // When just body System.out.println(&quot;Null: &quot;  + contentType); // Check if plain if ((contentType.length() >= 10) &&  (contentType.toLowerCase().substring(0, 10).equals(&quot;text/plain&quot;))) { part.writeTo(System.out); } else { // Don't think this will happen System.out.println(&quot;Other body: &quot; + contentType); part.writeTo(System.out); }
Save Attachments/3 } else if (disposition.equals(Part.ATTACHMENT)) { System.out.println(&quot;Attachment: &quot; + part.getFileName() +  &quot; : &quot; + contentType); saveFile(part.getFileName(), part.getInputStream()); } else if (disposition.equals(Part.INLINE)) { System.out.println(&quot;Inline: &quot; + part.getFileName() +  &quot; : &quot; + contentType); saveFile(part.getFileName(), part.getInputStream()); } else {  // Should never happen System.out.println(&quot;Other: &quot; + disposition); } }
Debugging Trace commands sent session.setDebug(true)
New Mail Notification Events Add MessageCountListener to folder Find out when new messages are received Sleep then folder.getMessageCount() to get notification from IMAP server Not POP3 - Does not work when folder open
More Notification Events Transport/Store/Folder.addConnectionListener() open, closed, disconnected Folder.addFolderListener() created, deleted, renamed Folder.addMessageChangeListener changed Store.addStoreListener notification Transport.addTransportListener message delivered, not delivered, partially delivered
JavaMail Searching API includes support for searching for matching messages javax.mail.search package Build a SearchTerm Search: Message[] msgs = folder.search(st);
Building Up SearchTerm AND terms (class AndTerm) OR terms (class OrTerm) NOT terms (class NotTerm) SENT DATE terms (class SentDateTerm) CONTENT terms (class BodyTerm) HEADER terms (FromTerm / FromStringTerm, RecipientTerm / RecipientStringTerm, SubjectTerm, etc..)
Using SearchTerm Folder folder = store.getFolder(&quot;INBOX&quot;); SearchTerm st = new AndTerm(new SubjectTerm(&quot;ADV:&quot;), new BodyTerm(&quot;hello&quot;); Message[] msgs = folder.search(st);
S/MIME Includes email signing and encryption support Get a different provider Phaos S/MIME toolkit http://www.phaos.com/e_security/prod_smime.html JCSI http://security.dstc.edu.au/projects/java/release2.html
JavaMail with JSP Definitely doable with Java source scriptlets However, should limit amount of Java source in JSP pages Use JavaBeans that hide/simplify capabilities for Web designer Create / Get ImMailBean http://www.imessaging.com/html/immailbean.html Source Fourge http://sourceforge.net/project/?group_id=1282
JavaMail with NNTP You can use JavaMail with NNTP Need to get an NNTP provider http://www.dog.net.uk/knife/ To read newsgroups Store store = session.getStore(&quot;nntp&quot;); store.connect(host, username, password); Folder folder = store.getFolder(newsgroup); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages();
JavaMail is Free Sun’s reference implementation is completely free Sun’s License:  http://java.sun.com/products/javamail/LICENSE.txt Includes SMTP, IMAP, and POP3 providers
James Java Apache Mail Enterprise Server Pure Java-based mail server Supports Mailets Like servlets, but for extending mail server Add capabilities like mailing list support, filtering, translation, etc. http://java.apache.org/james/index.html
Miscellaneous Sun’s JavaMail FAQ http://java.sun.com/products/javamail/FAQ.html Mailing List http://archives.java.sun.com/archives/javamail-interest.html Get the JavaMail Source 1.1.2 source part of J2EE Sun Community Source Licensing http://www.sun.com/software/communitysource/j2ee/
Other Providers knife http://www.dog.net.uk/knife/ NNTP, POP3, mailbox file provider Project &quot;POPpers&quot; http://www2s.biglobe.ne.jp/~dat/java/project/poppers/index_en.html ICEMail Java-based Email Client http://www.icemail.org/
Questions & Answers Questions? Use the FAQs John Zukowski http://www.jguru.com http://java.about.com http://www.jguru.com/faq/JavaMail

More Related Content

PDF
Lecture11 b
PPT
香港六合彩 &raquo; SlideShare
PDF
Apache FTP Server Integration
PDF
Chat Room System using Java Swing
PPT
Corba by Example
PPTX
#5 (Remote Method Invocation)
PPT
Jsp/Servlet
PDF
Chat application in java using swing and socket programming.
Lecture11 b
香港六合彩 &raquo; SlideShare
Apache FTP Server Integration
Chat Room System using Java Swing
Corba by Example
#5 (Remote Method Invocation)
Jsp/Servlet
Chat application in java using swing and socket programming.

What's hot (20)

PDF
Examples from Pune meetup
PDF
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
PDF
8 Minutes On Rack
PDF
Python RESTful webservices with Python: Flask and Django solutions
PDF
PDF
OSGi Puzzlers
ODP
Java 7 Features and Enhancements
PDF
Java Programming - 08 java threading
PDF
PPTX
Network programming in java - PPT
PPTX
JEE.next()
PPTX
Flask restfulservices
PDF
Implementation of a state machine for a longrunning background task in androi...
PPT
Real time server
PPTX
java script
PDF
Rack Middleware
PDF
Threads, Queues, and More: Async Programming in iOS
PDF
Python Google Cloud Function with CORS
PDF
Flask patterns
Examples from Pune meetup
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
8 Minutes On Rack
Python RESTful webservices with Python: Flask and Django solutions
OSGi Puzzlers
Java 7 Features and Enhancements
Java Programming - 08 java threading
Network programming in java - PPT
JEE.next()
Flask restfulservices
Implementation of a state machine for a longrunning background task in androi...
Real time server
java script
Rack Middleware
Threads, Queues, and More: Async Programming in iOS
Python Google Cloud Function with CORS
Flask patterns
Ad

Viewers also liked (9)

PDF
Simplify360 culture code
PPTX
Java Sending mail
PDF
A Whole New Brain for Teachers
PDF
A Photo Reflection of Fab 8 NeuroELT Conference
PPT
Diseño de un codificador decimal bcd
PPT
J2EE - JSP-Servlet- Container - Components
PPT
Basic SEO Presentation
PPTX
Digital Marketing PPT
PPTX
Digital Marketing Overview
Simplify360 culture code
Java Sending mail
A Whole New Brain for Teachers
A Photo Reflection of Fab 8 NeuroELT Conference
Diseño de un codificador decimal bcd
J2EE - JSP-Servlet- Container - Components
Basic SEO Presentation
Digital Marketing PPT
Digital Marketing Overview
Ad

Similar to Baocao Web Tech Java Mail (20)

DOCX
JavaExamples
PPT
PDF
Hi, I need some one to help me with Design a client-server Chat so.pdf
PDF
Please include comments if at all possible Use a socket connection t.pdf
PPT
General Principles of Web Security
PDF
file-transfer-using-tcp.pdf
PPT
Spring Capitulo 05
PPT
Apache Utilities At Work V5
PDF
WebTalk - Implementing Web Services with a dedicated Java daemon
PDF
Need help on creating code using cart. The output has to show multip.pdf
PDF
Run rmi
PDF
C++ course start
DOCX
Lab manual cn-2012-13
PDF
4Developers: Dominik Przybysz- Message Brokers
PDF
Speed up your Web applications with HTML5 WebSockets
PPT
Socket Programming
PDF
Java networking programs socket based
PDF
MultiClient chatting berbasis gambar
PPTX
Servlets
PPT
Rapid java backend and api development for mobile devices
JavaExamples
Hi, I need some one to help me with Design a client-server Chat so.pdf
Please include comments if at all possible Use a socket connection t.pdf
General Principles of Web Security
file-transfer-using-tcp.pdf
Spring Capitulo 05
Apache Utilities At Work V5
WebTalk - Implementing Web Services with a dedicated Java daemon
Need help on creating code using cart. The output has to show multip.pdf
Run rmi
C++ course start
Lab manual cn-2012-13
4Developers: Dominik Przybysz- Message Brokers
Speed up your Web applications with HTML5 WebSockets
Socket Programming
Java networking programs socket based
MultiClient chatting berbasis gambar
Servlets
Rapid java backend and api development for mobile devices

Baocao Web Tech Java Mail

  • 1. JavaMail API Fundamentals John Zukowski - jaz@zukowski.net JZ Ventures, Inc.
  • 2. Agenda Getting Started Core Classes Getting Mail Sending Mail Attachments Searching Q&A
  • 3. Getting Started Without (Pre?) JavaMail With JavaMail http://java.sun.com/products/javamail/
  • 4. Without JavaMail Read RFC 821 for SMTP http://www.cis.ohio-state.edu/htbin/rfc/rfc821.html Other RFC describe things like attachments RFC 822: Text Messages, RFC 2045-7: MIME, RFC 1939: POP3, RFC 2060: IMAP, ... Open socket connection to port 25 HELO sending host MAIL FROM: sender email RCPT TO: recipient email DATA ... the email message... ... any number of lines ... . QUIT
  • 5. SmtpClient import sun.net.smtp.SmtpClient; import java.io.PrintStream; public class SmtpClientExample { public static void main (String args[]) throws Exception { String host = args[0]; String from = args[1]; String to = args[2]; SmtpClient smtp = new SmtpClient(host); smtp.from(from); smtp.to(to); PrintStream msg = smtp.startMessage(); msg.println(&quot;To: &quot; + to); msg.println(&quot;Subject: Hello SmtpClient&quot;); msg.println(); // blank line between headers and message msg.println(&quot;This is a test message.&quot;); smtp.closeServer(); } }
  • 6. Without JavaMail Take 3 Just use a URL Open a mailto: URL Write to opened URLConnection Need to set mail.host System property Be sure to end lines with \r\n Don’t use println()
  • 7. Mail Through URL import java.io.*; import java.net.*; public class MailTo { public static void main(String args[]) throws Exception { System.getProperties().put(&quot;mail.host&quot;, args[0]); URL url = new URL(&quot;mailto:jaz@jguru.com&quot;); URLConnection conn = url.openConnection(); PrintStream out = new PrintStream(conn.getOutputStream(), true); out.print(&quot;From: jguru-fan@yourisp.com&quot;+&quot;\r\n&quot;); out.print(&quot;Subject: Works Great!&quot;+&quot;\r\n&quot;); out.print(&quot;Thanks!&quot;+&quot;\r\n&quot;); out.close(); System.out.println(&quot;Message Sent&quot;); } }
  • 8. With JavaMail API Latest Version 1.2 December 5, 2000 release Sun includes IMAP, POP, and SMTP service providers Version 1.1.3 (2/22/2000) most popular one used Need to get JavaBeans Activation Framework http://java.sun.com/beans/glasgow/jaf.html See demo directory for many examples
  • 9. JavaMail Setup Add JAR files to CLASSPATH, to jre/lib/ext Applets can use: javax.* Won’t work in Netscape though without Plug-in Will work in Internet Explorer / HotJava JavaMail mail.jar (280K) Separate JAR files available if only using parts Activation Framework activation.jar (45K)
  • 10. JDK Requirements Works with JDK 1.1.6+ Works with Java 2 platform, Standard Edition, versions 1.2 / 1.3 Included with Java 2 platform, Enterprise Edition
  • 11. Core Classes Session Message / MimeMessage InternetAddress Authenticator Transport
  • 12. Session Represents a mail session Uses Properties to get things like mail host mail.host mail.smtp.host Get session - no constructor Session session = Session.getInstance(props, null); // null for Authenticator Session session = Session.getDefaultInstance(props, null);
  • 13. 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()
  • 14. InternetAddress RFC822 Address Create: new InternetAddress(&quot;jaz@zukowski.net&quot;); new InternetAddress(&quot;jaz@zukowski.net &quot;, &quot;John Zukowski&quot;); For To, From, CC, BCC message.setFrom(address) message.addRecipient(type, address) Types Message.RecipientType.TO Message.RecipientType.CC Message.RecipientType.BCC
  • 15. 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); }
  • 16. Transport Message transport mechanism Get transport for session Transport transport = session.getTransport(&quot;smtp&quot;); Connect transport.connect(host, username, password); Act - repeat if necessary transport.sendMessage(message, message.getAllRecipients()); Done transport.close();
  • 17. Sending Mail Need a working SMTP server Can be written in Java using JavaMail API, but irrelevant Need from/to addresses, but don’t need to be valid, unless SMTP server includes some form of verification To run example: java MailExample smtp.mailserver from@from.com to@to.com
  • 18. Hello World 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 properties Properties props = System.getProperties(); // Setup mail server props.put(&quot;mail.smtp.host&quot;, host);
  • 19. Hello World/2 // 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(&quot;Hello JavaMail&quot;); message.setText(&quot;Welcome to JavaMail&quot;); // Send message Transport.send(message); } }
  • 20. Getting Mail POP3 provider doesn’t provide local data storage There are mailbox store providers available Need to get/install POP3 provider Part of JavaMail 1.2 release NOT part of basic JavaMail 1.1 API implementation
  • 21. Reading Hello World 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 properties Properties props = new Properties(); // Get session Session session = Session.getInstance(props, null);
  • 22. Reading Hello World/2 // Get the store Store store = session.getStore(&quot;pop3&quot;); store.connect(host, username, password); // Get folder Folder folder = store.getFolder(&quot;INBOX&quot;); 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++) {
  • 23. Reading Hello World/3 System.out.println(i + &quot;: &quot; + message[i].getFrom()[0] + &quot;\t&quot; + message[i].getSubject()); System.out.println(&quot;Do you want to read message? [YES to read/QUIT to end]&quot;); String line = reader.readLine(); if (&quot;YES&quot;.equals(line)) { message[i].writeTo(System.out); } else if (&quot;QUIT&quot;.equals(line)) { break; } } // Close connection folder.close(false); store.close(); } }
  • 24. Authenticator Usage Put host in properties Properties props = new Properties(); props.put(&quot;mail.host&quot;, host); Setup authentication, get session Authenticator auth = new PopupAuthenticator(); Session session = Session.getInstance(props, auth); Get the store Store store = session.getStore(&quot;pop3&quot;); store.connect();
  • 25. Saving Messages To save copy locally: Get/create appropriate provider Knife - http://www.dog.net.uk/knife/ mimeMessage.writeTo(outputStream)
  • 26. Replying Use Message.reply(boolean) Sets up message with proper headers boolean of true indicates reply to all vs. reply to sender only Does NOT setup message contents
  • 27. Deleting Messages Set message flag to deleted: message.setFlag(Flags.Flag.DELETED, true); Be sure folder opened read-write: folder.open(Folder.READ_WRITE); Deleted when folder closed: folder.close(true); // true = expunge Expunge / Permanently Deletes folder.expunge() NOT always implemented
  • 28. Including Attachments Each attachment goes into a MimeBodyPart DataHandler deals with reading in contents Provide it with a DataSource Either URLDataSource or FileDataSource
  • 29. Sending Attachments // create mime message object and set the required parameters MimeMessage message = createMessage(to, cc, subject); // create the message part MimeBodyPart messageBodyPart = new MimeBodyPart(); //fill message messageBodyPart.setText(msg); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // fill the array of files to be attached File [] attachments = { .... }
  • 30. Sending Attachments/2 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 message message.setContent(multipart); // SEND THE MESSAGE Transport.send(message);
  • 31. Sending HTML Attachment Don’t use setText() Use setDataHandler() String htmlText = &quot;<H1>Hello</H1><H2>World</H2>&quot;; message.setContent(htmlText, &quot;text/html&quot;));
  • 32. Including HTML Images Inline Specify Image source with cid: URL <IMG SRC=cid:23abc@pc27> Set Content-ID in header of image attachment part.setHeader(&quot;Content-ID&quot;,&quot;23abc@pc27&quot;); Complete example: http://www.jguru.com/jguru/faq/view.jsp?EID=97371
  • 33. Getting Attachments from Client You want to create a web-based email system Your user wants to include file from their system as attachment Use an HTML Form Use Servlet to read stream Use MultipartRequest class from O’Reilly servlets book – www.servlets.com
  • 34. HTML Form <FORM ENCTYPE=&quot;multipart/form-data&quot; method=post action=&quot;/myservlet&quot;> <INPUT TYPE=&quot;file&quot; NAME=&quot;mptest&quot;> <INPUT TYPE=&quot;submit&quot; VALUE=&quot;upload&quot;> </FORM>
  • 35. Getting Attachments For each part of Multipart, process part Attachments can be inline or not String disposition = part.getDisposition(); if (disposition.equals(Part.INLINE)) if (disposition.equals(Part.ATTACHMENT))
  • 36. Save Attachments public static void handleMultipart(Multipart multipart) throws MessagingException, IOException { for (int i=0, n=multipart.getCount(); i<n; i++) { handlePart(multipart.getBodyPart(i)); } } Following code doesn’t deal with Multipart in Multipart left as exercise for reader 
  • 37. Save Attachments/2 public static void handlePart(Part part) throws MessagingException, IOException { String disposition = part.getDisposition(); String contentType = part.getContentType(); if (disposition == null) { // When just body System.out.println(&quot;Null: &quot; + contentType); // Check if plain if ((contentType.length() >= 10) && (contentType.toLowerCase().substring(0, 10).equals(&quot;text/plain&quot;))) { part.writeTo(System.out); } else { // Don't think this will happen System.out.println(&quot;Other body: &quot; + contentType); part.writeTo(System.out); }
  • 38. Save Attachments/3 } else if (disposition.equals(Part.ATTACHMENT)) { System.out.println(&quot;Attachment: &quot; + part.getFileName() + &quot; : &quot; + contentType); saveFile(part.getFileName(), part.getInputStream()); } else if (disposition.equals(Part.INLINE)) { System.out.println(&quot;Inline: &quot; + part.getFileName() + &quot; : &quot; + contentType); saveFile(part.getFileName(), part.getInputStream()); } else { // Should never happen System.out.println(&quot;Other: &quot; + disposition); } }
  • 39. Debugging Trace commands sent session.setDebug(true)
  • 40. New Mail Notification Events Add MessageCountListener to folder Find out when new messages are received Sleep then folder.getMessageCount() to get notification from IMAP server Not POP3 - Does not work when folder open
  • 41. More Notification Events Transport/Store/Folder.addConnectionListener() open, closed, disconnected Folder.addFolderListener() created, deleted, renamed Folder.addMessageChangeListener changed Store.addStoreListener notification Transport.addTransportListener message delivered, not delivered, partially delivered
  • 42. JavaMail Searching API includes support for searching for matching messages javax.mail.search package Build a SearchTerm Search: Message[] msgs = folder.search(st);
  • 43. Building Up SearchTerm AND terms (class AndTerm) OR terms (class OrTerm) NOT terms (class NotTerm) SENT DATE terms (class SentDateTerm) CONTENT terms (class BodyTerm) HEADER terms (FromTerm / FromStringTerm, RecipientTerm / RecipientStringTerm, SubjectTerm, etc..)
  • 44. Using SearchTerm Folder folder = store.getFolder(&quot;INBOX&quot;); SearchTerm st = new AndTerm(new SubjectTerm(&quot;ADV:&quot;), new BodyTerm(&quot;hello&quot;); Message[] msgs = folder.search(st);
  • 45. S/MIME Includes email signing and encryption support Get a different provider Phaos S/MIME toolkit http://www.phaos.com/e_security/prod_smime.html JCSI http://security.dstc.edu.au/projects/java/release2.html
  • 46. JavaMail with JSP Definitely doable with Java source scriptlets However, should limit amount of Java source in JSP pages Use JavaBeans that hide/simplify capabilities for Web designer Create / Get ImMailBean http://www.imessaging.com/html/immailbean.html Source Fourge http://sourceforge.net/project/?group_id=1282
  • 47. JavaMail with NNTP You can use JavaMail with NNTP Need to get an NNTP provider http://www.dog.net.uk/knife/ To read newsgroups Store store = session.getStore(&quot;nntp&quot;); store.connect(host, username, password); Folder folder = store.getFolder(newsgroup); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages();
  • 48. JavaMail is Free Sun’s reference implementation is completely free Sun’s License: http://java.sun.com/products/javamail/LICENSE.txt Includes SMTP, IMAP, and POP3 providers
  • 49. James Java Apache Mail Enterprise Server Pure Java-based mail server Supports Mailets Like servlets, but for extending mail server Add capabilities like mailing list support, filtering, translation, etc. http://java.apache.org/james/index.html
  • 50. Miscellaneous Sun’s JavaMail FAQ http://java.sun.com/products/javamail/FAQ.html Mailing List http://archives.java.sun.com/archives/javamail-interest.html Get the JavaMail Source 1.1.2 source part of J2EE Sun Community Source Licensing http://www.sun.com/software/communitysource/j2ee/
  • 51. Other Providers knife http://www.dog.net.uk/knife/ NNTP, POP3, mailbox file provider Project &quot;POPpers&quot; http://www2s.biglobe.ne.jp/~dat/java/project/poppers/index_en.html ICEMail Java-based Email Client http://www.icemail.org/
  • 52. Questions & Answers Questions? Use the FAQs John Zukowski http://www.jguru.com http://java.about.com http://www.jguru.com/faq/JavaMail