dineshonjava

Authentication using JavaMail SMTP

Many SMTP servers use an authentication system as an extra layer of security in their mail transport. If you need to send email to such a server with JavaMail, the library provides a convenient abstraction of the process. First, create an anonymous inner class that implements javax.mail.Authenticator and contains the password authentication information:

Authenticator authenticator = new Authenticator() {
private PasswordAuthentication authentication;
 
{
authentication = new PasswordAuthentication("username", "password");
}
 
protected PasswordAuthentication getPasswordAuthentication() {
return authentication;
}
};
Next, create instances of java.util.Properties and javax.mail.Session that will be used to build the message transport. The important differences from JavaMail usage here are the extra auth property and the passing of the authenticator object to the mail session. (Note that all values of the Properties instance are strings — this is required by the class. Booleans, integers, et cetera should be passed as strings to this object.)

Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.host", "smtp.somewhere.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
Session session = Session.getDefaultInstance(props, authenticator);

Now that our Session is prepared, we can send the message as normal. The authentication model is carried within the mail session, so each message can take it in and reuse its information.


Message message = new MimeMessage(session);
 
message.setFrom(new InternetAddress("from@somewhere.com"));
message.addRecipient(RecipientType.TO, new InternetAddress("xyz@somewhere.com"));
 
message.setSubject("Hello world!");
message.setContent("Sent via an SMTP server with authentication.", "text/plain");
 
Transport.send(message);


<<Previous <<   || Index ||   >>Next >>


Replying email in Java Mail API

In this chapter we will see how to reply to an email using JavaMail API.

We can forward the received mail to someone else as we send emails. There are many javamail classes that are used to forward the messages to the destination resource.

For better understanding of this example, learn the steps of sending email using JavaMail API first.

For receiving or sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar

Create Java Class

Create a java class file ReplyToEmail, the contents of which are as follows:

import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
 
public class ReplyToEmail {
 public static void main(String[] args) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  final String username="admin@dineshonjava.com";
  final String password="******";
  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(username,password);
    }
   });
  try {
  Store store = session.getStore("imaps");  
  store.connect("imap.gmail.com",username, password);  
  
  //Create a Folder object and open the folder  
  Folder folder = store.getFolder("inbox");  
  folder.open(Folder.READ_ONLY);  
     Message message = folder.getMessage(10);  
    // Get all the information from the message  
    String from = InternetAddress.toString(message.getFrom());  
    if (from != null) {  
   System.out.println("From: " + from);  
    }  
    String replyTo = InternetAddress.toString(message.getReplyTo());  
    if (replyTo != null) {  
   System.out.println("Reply-to: " + replyTo);  
    }  
    String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));  
    if (to != null) {  
   System.out.println("To: " + to);  
    }  
    
    String subject = message.getSubject();  
   if (subject != null) {  
  System.out.println("Subject: " + subject);  
   }  
   Date sent = message.getSentDate();  
   if (sent != null) {  
  System.out.println("Sent: " + sent);  
   }  
   System.out.println(message.getContent());  
   
   // compose the message to forward  
   Message message2 = new MimeMessage(session);  
    message2= (MimeMessage) message.reply(false);
   message2.setSubject("RE: " + message.getSubject());  
   message2.setFrom(new InternetAddress(from));  
   message2.setReplyTo(message.getReplyTo());

   message2.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
   
   // Create your new message part  
   BodyPart messageBodyPart = new MimeBodyPart();  
   messageBodyPart.setText("Oiginal message:\n\n");  
   
   // Create a multi-part to combine the parts  
   Multipart multipart = new MimeMultipart();  
   multipart.addBodyPart(messageBodyPart);  
   
   // Create and fill part for the forwarded content  
   messageBodyPart = new MimeBodyPart();  
   messageBodyPart.setDataHandler(message.getDataHandler());  
   
   // Add part to multi part  
   multipart.addBodyPart(messageBodyPart);  
   
   // Associate multi-part with message  
   message2.setContent(multipart);  
   
   // Send message  
   Transport.send(message2);  
   
   System.out.println("message replied successfully ....");  
   } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
}

Compile and Run

Now that our class is ready, let us compile the above class. I've saved the class ReplyToEmail.java to directory : D:\Javas\mailapi\. We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class

Replying email in Java Mail API

Verify Output

You should see the following message on the command console:
From: Anonymous <noreply-comment@blogger.com>
Reply-to: Anonymous <noreply-comment@blogger.com>
To: admin@dineshonjava.com
Subject: [Dinesh on Java] New comment on Writing First AspectJ Program in Spring
 : Chapter ....
Sent: Wed Dec 19 10:29:12 IST 2012
javax.mail.internet.MimeMultipart@1afebc9
message replied successfully ....


Replying email in Java Mail



<<Previous <<   || Index ||   >>Next >>



Deleting email in Java Mail API

We already discussed the fundamentals of Java Mail API.

In the previous chapters we were discussed the way by which Java mail API uses SMTP to send emails with attachment and without attachment. Also we discussed the way by which Java Mail API is reading emails using POP as well as IMAP.In this chapter we are discussing how an email can be deleted from Gmail inbox from a Java application.

We are accessing Gmail mail server in our application.We are displaying the unread mails from inbox using IMAP as protocol. Then deleting the first unread email .When the program exits and if we open the inbox , then we can observe the result properly.

An email can be deleted from inbox by using
message.setFlag(Flags.Flag.DELETED, true)
The predefined flags are defined in the inner class Flags.Flag and are listed below:
  • Flags.Flag.ANSWERED
  • Flags.Flag.DELETED
  • Flags.Flag.DRAFT
  • Flags.Flag.FLAGGED
  • Flags.Flag.RECENT
  • Flags.Flag.SEEN
  • Flags.Flag.USER
For receiving or sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar

Steps for deleting the email using JavaMail API
There are total 5 steps for deleting the email. They are:
  1. Get the session object
  2. create the store object and connect to the current host
  3. create the folder object and open it
  4. Get the message to delete
  5. delete the message using setFlag method
