Friday, September 20, 2013

A simple way to send your mails in Java; Java Mail API

I had played around with Java Mail API last year for a competition (while I was in college) where my team was assigned to build a system which would send bulk mail customized by the sender to a list of recipents as per their age and gender. I built the core messaging system in fifteen minutes or so, thanks to Java Mail!

Though Java Mail is said to be more complicated and low-level than any (most) other Java APIs around. I found sending a simple email pretty easy.

The entire source code (which is comfortably small) can be divided into specific part;

1) Properties of E-Mail Service:

Here, I've setup the properties initializing them in the Properties object - java.util.Properties, provided by the Utility Class - java.util.

        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");

2) Starting the Session by logging in using the Authenticator from JavaMail.

          Session session = Session.getDefaultInstanc (props,new  javax.mail.Authenticator()
            {protected PasswordAuthentication getPasswordAuthentication()
             {
                 return new PasswordAuthentication(target_email,password);
             }
            }
        );

Here, you'll need to enter your EMail service provider Username (with the postfix @yourhost.com) and the password. I used a Class attribute to keep the password, sender email ID and the recipents email address.

    public static String password = "mypassword";
    public static String sender_email = "iam.legend.n@gmail.com";
    public static String recipent_email = "md.naseem.ashraf@gmail.com";

A better way of fashioning this code is by setting up these attributes as private and keeping an Arraylist of recipent's email address which would be fetched, altered and mainteained separately.

3) Sending the MIME Message (the actual E-Mail message):


try {
        Message message = new MimeMessage(session);

        message.setFrom(new InternetAddress(sender_email));
        message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(reciever_email));

        message.setSubject("EMail Subject!!");

        message.setText("Congratulations!!" +
                        "\nYour EMail has been successfuly recieved by this EMail client.");

        Transport.send(message);
        System.out.println("Message Sent!!");       
        }

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

This block of code is self-explanatory. Some specific options I'd like to talk about, required to customize our E-Mails are:

1. message.addHeader(String ....)

Useful to add headers to E-Mails which are used by E-Mail Clients to sort, classify and identify emails. This is pretty useful now a days with GMail's new layout where E-Mails are classified as Standard, Social (Group, Mailing Lists etc) and Promotions (Advertisements) under respective tabs.

Though I'm finding it annoying in the new layout to open multiple emails simultaneously in separate tabs. Thus, I stick to basic HTML layout which has the plus point of being super fast.

2. Message.RecipientType.XX - You can set, TO (To a single prime recipient), CC (Carbon Copies) and BCC (Blind Carbon Copies) in the Recipient Type.

Example:

message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(reciever_email));

message.setRecipients(Message.RecipientType.CC,InternetAddress.parse(another_email));

3. message.setFrom(X) - You can also set the sender email address specifically in the mail even though it will be identified by the EMail client.

Example:

message.setFrom(new InternetAddress(sender_email));

Note that the string sender_email usage with InternetAddress.

CONGRATULATIONS!!


You've setup your Java program to send E-Mails. Some of the ways you can put added functionalities would be by creating a good String creation method which would arrange the message text and then add to "message.setText(...)" method.

I'll be soon studying about recieving and processing E-mail with JavaMail. Will blog about it later.

ADDENDUM:

Source code is added here -
https://docs.google.com/file/d/0B4e1TZA7mwrNV01rTDBrQVluc3M/edit?usp=sharing

No comments:

Post a Comment