SlideShare una empresa de Scribd logo
1 de 20
Descargar para leer sin conexión
JavaMail API
Fundamentals
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 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 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(“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 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 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 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 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 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 (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 message
message.setContent(multipart);

// SEND THE MESSAGE
Transport.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

Más contenido relacionado

La actualidad más candente

WORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGWORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGHitesh Mohapatra
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
Examples from Pune meetup
Examples from Pune meetupExamples from Pune meetup
Examples from Pune meetupSantosh Ojha
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and EnhancementsGagan Agrawal
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsSolution4Future
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rackdanwrong
 
Python concurrency: libraries overview
Python concurrency: libraries overviewPython concurrency: libraries overview
Python concurrency: libraries overviewAndrii Mishkovskyi
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Somenath Mukhopadhyay
 
Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservicesMarcos Lin
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Kiyotaka Oku
 
Maksim Melnikau aka “max_posedon” - Telepathy protocol example
Maksim Melnikau aka “max_posedon” - Telepathy protocol exampleMaksim Melnikau aka “max_posedon” - Telepathy protocol example
Maksim Melnikau aka “max_posedon” - Telepathy protocol exampleMinsk Linux User Group
 
Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)njbartlett
 
Real time server
Real time serverReal time server
Real time serverthepian
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 

La actualidad más candente (20)

Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
OSGi Puzzlers
OSGi PuzzlersOSGi Puzzlers
OSGi Puzzlers
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGWORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
Examples from Pune meetup
Examples from Pune meetupExamples from Pune meetup
Examples from Pune meetup
 
Java 7 Features and Enhancements
Java 7 Features and EnhancementsJava 7 Features and Enhancements
Java 7 Features and Enhancements
 
Python RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutionsPython RESTful webservices with Python: Flask and Django solutions
Python RESTful webservices with Python: Flask and Django solutions
 
8 Minutes On Rack
8 Minutes On Rack8 Minutes On Rack
8 Minutes On Rack
 
Python concurrency: libraries overview
Python concurrency: libraries overviewPython concurrency: libraries overview
Python concurrency: libraries overview
 
Psr-7
Psr-7Psr-7
Psr-7
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...Implementation of a state machine for a longrunning background task in androi...
Implementation of a state machine for a longrunning background task in androi...
 
Flask restfulservices
Flask restfulservicesFlask restfulservices
Flask restfulservices
 
httpie
httpiehttpie
httpie
 
Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介Grails/Groovyによる開発事例紹介
Grails/Groovyによる開発事例紹介
 
Maksim Melnikau aka “max_posedon” - Telepathy protocol example
Maksim Melnikau aka “max_posedon” - Telepathy protocol exampleMaksim Melnikau aka “max_posedon” - Telepathy protocol example
Maksim Melnikau aka “max_posedon” - Telepathy protocol example
 
JAVA NIO
JAVA NIOJAVA NIO
JAVA NIO
 
Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)Introduction to OSGi (Tokyo JUG)
Introduction to OSGi (Tokyo JUG)
 
Real time server
Real time serverReal time server
Real time server
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 

Destacado

Ahmadova yana
Ahmadova yanaAhmadova yana
Ahmadova yanaklepa.ru
 
Life Insurance - 2013 Gold Monitor Award Winners
Life Insurance - 2013 Gold Monitor Award WinnersLife Insurance - 2013 Gold Monitor Award Winners
Life Insurance - 2013 Gold Monitor Award WinnersCorporate Insight
 
Haiti great progress achieved, huge challenges ahead
Haiti great progress achieved, huge challenges aheadHaiti great progress achieved, huge challenges ahead
Haiti great progress achieved, huge challenges aheadlaurentlamothe
 
Outlook 2013 LPL Financial Research
Outlook 2013   LPL Financial ResearchOutlook 2013   LPL Financial Research
Outlook 2013 LPL Financial Researchlewiswalker
 
Presentation1 officer buckle
Presentation1 officer bucklePresentation1 officer buckle
Presentation1 officer buckleliza14
 
Community mobilization slides august 2012 (3)
Community mobilization slides   august 2012 (3)Community mobilization slides   august 2012 (3)
Community mobilization slides august 2012 (3)progroup
 
Compliant Email Solutions for HIPAA & SOX regulations
Compliant Email Solutions for HIPAA & SOX regulationsCompliant Email Solutions for HIPAA & SOX regulations
Compliant Email Solutions for HIPAA & SOX regulationsSherWeb
 