Example of deleting email using JavaMail API-
Now let us see the Java application. The following class needs to put as a class in a dynamic web project. If we need to access mails from J2SE application , then we can download Java Mail API from here.Extract the zip file and include the jar files in the project path.

DeleteMailSample.java

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Flags.Flag;
import javax.mail.search.FlagTerm;
public class DeleteMailSample {
    Properties properties = null;
    private Session session = null;
    private Store store = null;
    private Folder inbox = null;
    private Message messages[];
    private String userName = "*******@gmail.com";// provide user name
    private String password = "********";// provide password
    public DeleteMailSample() {
    }

    public void getMails() {
        getConnection();
        readMails();
        if (null != messages && messages.length > 0) {
            System.out.println("trying to delete  first mail...");
            deleteMessage(messages[0]);
            closeSession();
        }
    }

   public void getConnection() {
        properties = new Properties();
        properties.setProperty("mail.host", "imap.gmail.com");
        properties.setProperty("mail.port", "995");
        properties.setProperty("mail.transport.protocol", "imaps");
        session = Session.getInstance(properties,
                new javax.mail.Authenticator() {
                    protected PasswordAuthentication getPasswordAuthentication() {
                        return new PasswordAuthentication(userName, password);
                    }
                });
        try {
            store = session.getStore("imaps");
            store.connect();
            inbox = store.getFolder("INBOX");
            inbox.open(Folder.READ_WRITE);
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

     public void readMails() {
        try {
            if (null != inbox) {
                messages = inbox.search(new FlagTerm(new Flags(Flag.SEEN),false));
                System.out.println("Number of mails = " + messages.length);
                for (int i = 0; i < messages.length; i++) {
                    Message message = messages[i];
                    Address[] from = message.getFrom();
                    System.out.println("-------------------------------");
                    System.out.println("Date : " + message.getSentDate());
                    System.out.println("From : " + from[0]);
                    System.out.println("Subject: " + message.getSubject());
                    System.out.println("Content :");
                    processMessageBody(message);
                    System.out.println("--------------------------------");
                }
            }
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public void closeSession() {
        if (null != inbox && null != store) {
            try {
                inbox.close(true);
                store.close();
            } catch (MessagingException e) {
                e.printStackTrace();
            }
        }
    }
    public void deleteMessage(Message message) {
        try {
            message.setFlag(Flags.Flag.DELETED, true);
            System.out.println("deleted mail");
        } catch (MessagingException e) {
           e.printStackTrace();
        }
    }
    public void processMessageBody(Message message) {
        try {
            Object content = message.getContent();
           // check for string
            // then check for multipart
            if (content instanceof String) {
                System.out.println(content);
            } else if (content instanceof Multipart) {
                Multipart multiPart = (Multipart) content;
                procesMultiPart(multiPart);
            } else if (content instanceof InputStream) {
                InputStream inStream = (InputStream) content;
                int ch;
                while ((ch = inStream.read()) != -1) {
                    System.out.write(ch);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    public void procesMultiPart(Multipart content) {
        try {
            int multiPartCount = content.getCount();
            for (int i = 0; i < multiPartCount; i++) {
                BodyPart bodyPart = content.getBodyPart(i);
                Object o;
                o = bodyPart.getContent();
                if (o instanceof String) {
                    System.out.println(o);
                } else if (o instanceof Multipart) {
                    procesMultiPart((Multipart) o);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        DeleteMailSample sample = new DeleteMailSample();
        sample.getMails();
    }
}

Provide username and password for gmail account. Then compile and run the code. Assume our inbox has 1 unread mail as of now. So the number of mails will be displayed as 1.Then it will display the individual mails one by one. At last it will delete the first mail in inbox. This can be verified by logging in to gmail account from any client or using browser.

Inbox before running this application-

Deleting email in Java Mail API

Now set up classpath and compile java file as follows-

Deleting email in Java

Now after run this application please see Inbox Mail is deleted-

Deleting email in Java Mail







<<Previous <<   || Index ||   >>Next >>









Forwarding Messages using Java Mail

This Example shows you how to forward a message using javamail api. there is no method to forward a mail from one user to another user. if u want forward a message to another user firstly get all header field and get message content then send its for another user.


We can forward the received mail to someone else as we send emails. There are many javamail classes that are used to forward the messages to the destination resource.

For better understanding of this example, learn the steps of sending email using JavaMail API first.
For receiving or sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar

Create Java Class

Create a java class file ForwardEmail, the contents of which are as follows:
import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
 
public class ForwardMail {
 public static void main(String[] args) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  final String username="dineshonjava@gmail.com";
  final String password="******";
  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(username,password);
    }
   });
  try {
  //Message message = new MimeMessage(session);
  //message.setFrom(new InternetAddress("dineshonjava@gmail.com"));
  //message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("admin@dineshonjava.com"));
  // Get a Store object and connect to the current host   
  Store store = session.getStore("imaps");  
  store.connect("imap.gmail.com","dineshonjava@gmail.com", password);  
  
  //Create a Folder object and open the folder  
  Folder folder = store.getFolder("inbox");  
  folder.open(Folder.READ_ONLY);  
     Message message = folder.getMessage(1);  
    // Get all the information from the message  
    String from = InternetAddress.toString(message.getFrom());  
    if (from != null) {  
   System.out.println("From: " + from);  
    }  
    String replyTo = InternetAddress.toString(message.getReplyTo());  
    if (replyTo != null) {  
   System.out.println("Reply-to: " + replyTo);  
    }  
    String to = InternetAddress.toString(message.getRecipients(Message.RecipientType.TO));  
    if (to != null) {  
   System.out.println("To: " + to);  
    }  
    
    String subject = message.getSubject();  
   if (subject != null) {  
  System.out.println("Subject: " + subject);  
   }  
   Date sent = message.getSentDate();  
   if (sent != null) {  
  System.out.println("Sent: " + sent);  
   }  
   System.out.println(message.getContent());  
   
   // compose the message to forward  
   Message message2 = new MimeMessage(session);  
   message2.setSubject("Fwd: " + message.getSubject());  
   message2.setFrom(new InternetAddress(from));  
   message2.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  
   
   // Create your new message part  
   BodyPart messageBodyPart = new MimeBodyPart();  
   messageBodyPart.setText("Oiginal message:\n\n");  
   
   // Create a multi-part to combine the parts  
   Multipart multipart = new MimeMultipart();  
   multipart.addBodyPart(messageBodyPart);  
   
   // Create and fill part for the forwarded content  
   messageBodyPart = new MimeBodyPart();  
   messageBodyPart.setDataHandler(message.getDataHandler());  
   
   // Add part to multi part  
   multipart.addBodyPart(messageBodyPart);  
   
   // Associate multi-part with message  
   message2.setContent(multipart);  
   
   // Send message  
   Transport.send(message2);  
   
   System.out.println("message forwarded ....");  
   } catch (Exception e) {
   throw new RuntimeException(e);
  }
 }
}

Compile and Run

Now that our class is ready, let us compile the above class. I've saved the class ForwardEmail.java

We would need the jars javax.mail.jar and activation.jar in the classpath. Execute the command below to compile the class

Forwarding Messages using Java Mail API

Verify Output

You should see the following message on the command console:

From: Gmail Team <mail-noreply@google.com>
Reply-to: Gmail Team <mail-noreply@google.com>
To: Dinesh Rajput <dineshonjava@gmail.com>
Subject: Get Gmail on your mobile phone
Sent: Sun Apr 15 21:31:38 IST 2012
javax.mail.internet.MimeMultipart@1719d5b
message forwarded ....



Forwarding Messages using Java Mail




<<Previous <<   || Index ||   >>Next >>



Sending Email With Inline Images JavaMail API

Here is an example to send an HTML email from your machine with inline image. Here we have used SMPT server via which emails are sent to our destination email address.

To send a email with an inline image, the steps followed are:
  1. Get a Session
  2. Create a default MimeMessage object and set From, To, Subject in the message.
  3. Create a MimeMultipart object.
  4. In our example we will have an HTML part and an Image in the email. So first create the HTML content and set it in the multipart object as:
    // first part (the html)
    BodyPart messageBodyPart = new MimeBodyPart();
    String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
    messageBodyPart.setContent(htmlText, "text/html");
    // add it
    multipart.addBodyPart(messageBodyPart);
    
  5. Next add the image by creating a Datahandler as follows:
    // second part (the image)
    messageBodyPart = new MimeBodyPart();
    DataSource fds = new FileDataSource("D:\\Javas\\mailapi\\100.png");
    messageBodyPart.setDataHandler(new DataHandler(fds));
    messageBodyPart.setHeader("Content-ID", "<image>");
    
  6. Next set the multipart in the message as follows:
    // second part (the image)
    message.setContent(multipart);
    
  7. Send the message using the Transport object.
Example of sending email with Inline Images JavaMail API-
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
 
public class SendInlineImagesInEmail {
 public static void main(String[] args) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  final String username="dineshonjava";
  final String password="***********";
  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(username,password);
    }
   });
 
  try {
    Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress("dineshonjava@gmail.com"));
   message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("admin@dineshonjava.com"));
   message.setSubject("Welcome Mail Tutorial!!!");
   
  // This mail has 2 part, the BODY and the embedded image
         MimeMultipart multipart = new MimeMultipart("related");
         // first part (the html)
         BodyPart messageBodyPart = new MimeBodyPart();
         String htmlText = "<H1>Hello</H1><img src=\"cid:image\">";
         messageBodyPart.setContent(htmlText, "text/html");
         // add it
         multipart.addBodyPart(messageBodyPart);
         // second part (the image)
         messageBodyPart = new MimeBodyPart();
         DataSource fds = new FileDataSource("D:\\Javas\\mailapi\\100.png");
         messageBodyPart.setDataHandler(new DataHandler(fds));
         messageBodyPart.setHeader("Content-ID", "<image>");
         // add image to the multipart
         multipart.addBodyPart(messageBodyPart);
         // put everything together
         message.setContent(multipart);
   // Send the actual HTML message, as big as you like
  Transport.send(message);
   System.out.println("Mail sent successfully!!!");
 
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}
As we are using the SMTP server provided by the host provider SMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password.

Sending Email With Inline Images JavaMail API

Verify Output
You should see the following message on the command console:

Mail sent successfully!!!

As I'm sending an email to my gmail address through SMTP, the following mail would be received in my gmail account inbox:

Sending Email With Inline Images JavaMail




<<Previous <<   || Index ||   >>Next >>


JavaMail API Sending an HTML Email

Here is an example to send an HTML email from your machine. Here we have used SMPT server via which emails are sent to our destination email address.

This example is very similar to sending simple email, except that, here we are using setContent() method to set content whose second argument is "text/html" to specify that the HTML content is included in the message. Using this example, you can send as big as HTML content you like.

For receiving or sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar

To send a email with HTML content, the steps followed are:
  1. Get a Session
  2. Create a default MimeMessage object and set From, To, Subject in the message.
  3. Set the actual message using setContent() method as below:
    message.setContent("<h1>
    This is actual message embedded in HTML tags</h1>
    ", "text/html");
    
  4. Send the message using the Transport object.

Example of sending email with html content using JavaMail API-
Create a java class file SendHTMLEmail, the contents of which are as follows:
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class SendHtmlEmail {
 public static void main(String[] args) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  final String username="dineshonjava";
  final String password="******";
  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(username,password);
    }
   });
 
  try {
    Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress("dineshonjava@gmail.com"));
   message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("admin@dineshonjava.com"));
   message.setSubject("Welcome Mail Tutorial!!!");
   // Send the actual HTML message, as big as you like
   message.setContent("<h1>Dear User,\n\n This mail tutorial really nice, please try it!!!</h1>", "text/html");
   message.setContent("<h1>sending html mail check</h1>","text/html" ); 
   Transport.send(message);
 
