Saturday, 21 July 2012

Java Mail API Tutorial

Hi Friends.....

I would like to share simple examples on using of the Java Mail Api. I think it will aid to develop very interesting and useful applications.

First of all, we should download mail.jar and activation.jar file and place it in the classpath.

I will provide you three examples that shows overview of usage of this API:

  • Sending a simple Text message.
  • Sending email with Attachments.
  • Sending HTML content Message
I. Sending a Simple Text Email :


package com.navin.emailapp;


import java.util.Properties;
import javax.mail.Message.RecipientType;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
 * @author naveen.k
 */
public class EmailApplication {


    public static void main(String[] args) {
        final String fromEmailId = "sender_emailid@domain.com";
        final String password = "sender_password";
        String host = "smtp_host";
        String portNumber = "smtp_port_number";


        String toEmailId = "receiver_emailid@domain.com";
        String subject = "Testing email";
        String message = "Hi... thist is my first mail                  application";


        Properties pro=new Properties();
        pro.put("mail.smtp.user", fromEmailId);
        pro.put("mail.smtp.host", host);
        pro.put("mail.smtp.port", portNumber);
        pro.put("mail.smtp.starttls.enable", "true");
        pro.put("mail.smtp.auth", "true");
        pro.put("mail.smtp.socketfactory.port", portNumber);
        pro.put("mail.smtp.socketfactory.class","javax.net.ssl.SSLSocketFactory");
        pro.put("mail.smtp.socketfactory.callback", "false");
        try
        {
            Session session=Session.getInstance(pro, null);
            session.setDebug(true);


            MimeMessage msg=new MimeMessage(session);
            msg.setText(message);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(fromEmailId));
            msg.addRecipient(RecipientType.TO, new InternetAddress(toEmailId));
            msg.saveChanges();


            Transport trans=session.getTransport("smtp");
            trans.connect(host, fromEmailId, password);
            trans.send(msg, msg.getAllRecipients());
            trans.close();
        }
        catch(Exception e ){e.printStackTrace(); }
    }


}

II. Sending email with Attachments :


package com.navin.emailapp;


import java.util.Date;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
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;


/**
 * @author naveen.k
 */
public class EmailApplication2 {


    public static void main(String[] args) {


        String fromEmailId = "sender_emailid@domain.com", password = "sender_password",
                host = "smtp_host", port = "smtp_port_number",
                toEmailId = "receiver_emailid@domain.com",
                subject = "Testing attachment email",
                message = "This is my second mail application",
                filename = "d:/test.txt"; 
        
        // if you would like to use the above mention properties, those are applicable here also
        Properties props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        try {
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(true);


            MimeMessage msg = new MimeMessage(session);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(fromEmailId));
            msg.addRecipient(Message.RecipientType.TO, new InternetAddress(toEmailId));

            // create and fill first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            mbp1.setText(message);

            // create second message part
            MimeBodyPart mbp2 = new MimeBodyPart();


            // attach the file to message
            FileDataSource fds = new FileDataSource(filename);
            mbp2.setDataHandler(new DataHandler(fds));
            mbp2.setFileName(fds.getName());


            //create multipart and add contents to it
            MimeMultipart mp = new MimeMultipart();
            mp.addBodyPart(mbp1);
            mp.addBodyPart(mbp2);


            //add multipart to message
            msg.setContent(mp);


            msg.setSentDate(new Date());
            msg.saveChanges();

            Transport transport = session.getTransport("smtp");
            transport.connect(host, fromEmailId, password);
            transport.sendMessage(msg, msg.getAllRecipients());
            transport.close();
        } catch (Exception ex) {ex.printStackTrace();}
    }
}


III. Sending HTML content Messages:


 This example is same as the above examples except setting "javax.mail.internet.MimeMessage" content type to "text/html".


The snippet is provided below, by skipping the entire code to avoid confusion and for making the major part clear..... :)

/**.....  the code is totally same as I example .....**/
           
            MimeMessage msg=new MimeMessage(session);
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress(fromEmailId));
            msg.addRecipient(RecipientType.TO, new InternetAddress(toEmailId));
           
            msg.setContent("<h1>Test HTML content </h1>","text/html");
            msg.saveChanges();

/**.....  the code is totally same as I example .....**/

           


You can find the gmail setting at https://support.google.com/mail/bin/answer.py?hl=en&answer=13287


Download my sample application jar here. Please, maintain the same folder structure and run the 'NaveenEmailApp.jar'.

No comments:

Post a Comment