Social Media Distraction - How to Avoid It
Social Media Distraction - How to Avoid ItSocial Media Distraction - How to Avoid It
Social Media Distraction - How to Avoid Itgraspitmarketing
 
digital proctor system
digital proctor systemdigital proctor system
digital proctor systemMuthu Kumar
 
Ppt roshna corrected
Ppt roshna correctedPpt roshna corrected
Ppt roshna correctedSano Anil
 
Student induction 2013-14
Student induction 2013-14Student induction 2013-14
Student induction 2013-14doogstone
 
Outsourcing your share point hosting the cloud’s fine print magnified
Outsourcing your share point hosting the cloud’s fine print magnifiedOutsourcing your share point hosting the cloud’s fine print magnified
Outsourcing your share point hosting the cloud’s fine print magnifiedSherWeb
 
How to-ruin-your-happiness
How to-ruin-your-happinessHow to-ruin-your-happiness
How to-ruin-your-happinessSarwan Singh
 
Teaching mannuel
Teaching mannuelTeaching mannuel
Teaching mannuelSano Anil
 
A Historical Glimpse at Jerusalem’s Western Wall
A Historical Glimpse at Jerusalem’s Western WallA Historical Glimpse at Jerusalem’s Western Wall
A Historical Glimpse at Jerusalem’s Western WallLeib Tropper
 
2016 April Announcements
2016 April Announcements2016 April Announcements
2016 April AnnouncementsWayne Irwin
 

Destacado (20)

Ahmadova yana
Ahmadova yanaAhmadova yana
Ahmadova yana
 
Parish Leadership 2014: Real Estate
Parish Leadership 2014: Real EstateParish Leadership 2014: Real Estate
Parish Leadership 2014: Real Estate
 
Life Insurance - 2013 Gold Monitor Award Winners
Life Insurance - 2013 Gold Monitor Award WinnersLife Insurance - 2013 Gold Monitor Award Winners
Life Insurance - 2013 Gold Monitor Award Winners
 
Haiti great progress achieved, huge challenges ahead
Haiti great progress achieved, huge challenges aheadHaiti great progress achieved, huge challenges ahead
Haiti great progress achieved, huge challenges ahead
 
Outlook 2013 LPL Financial Research
Outlook 2013   LPL Financial ResearchOutlook 2013   LPL Financial Research
Outlook 2013 LPL Financial Research
 
Presentation1 officer buckle
Presentation1 officer bucklePresentation1 officer buckle
Presentation1 officer buckle
 
Community mobilization slides august 2012 (3)
Community mobilization slides   august 2012 (3)Community mobilization slides   august 2012 (3)
Community mobilization slides august 2012 (3)
 
Compliant Email Solutions for HIPAA & SOX regulations
Compliant Email Solutions for HIPAA & SOX regulationsCompliant Email Solutions for HIPAA & SOX regulations
Compliant Email Solutions for HIPAA & SOX regulations
 
Social Media Distraction - How to Avoid It
Social Media Distraction - How to Avoid ItSocial Media Distraction - How to Avoid It
Social Media Distraction - How to Avoid It
 
digital proctor system
digital proctor systemdigital proctor system
digital proctor system
 
Ppt roshna corrected
Ppt roshna correctedPpt roshna corrected
Ppt roshna corrected
 
Student induction 2013-14
Student induction 2013-14Student induction 2013-14
Student induction 2013-14
 
Outsourcing your share point hosting the cloud’s fine print magnified
Outsourcing your share point hosting the cloud’s fine print magnifiedOutsourcing your share point hosting the cloud’s fine print magnified
Outsourcing your share point hosting the cloud’s fine print magnified
 
How to-ruin-your-happiness
How to-ruin-your-happinessHow to-ruin-your-happiness
How to-ruin-your-happiness
 
Educazione fisica
Educazione fisicaEducazione fisica
Educazione fisica
 
Teaching mannuel
Teaching mannuelTeaching mannuel
Teaching mannuel
 
A Historical Glimpse at Jerusalem’s Western Wall
A Historical Glimpse at Jerusalem’s Western WallA Historical Glimpse at Jerusalem’s Western Wall
A Historical Glimpse at Jerusalem’s Western Wall
 
Problemas ud 2
Problemas ud 2Problemas ud 2
Problemas ud 2
 
Ergonomía
Ergonomía Ergonomía
Ergonomía
 
2016 April Announcements
2016 April Announcements2016 April Announcements
2016 April Announcements
 