   System.out.println("Mail sent successfully!!!");
 
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}

As we are using the SMTP server provided by the host provider SMTP, we need to authenticate the username and password. The javax.mail.PasswordAuthentication class is used to authenticate the password.

JavaMail API Sending an HTML Email

Verify Output
You should see the following message on the command console:

Mail sent successfully!!!

As I'm sending an email to my gmail address through SMTP, the following mail would be received in my gmail account inbox:

JavaMail API Sending an HTML



<<Previous <<   || Index ||   >>Next >>




JavaMail API Receiving email with attachment

As we receive the email, we can receive the attachment also by using Multipart and BodyPart classes.
For better understanding of this example, learn the steps of sending email using JavaMail API first.

For receiving or sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar

Example of receiving email with attachment using JavaMail API
import java.util.*;  
import javax.mail.*;  
import javax.mail.internet.*;  
import javax.activation.*;  
import java.io.*; 
public class ReadMailAttachment{  
  
 public static void receiveEmail(String pop3Host, String storeType,  
  final String user, final String password) {  
  try {  
   //1) get the session object  
   Properties properties = new Properties();  
   properties.put("mail.store.protocol", "imaps");  
   //Session emailSession = Session.getDefaultInstance(properties);  
    Session emailSession = Session.getDefaultInstance(properties,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(user,password);
    }
   }); 
   //2) create the POP3 store object and connect with the pop server  
   Store emailStore = emailSession.getStore("imaps");
 emailStore.connect("imap.gmail.com","dineshonjava@gmail.com", password);
    
  
   //3) create the folder object and open it  
   Folder emailFolder = emailStore.getFolder("INBOX");  
   emailFolder.open(Folder.READ_WRITE);  
 // folder.open(Folder.READ_WRITE);  
   //4) retrieve the messages from the folder in an array and print it  
   Message[] messages = emailFolder.getMessages();  
   for (int i = 0; i < messages.length; i++) {  
    Message message = messages[i];  
    System.out.println("---------------------------------");  
    System.out.println("Email Number " + (i + 1));  
    System.out.println("Subject: " + message.getSubject());  
    System.out.println("From: " + message.getFrom()[0]);  
    System.out.println("Text: " + message.getContent().toString());  
 System.out.println("Sent Date: " +message.getSentDate()); 
     
  Multipart multipart = (Multipart) message.getContent();  
   
    for (int j = 0; j < multipart.getCount(); j++) {  
     BodyPart bodyPart = multipart.getBodyPart(j);  
     InputStream stream = bodyPart.getInputStream();  
     BufferedReader br = new BufferedReader(new InputStreamReader(stream));  
  
      while (br.ready()) {  
       System.out.println(br.readLine());  
      }  
     System.out.println();  
    }  
 }
   //5) close the store and folder objects  
   emailFolder.close(false);  
   emailStore.close();  
  
  } catch (NoSuchProviderException e) {e.printStackTrace();}   
  catch (MessagingException e) {e.printStackTrace();}  
  catch (IOException e) {e.printStackTrace();}  
 }  
  
 public static void main(String[] args) {  
  
  String host = "smtp.gmail.com";//change accordingly  
  String mailStoreType = "pop3";  
  final String username= "dineshonjava@gmail.com";  
  final String password= "******";//change accordingly  
  
  receiveEmail(host, mailStoreType, username, password);  
  
 }  
}  

