APJ-I – Lab8 - JavaMail Application Programming I Module 9: JavaMail Lab Guide for Lab8 Session Objectives In this session, you will be practicing with JavaMail API Steps for E-Mail Part – Getting started (30 minutes) Create a Send mail application (15 minutes) Consider the following example for understanding this three step process in detail: a Import the package javax.mail and then sub package javax.mail.internet import javax.mail.*; import javax.mail.internet.*; import java.util.*; b Create a class (SendingMail) and declare the host address, source address and destination address public class SendingMail { public static void main(String args[]) { final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory"; String myhost = "smtp.gmail.com"; //Using Gmail server String frm = "fpt.java.mail@gmail.com"; //Using existed gmail account String to = "fpt.java.mail@gmail.com"; //Your email c Get system properties as: Properties props = System.getProperties(); d Put value to Properties object props.put("mail.smtp.host", myhost); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.port", "465"); props.put("mail.transport.protocol", "smtp"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.socketFactory.class", SSL_FACTORY); props.put("mail.smtp.socketFactory.fallback", "false"); © 2011 FPT-Aptech Page / APJ-I - Lab9 - JavaMail e Create Session object to authentication Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication("fpt.java.mail@gmail.com", "khongcopassword"); //Using existed gmail account }); f Create a default MimeMessage object MimeMessage mesg = new MimeMessage(session); g Add email address and send email try { mesg.setFrom(new InternetAddress(frm)); mesg.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); mesg.setSubject("Test send mail"); mesg.setText("Content to test "); Transport.send(mesg); System.out.println("Send mail success!!!"); } catch (AddressException ex) { System.out.println("There was a problem sending your mail.\n" + ex); } catch (MessagingException e) { System.out.println("There was a problem sending your mail.\n" + e); } h Check your code and run application Create a JFrame for send mail application, design the interface as the following picture: (20 minutes – Use Netbeans) © 2011 FPT-Aptech Page / APJ-I – Lab8 - JavaMail Part – Workshops (30 minutes) Quickly look at workshops for Module for reviewing basic steps Try to compile, run and observe the output of sample code provided for related workshop Discuss with your class-mate and your instructor if needed Part – Lab Assignment (60 minutes) Do the assignment for Module carefully Discuss with your class-mates and your instructor if needed © 2011 FPT-Aptech Page /