Similar a Lecture11 b

Please include comments if at all possible Use a socket connection t.pdf
Please include comments if at all possible Use a socket connection t.pdfPlease include comments if at all possible Use a socket connection t.pdf
Please include comments if at all possible Use a socket connection t.pdffashionfootwear1
 
Distributed Objects and JAVA
Distributed Objects and JAVADistributed Objects and JAVA
Distributed Objects and JAVAelliando dias
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
file-transfer-using-tcp.pdf
file-transfer-using-tcp.pdffile-transfer-using-tcp.pdf
file-transfer-using-tcp.pdfJayaprasanna4
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfmeerobertsonheyde608
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsYakov Fain
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdffashiongallery1
 
State management in ASP.NET
State management in ASP.NETState management in ASP.NET
State management in ASP.NETOm Vikram Thapa
 
Java remote method invocation
Java remote method invocationJava remote method invocation
Java remote method invocationVan Dawn
 
4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message BrokersPROIDEA
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 

Similar a Lecture11 b (20)

Lecture19
Lecture19Lecture19
Lecture19
 
JavaExamples
JavaExamplesJavaExamples
JavaExamples
 
Please include comments if at all possible Use a socket connection t.pdf
Please include comments if at all possible Use a socket connection t.pdfPlease include comments if at all possible Use a socket connection t.pdf
Please include comments if at all possible Use a socket connection t.pdf
 
Servlets
ServletsServlets
Servlets
 
Run rmi
Run rmiRun rmi
Run rmi
 
Distributed Objects and JAVA
Distributed Objects and JAVADistributed Objects and JAVA
Distributed Objects and JAVA
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Lecture19
Lecture19Lecture19
Lecture19
 
file-transfer-using-tcp.pdf
file-transfer-using-tcp.pdffile-transfer-using-tcp.pdf
file-transfer-using-tcp.pdf
 
Need help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdfNeed help on creating code using cart. The output has to show multip.pdf
Need help on creating code using cart. The output has to show multip.pdf
 
Speed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSocketsSpeed up your Web applications with HTML5 WebSockets
Speed up your Web applications with HTML5 WebSockets
 
Hi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdfHi, I need some one to help me with Design a client-server Chat so.pdf
Hi, I need some one to help me with Design a client-server Chat so.pdf
 
State management in ASP.NET
State management in ASP.NETState management in ASP.NET
State management in ASP.NET
 
Java remote method invocation
Java remote method invocationJava remote method invocation
Java remote method invocation
 
Jms
JmsJms
Jms
 
Jms
JmsJms
Jms
 
Jms
JmsJms
Jms
 
4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers4Developers: Dominik Przybysz- Message Brokers
4Developers: Dominik Przybysz- Message Brokers
 
Lecture6
Lecture6Lecture6
Lecture6
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 

Más de vantinhkhuc (20)

Url programming
Url programmingUrl programming
Url programming
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Security overview
Security overviewSecurity overview
Security overview
 
Rmi
RmiRmi
Rmi
 
Md5
Md5Md5
Md5
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture9
Lecture9Lecture9
Lecture9
 
Jsse
JsseJsse
Jsse
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Jsp examples
Jsp examplesJsp examples
Jsp examples
 
Jpa
JpaJpa
Jpa
 
Ejb examples
Ejb examplesEjb examples
Ejb examples
 
Corba
CorbaCorba
Corba
 
Ajax
AjaxAjax
Ajax
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
Chc6b0c6a1ng 12
Chc6b0c6a1ng 12Chc6b0c6a1ng 12
Chc6b0c6a1ng 12
 
Ch06
Ch06Ch06
Ch06
 
Bai4
Bai4Bai4
Bai4
 

Lecture11 b

  • 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. Core Classes Session Message / MimeMessage InternetAddress Authenticator Transport Store
  • 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 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 Authenticator Session session = Session.getDefaultInstance(props, null);
  • 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. 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. 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. 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. 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. 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 properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host);
  • 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. Getting Mail There are mailbox store providers available (POP3 and IMAP).
  • 13. 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 properties Properties props = new Properties(); // Get session Session session = Session.getInstance(props, null);
  • 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. 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. 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. Sending Attachments Each attachment goes into a MimeBodyPart DataHandler deals with reading in contents Provide it with a URLDataSource or FileDataSource.
  • 18. 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 = { .... }
  • 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 message message.setContent(multipart); // SEND THE MESSAGE Transport.send(message);
  • 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