JavaMail API Receiving email with attachment




<<Previous <<   || Index ||   >>Next >>









Sending Email with Attachments using JavaMail

Here is an example to send an email with attachment from your machine.One common requirement that developers often have is to send notification emails to an application’s users. In the example i demonstrate the basic use of Java mail API to send html formatted email with attachment.

You need following dependencies (JARS) to be able to send an email:
  • mail.jar
  • activation.jar

Sending email with attachment using JavaMail API
There are total 7 steps for sending attachment with email. They are:
  1. Get the session object
  2. compose message
    messageBodyPart.setText("This is message body");
    
  3. create MimeBodyPart object and set your message text
  4. create new MimeBodyPart object and set DataHandler object to this object
    messageBodyPart = new MimeBodyPart();
    String filename = "D:\Javas\mailapi\salary.log";
    DataSource source = new FileDataSource(filename);
    messageBodyPart.setDataHandler(new DataHandler(source));
    messageBodyPart.setFileName(filename);
    multipart.addBodyPart(messageBodyPart);
    
  5. create Multipart object and add MimeBodyPart objects to this object
  6. set the multiplart object to the message object
    message.setContent(multipart);
    
  7. send message

Create Java Class-

import java.util.*;  
    import javax.mail.*;  
    import javax.mail.internet.*;  
    import javax.activation.*;  
      
    class SendAttachment{  
     public static void main(String [] args){  
      
      String to="admin@dineshonjava.com";//change accordingly  
      final String user="dineshonjava@gmail.com";//change accordingly  
      final String password="******";//change accordingly  
       
      //1) get the session object     
      Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
      
      Session session = Session.getDefaultInstance(props,  
       new javax.mail.Authenticator() {  
       protected PasswordAuthentication getPasswordAuthentication() {  
       return new PasswordAuthentication(user,password);  
       }  
      });  
         
      //2) compose message     
      try{  
        MimeMessage message = new MimeMessage(session);  
        message.setFrom(new InternetAddress(user));  
        message.addRecipient(Message.RecipientType.TO,new InternetAddress(to));  
        message.setSubject("Salary Aleart");  
          
        //3) create MimeBodyPart object and set your message text     
        BodyPart messageBodyPart1 = new MimeBodyPart();  
        messageBodyPart1.setText("Dear User," +
     "\n\n Please find attached file for salary log. This mail tutorial really nice, please try it!!!");  
          
        //4) create new MimeBodyPart object and set DataHandler object to this object      
        MimeBodyPart messageBodyPart2 = new MimeBodyPart();  
      
        String filename = "D:\\Javas\\mailapi\\salary.log";//change accordingly  
        DataSource source = new FileDataSource(filename);  
        messageBodyPart2.setDataHandler(new DataHandler(source));  
        messageBodyPart2.setFileName(filename);  
         
         
        //5) create Multipart object and add MimeBodyPart objects to this object      
        Multipart multipart = new MimeMultipart();  
        multipart.addBodyPart(messageBodyPart1);  
        multipart.addBodyPart(messageBodyPart2);  
      
        //6) set the multiplart object to the message object  
        message.setContent(multipart );  
         
        //7) send message  
        Transport.send(message);  
       
       System.out.println("message sent....");  
       }catch (MessagingException ex) {ex.printStackTrace();}  
     }  
    }  

As you can see in the above example, total 7 steps are followed to send email with attachment. Now run this program by :







<<Previous <<   || Index ||   >>Next >>









Receiving email using JavaMail API

In the previous article, we have looked at sending mail with Java Mail API.Sending e-mail was relatively simple with only one protocol (SMTP) to handle. But Reception involves two protocols, POP3 and IMAP. POP3 is the older protocol, which offers a single queue of mail messages as a single inbox. IMAP is the more modern protocol, which presents mail messages as entries in a hierarchy of folders, one of which will be an inbox.

Java Mail comes with Provider implementations for POP3 and IMAP, and the secure versions of those as POP3S and IMAPS.

For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar

Steps involved in receive mail:

Step 1: Define the mail properties (i.e.) Define the protocol, mail server by using the properties class.

Step 2: Create the session for read the mail with the properties which we already defined.

Step 3: Create and connect the store for read the mail.

Step 4: Define and open the folder which we need to read. Open the folder in read-only mode.

Step 5: Search the unread contents in the specified folder and stored it into messages array.

Step 6: Display the messages.

Example of Receiving email using JavaMail API-

Let's see the example of receiving the mail using java mail api.

import java.io.IOException;  
import java.util.Properties;  
import javax.mail.Folder;  
import javax.mail.Message;  
import javax.mail.MessagingException;  
import javax.mail.NoSuchProviderException;  
import javax.mail.PasswordAuthentication;
import javax.mail.Session;  
import com.sun.mail.pop3.POP3Store;  
import javax.mail.*;
public class ReceiveMail{  
  
 public static void receiveEmail(String pop3Host, String storeType,  
  final String user, final String password) {  
  try {  
   //1) get the session object  
   Properties properties = new Properties();  
   properties.put("mail.store.protocol", "imaps");  
   //Session emailSession = Session.getDefaultInstance(properties);  
    Session emailSession = Session.getDefaultInstance(properties,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(user,password);
    }
   }); 
   //2) create the POP3 store object and connect with the pop server  
   Store emailStore = emailSession.getStore("imaps");
 emailStore.connect("imap.gmail.com","dineshonjava@gmail.com", password);
    
  
   //3) create the folder object and open it  
   Folder emailFolder = emailStore.getFolder("INBOX");  
   emailFolder.open(Folder.READ_ONLY);  
  
   //4) retrieve the messages from the folder in an array and print it  
   Message[] messages = emailFolder.getMessages();  
   for (int i = 0; i < messages.length; i++) {  
    Message message = messages[i];  
    System.out.println("---------------------------------");  
    System.out.println("Email Number " + (i + 1));  
    System.out.println("Subject: " + message.getSubject());  
    System.out.println("From: " + message.getFrom()[0]);  
    System.out.println("Text: " + message.getContent().toString());  
   }  
  
   //5) close the store and folder objects  
   emailFolder.close(false);  
   emailStore.close();  
  
  } catch (NoSuchProviderException e) {e.printStackTrace();}   
  catch (MessagingException e) {e.printStackTrace();}  
  catch (IOException e) {e.printStackTrace();}  
 }  
  
 public static void main(String[] args) {  
  
  String host = "smtp.gmail.com";//change accordingly  
  String mailStoreType = "pop3";  
  final String username= "dineshonjava@gmail.com";  
  final String password= "*******";//change accordingly  
  
  receiveEmail(host, mailStoreType, username, password);  
  
 }  
}  

As you can see in the above example, userid and password need to be authenticated. As, this program illustrates, you can receive email easily but change the username and password accordingly.

Receiving email using JavaMail API



<<Previous <<   || Index ||   >>Next >>


Send an Email via Gmail SMTP

We can send email by using the SMTP server of gmail. It is good if you are don't have any SMTP server and reliable. Here we will learn how to send email through gmail server by SSL (Secured Socket Layer). SSL is basically used for security if you are sending email through gmail server.

For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
 
public class SendMailSSL {
 public static void main(String[] args) {
  Properties props = new Properties();
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.socketFactory.port", "465");
  props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.port", "465");
  final String username="dineshonjava";
  final String password="******";//Change accordingly
  Session session = Session.getDefaultInstance(props,
   new javax.mail.Authenticator() {
    protected PasswordAuthentication getPasswordAuthentication() {
     return new PasswordAuthentication(username,password);
    }
   });
 
  try {
 
   Message message = new MimeMessage(session);
   message.setFrom(new InternetAddress("dineshonjava@gmail.com"));
   message.setRecipients(Message.RecipientType.TO,InternetAddress.parse("admin@dineshonjava.com"));
   message.setSubject("Welcome Mail Tutorial!!!");
   message.setText("Dear User," +
     "\n\n This mail tutorial really nice, please try it!!!");
 
   Transport.send(message);
 
   System.out.println("Mail sent successfully!!!");
 
  } catch (MessagingException e) {
   throw new RuntimeException(e);
  }
 }
}

As you can see in the above example, userid and password need to be authenticated. As, this program illustrates, you can send email easily but change the username and password accordingly. Let's see how to run it once again by simple technique-

Send an Email via Gmail SMTP


Send an Email via Gmail


<<Previous <<   || Index ||   >>Next >>


Sending Email JavaMail API

Here is an example to send a simple email. Here we have used SMPT server via which emails are sent to our destination email address. There are various ways to send email using JavaMail API. For this purpose, you must have SMTP server that is responsible to send mails.

You can use one of the following techniques to get the SMTP server:
  • Install and use any SMTP server such as Postcast server, Apache James server, gmail server etc. (or)
  • Use the SMTP server provided by the host provider e.g. my SMTP server is mail.dineshonjava.com (or)
  • Use the SMTP Server provided by other companies e.g. gmail etc.
Here, we are going to learn above three aproches to send email using javamail API. But we should learn the basic steps to send email from java application.

To send a simple email steps followed are:
  1. Get the session object that stores all the information of host like host name, username, password etc.
  2. compose the message
  3. send the message

Get the session object
The javax.mail.Session class provides two methods to get the object of session, Session.getDefaultInstance() method and Session.getInstance() method. You can use anyone method to get the session object.

Examples of these methods are as follows:

1.Syntax of getDefaultInstance() method
There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session.
public static Session getDefaultInstance(Properties props)  
public static Session getDefaultInstance(Properties props,Authenticator auth)  
Example of getDefaultInstance() method
Properties properties=new Properties();  
//fill all the informations like host name etc.  
Session session=Session.getDefaultInstance(properties,null); 
2.Syntax of getInstance() method
There are two methods to get the session object by using the getInstance() method. It returns the new session.
public static Session getInstance(Properties props)  
public static Session getInstance(Properties props,Authenticator auth)  
Example of getDefaultInstance() method
Properties properties=new Properties();  
//fill all the informations like host name etc.  
Session session=Session.getInstance(properties,null);

Compose the message
The javax.mail.Message class provides methods to compose the message. But it is an abstract class so its subclass javax.mail.internet.MimeMessage class is mostly used.

To create the message, you need to pass session object in MimeMessage class constructor.

For example:
MimeMessage message=new MimeMessage(session); 

Now message object has been created but to store information in this object MimeMessage class provides many methods. Let's see methods provided by the MimeMessage class:

Commonly used methods of MimeMessage class
  • public void setFrom(Address address): is used to set the from header field.
  • public void addRecipients(Message.RecipientType type, String addresses): is used to add the given address to the recipient type.
  • public void setSubject(String subject): is used to set the subject header field.
  • public void setText(String textmessage) is used to set the text as the message content using text/plain MIME type.
Example to compose the message:
MimeMessage message=new MimeMessage(session);  
message.setFrom(new InternetAddress("dineshonjava@gmail.com"));  
message.addRecipient(Message.RecipientType.To,   
new InternetAddress("admin@dineshonjava.com"));  
message.setHeader("Wecome to JAVAMail Tutorial");  
message.setText("Hi Users, This is java mail tutorial...");

Send the message
The javax.mail.Transport class provides method to send the message.

Commonly used methods of Transport class
  • public static void send(Message message): is used send the message.
  • public static void send(Message message, Address[] address): is used send the message to the given addresses.

Example to send the message:
Transport.send(message); 

Sending Simple Email Example-

Create Java Class
Create a java class file SendEmail, the contents of which are as follows:
JavaMail – GMail via TLS
Send an Email via Gmail SMTP server using TLS connection.
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
   public static void main(String[] args) {
      // Recipient's email ID needs to be mentioned.
      String to = "dinesh.mca.jss@gmail.com";

      // Sender's email ID needs to be mentioned
      String from = "dineshonjava@gmail.com";
      final String username = "dineshonjava";//change accordingly
      final String password = "*****";//change accordingly

      // Assuming you are sending email through relay.jangosmtp.net
      String host = "smtp.gmail.com";

        Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

      // Get the Session object.
      Session session = Session.getInstance(props,
         new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
               return new PasswordAuthentication(username, password);
    }
         });

      try {
    // Create a default MimeMessage object.
    Message message = new MimeMessage(session);
 
    // Set From: header field of the header.
    message.setFrom(new InternetAddress(from));
 
    // Set To: header field of the header.
    message.setRecipients(Message.RecipientType.TO,
               InternetAddress.parse(to));
 
    // Set Subject: header field
    message.setSubject("Testing Subject");
 
    // Now set the actual message
    message.setText("Hello, this is sample for to check send " +
  "email using JavaMailAPI ");

    // Send message
    Transport.send(message);

    System.out.println("Sent message successfully....");

      } catch (MessagingException e) {
         throw new RuntimeException(e);
      }
   }
}

Email JavaMail API

For sending the email using JavaMail API, you need to load the two jar files:
  • mail.jar
  • activation.jar
Sending Email JavaMail API



<<Previous <<   || Index ||   >>Next >>









JavaMail API Core Classes

The JavaMail API consists of some interfaces and classes used to send, read, and delete e-mail messages. Though there are many packages in the JavaMail API, will cover the main two packages that are used in Java Mail API frequently: javax.mail and javax.mail.internet package. These packages contain all the JavaMail core classes.

There are two packages that are used in Java Mail API: javax.mail and javax.mail.internet package. These packages contains many classes for Java Mail API. They are:
  • javax.mail.Session class
  • javax.mail.Message class
  • javax.mail.internet.MimeMessage class
  • javax.mail.Address class
  • javax.mail.internet.InternetAddress class
  • javax.mail.Authenticator class
  • javax.mail.PasswordAuthentication class
  • javax.mail.Transport class
  • javax.mail.Store class
  • javax.mail.Folder class etc.
Session Class-
The Session class is the primary class of the JavaMail API and it is not subclassed. The Session object acts as the connection factory for the JavaMail API, which handles both configuration setting and authentication.

Session object can be created in the following ways:

1. By looking up the administered object stored in the JNDI service
InitialContext ctx = new InitialContext();
Session session = (Session) ctx.lookup("usersMailSession");
usersMailSession is the JNDI name object used as the administered object for the Session object. usersMailSession can be created and configured with the required parameters as name/value pairs, including information such as the mail server hostname, the user account sending the mail, and the protocols supported by the Session object.

2. Another method of creating the Session object is based on the programmatic approach in which you can use a java.util.Properties object to override some of the default information, such as the mail server name, username, password, and other information that can be shared across your entire application.

The constructor for Session class is private. Hence the Session class provides two methods (listed below) which get the Session object.

3. getDefaultInstance(): There are two methods to get the session object by using the getDefaultInstance() method. It returns the default session.
public static Session getDefaultInstance(Properties props)
public static Session getDefaultInstance(Properties props,Authenticator auth)
4. getInstance(): There are two methods to get the session object by using the getInstance() method. It returns the new session.
public static Session getInstance(Properties props)
public static Session getInstance(Properties props,Authenticator auth)

Message Class
With Session object created we now move on to creating a message that will be sent. The message type will be javax.mail.Message.

1. Message is an abstract class. Hence its subclass javax.mail.internet.MimeMessage class is mostly used.

2. To create the message, you need to pass session object in MimeMessage class constructor.
For example:
MimeMessage message=new MimeMessage(session);

3. Once the message object is created we need to store information in it. Message class implements the javax.mail.Part interface while javax.mail.internet. MimeMessage implements javax.mail.internet.MimePart. You can either use message.setContent() or mimeMessage.setText() to store the content.

4. Commonly used methods of MimeMessage class are
  • public void setFrom(Address address) used to set the from header field.
  • public void addRecipients(Message.RecipientType type, String addresses) used to add the given address to the recipient type.
  • public void setSubject(String subject) used to set the subject header field.
  • public void setText(String textmessage) used to set the text as the message content using text/plain MIME type.

Address Class
Now that we have a Session and Message (with content stored in it) objects, we need to address the letter by using Address object.

Address is an abstract class. Hence its subclass javax.mail.internet.InternetAddress class is mostly used.

1. Address can be created by just passing email address:
Address address = new InternetAddress("admin@gmail.com"); 
2. Another way of creating Address is by passing name alogwith the email address:
Address address = new InternetAddress("admin@gmail.com", admin); 
3. You can also set the To, From, CC, BCC fields as below
message.setFrom(address)
message.addRecipient(type, address)
4. Three predefined address types are objects with one of these values:
Message.RecipientType.TO
Message.RecipientType.CC
Message.RecipientType.BCC
Authenticator Class
The class Authenticator represents an object that knows how to obtain authentication for a network connection. Usually, it will do this by prompting the user for information.

Authenticator is an abstract class. You create a subclass PasswordAuthentication, passing a username and password to its constructor.

You must register the Authenticator with the Session when you create session object.

Following is an example of Authenticator use:
Properties props = new Properties();
//Override props with any customized data
PasswordAuthentication auth = new PasswordAuthentication("admin", "root")
Session session = Session.getDefaultInstance(props, auth);

Transport Class
Transport class is used as a message transport mechanism. This class normally uses the SMTP protocol to send a message.

1. It is an abstract class.

2. You can use the default version of the class by just calling the static send() method:
Transport.send(message);
3. The other way to send message is by getting a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection:
message.saveChanges(); // implicit with send()
//Get transport for session
Transport transport = session.getTransport("smtp");
//Connect
transport.connect(host, username, password);
//repeat if necessary
transport.sendMessage(message, message.getAllRecipients());
//Done, close the connection
transport.close();

Store Class
An abstract class that models a message store and its access protocol, for storing and retrieving messages. Subclasses provide actual implementations. Store extends the Service class, which provides many common methods for naming stores, connecting to stores, and listening to connection events.

Clients gain access to a Message Store by obtaining a Store object that implements the database access protocol. Most message stores require the user to be authenticated before they allow access. The connect method performs that authentication.
Store store = session.getStore("pop3");
store.connect(host, username, password);

Folder Class
Folder is an abstract class that represents a folder for mail messages. Subclasses implement protocol specific Folders. Folders can contain subfolders as well as messages, thus providing a hierarchical structure.

After connecting to the Store, you can then get a Folder, which must be opened before you can read messages from it.
Folder folder = store.getFolder("INBOX");
folder.open(Folder.READ_ONLY);
Message message[] = folder.getMessages();

The getFolder(String name) method for a Folder object returns the named subfolder. Close the both the Store and Folder connection once reading mail is done.




<<Previous <<   || Index ||   >>Next >>




JavaMail API Environment Setup

You will install Sun's JavaMail reference implementation .After you install the Sun's JavaMail reference then introduce the demonstration programs that come with the reference implementation.

Then using the some special Task to established JavaMail API Environment setup:

Task 1: firstly Download the latest version of the JavaMail Implementation from Sun.

Task 2: After JavaMail download to latest version for JavaBeans Activation Framework from Sun.

Task 3: Then both downloaded packages Unzip. you get the ZIP file for all platform for both packages.

Task 4: using the jar tool to Unzip these packages .

Task 5: Add the mail.jar file from the JavaMail 1.5 download and the activation.jar file from the JavaBeans Activation Framework download to your CLASSPATH.

Task 6: Then total files copy into your extension library directory. The default installation copy using for Microsoft Windows, the command look like the following:


cd \javamail-1.2
copy mail.jar \jdk\jre\lib\ext
cd \jaf-1.0.1
copy activation.jar \jdk\jre\lib\ext

Task 7:After that Go into the demo directory. The demo directory comes with the JavaMail API implementation and compile to the msgsend program to send a test message.

Task 8:The msgsend program compile to javac msgsend.java

Task 9:Execute the program passing in a from address with the -o option, your SMTP server with the -M option, and the to address (with no option). You'll then enter the subject, the text of your message, and the end-of-file character (CTRL-Z) to signal the end of the message input.

Task 10: Then lastly check to make sure your message received with normal mail reader (Eudora, Outlook Express, pine,etc.

SMPT server
To send emails, you must have SMTP server that is responsible to send mails. You can use one of the following techniques to get the SMTP server:

Install and use any SMTP server such as Postfix server (for Ubuntu), Apache James server (Java Apache Mail Enterprise Server)etc. (or)

Use the SMTP server provided by the host provider for eg: free SMTP provide by JangoSMTP site is relay.jangosmtp.net (or)

Use the SMTP Server provided by companies e.g. gmail, yahoo, etc.





<<Previous <<   || Index ||   >>Next >>









Java Mail API Tutorial

Java Mail API Tutorial
The JavaMail API provides a platform-independent and protocol-independent framework to build mail and messaging applications. The JavaMail API is available as an optional package for use with the Java SE platform and is also included in the Java EE platform.

The JavaMail is an API that is used to compose, write and read electronic messages (emails).

The JavaMail API provides protocol-independent and plateform-independent framework for sending and receiving mails.

The javax.mail and javax.mail.activation packages contains the core classes of JavaMail API.

The JavaMail facility can be applied to many events. It can be used at the time of registering the user (sending notification such as thanks for your interest to my site), forgot password (sending password to the users email id), sending notifications for important updates etc. So there can be various usage of java mail api.


Following are some of the protocols supported in JavaMail API:


  • SMTP: Acronym for Simple Mail Transfer Protocol. It provides a mechanism to deliver email.
  • POP: Acronym for Post Office Protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. RFC 1939 defines this protocol.
  • IMAP: Acronym for Internet Message Access Protocol. It is an advanced protocol for receiving messages. It provides support for multiple mailbox for each user, in addition to, mailbox can be shared by multiple users. It is defined in RFC 2060.
  • MIME: Acronym for Multipurpose Internet Mail Extensions. . It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822, RFC 2045, RFC 2046, and RFC 2047. As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs.
  • NNTP and Others:There are many protocols that are provided by third-party providers. Some of them are Network News Transfer Protocol (NNTP), Secure Multipurpose Internet Mail Extensions (S/MIME) etc.

Architecture
As said above the java application uses JavaMail API to compose, send and receive emails.The following figure illustrates the architecture of JavaMail:
Java Mail API

The abstract mechanism of JavaMail API is similar to other J2EE APIs, such as JDBC, JNDI, and JMS. As seen the architecture diagram above, JavaMail API is divided into two main parts:


  • An application-independent part: An application-programming interface (API) is used by the application components to send and receive mail messages, independent of the underlying provider or protocol used.
  • A service-dependent part: A service provider interface (SPI) speaks the protocol-specific languages, such as SMTP, POP, IMAP, and Network News Transfer Protocol (NNTP). It is used to plug in a provider of an e-mail service to the J2EE platform.

Table of Contents-
  1. JavaMail API Environment Setup
  2. JavaMail API Core Classes
  3. Sending Email JavaMail API
  4. Sending Email through Gmail Server
  5. JavaMail API Receiving email
  6. JavaMail API Sending email with attachment
  7. JavaMail API Receiving email with attachment
  8. JavaMail API Sending email with Html content
  9. JavaMail API  Sending Email With Inline Images
  10. JavaMail API Forwarding Emails
  11. JavaMail API Deleting Emails
  12. JavaMail API Replying Emails
  13. JavaMail API Authentication





<<Previous <<   || Index ||   >>Next >>









Servlets - Database Access Example

Accessing Database from servlets through JDBC! Accessing Access Database From Servlet This article shows you how to access database from servlets.

Create Table

To create the Users table in TEST database, use the following steps:


Create Table
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `age` bigint(20) DEFAULT NULL,
  `gender` varchar(255) DEFAULT NULL,
  `Hobbies` varchar(255) DEFAULT NULL,
  `jobtype` varchar(255) DEFAULT NULL,
  `username` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1


We are assuming there are many records in this table. In this example, we are getting the data from the database in servlet and printing it. We are doing all the database logic in servlet for simplicity of the program. But it will be better to separate it from the servlet file.

Example of Fetching Result-
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.net.*;

public class ServletData extends HttpServlet{
   Connection theConnection;
   private ServletConfig config;

public void init(ServletConfig config)
  throws ServletException{
   this.config=config;
   }

public void service (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {

   HttpSession session = req.getSession(true);

   res.setContentType("text/html");

   PrintWriter out = res.getWriter();

   out.println("<HTML><HEAD><TITLE>Emai List.</TITLE>");

   out.println("</HEAD>");

   out.println("<BODY bgColor=blanchedalmond text=#008000 topMargin=0>");

   out.println("<P align=center><FONT face=Helvetica><FONT color=fuchsia style=\"BACKGROUND-COLOR: white\"><BIG><BIG>List of users.</BIG></BIG></FONT></P>");

  out.println("<P align=center>");

out.println("<TABLE align=center border=1 cellPadding=1 cellSpacing=1 width=\"75%\">");

 

  out.println("<TR>");

  out.println("<TD>ID</TD>");

  out.println("<TD>AGE</TD>");
out.println("<TD>GENDER</TD>");
out.println("<TD>Hobbies</TD>");
out.println("<TD>jobtype</TD>");
  out.println("<TD>username</TD></TR>");

try{


   //Loading Sun's JDBC ODBC Driver 
   Class.forName("com.mysql.jdbc.Driver");
 

   //Connect to emaildb Data source
   theConnection = DriverManager.getConnection("jdbc:mysql://localhost:3306/DOJDB", "root", "root");
 

   Statement theStatement=theConnection.createStatement();

   ResultSet theResult=theStatement.executeQuery("select * from user"); //Select all records from user table.

  //Fetch all the records and print in table
  while(theResult.next()){

   out.println();

   out.println("<TR>");

   out.println("<TD>" + theResult.getString(1) + "</TD>");

   out.println("<TD>" + theResult.getString(2) + "</TD>");

   String s=theResult.getString(3);

   out.println("<TD><a href=" + s + ">" + s + "</a></TD>");
 out.println("<TD>" + theResult.getString(4) + "</TD>");
 out.println("<TD>" + theResult.getString(5) + "</TD>");
 out.println("<TD>" + theResult.getString(6) + "</TD>");
   out.println("</TR>");

  }

  theResult.close();//Close the result set

  theStatement.close();//Close statement

  theConnection.close(); //Close database Connection

  }catch(Exception e){

   out.println(e.getMessage());//Print trapped error.

  }

  out.println("</TABLE></P>");

  out.println("<P>&nbsp;</P></FONT></BODY></HTML>");

 }

  public void destroy(){

  }

}


Servlets - Database Access




<<Previous <<   || Index ||   >>Next >>