Showing posts with label Email. Show all posts
Showing posts with label Email. Show all posts

Aug 19, 2012

JavaMail API Part 4 - Using secured protocol

There are many security measures we can implement into the system. We will take a special case of gmail which uses STARTTLS. STARTTLS is an extension to plain text communication protocols, which offers a way to upgrade a plain text connection to an encrypted (TLS or SSL) connection instead of using a separate port for encrypted communication.



Here is the code for sending email using host which implements STARTTLS.

package com.test;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.AddressException;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;


public class SendMail {

   public static void main(String[] args) {

      String host = "smtp.gmail.com";

      String from = "sender@gmail.com";

      String pass = "sender's password";

      Properties props = System.getProperties();

      props.put("mail.smtp.starttls.enable", "true"); // added this line

      props.put("mail.smtp.host", host);

      props.put("mail.smtp.user", from);

      props.put("mail.smtp.password", pass);

      props.put("mail.smtp.port", "587");

      props.put("mail.smtp.auth", "true");

      String[] to = {"recipient1@abc.com, recipient2@abc.com"};

      String fileAttachment = "F:\\emoticons\\yawn.gif";

      Session session = Session.getDefaultInstance(props, null);

      MimeMessage message = new MimeMessage(session);

      try {

         message.setFrom(new InternetAddress(from));

         InternetAddress[] toAddress = new InternetAddress[to.length];

         // To get the array of addresses

         for( int i=0; i < to.length; i++ ) { // changed from a while loop

            toAddress[i] = new InternetAddress(to[i]);

         }

         for( int i=0; i < toAddress.length; i++) { // changed from a while loop

            message.addRecipient(Message.RecipientType.TO, toAddress[i]);

         }

         message.setSubject("sending in a group");

         // create the message part 

         MimeBodyPart messageBodyPart = new MimeBodyPart();

         //fill message

         messageBodyPart.setText("Hi");

         Multipart multipart = new MimeMultipart();

         multipart.addBodyPart(messageBodyPart);

         // Part two is attachment

         messageBodyPart = new MimeBodyPart();

         DataSource source = new FileDataSource(fileAttachment);

         messageBodyPart.setDataHandler(new DataHandler(source));

         messageBodyPart.setFileName(fileAttachment);

         multipart.addBodyPart(messageBodyPart);

         // Put parts in message

         message.setContent(multipart);

         Transport transport = session.getTransport("smtp");

         transport.connect(host, from, pass);

         transport.sendMessage(message, message.getAllRecipients());

         transport.close();

      } catch (AddressException e) {

         e.printStackTrace();

      } catch (MessagingException e) {

         e.printStackTrace();

      }
   }
}

JavaMail API Part 3 - Send attachment in email


Here is an example to send an email with attachment from your machine.

We assume that mail server is running on localhost and is connected to internet to send email.



For prerequisites please refer to my previous article on JavaMail API.


// File Name SendFileEmail.java



import java.util.*;

import javax.mail.*;

import javax.mail.internet.*;

import javax.activation.*;



public class SendFileEmail

{

   public static void main(String [] args)

   {

    

      // Recipient's email ID needs to be mentioned.

      String to = "abcd@gmail.com";

      // Sender's email ID needs to be mentioned

      String from = "web@gmail.com";

      // Assuming you are sending email from localhost

      String host = "localhost";

      // Get system properties

      Properties properties = System.getProperties();

      // Setup mail server

      properties.setProperty("mail.smtp.host", host);

      // Get the default Session object.

      Session session = Session.getDefaultInstance(properties);

      try{
         // Create a default MimeMessage object.

         MimeMessage message = new MimeMessage(session);

         // Set From: header field of the header.

         message.setFrom(new InternetAddress(from));

         // Set To: header field of the header.

         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

         // Set Subject: header field

         message.setSubject("This is the Subject Line!");

         // Create the message part

         BodyPart messageBodyPart = new MimeBodyPart();

         // Fill the message

         messageBodyPart.setText("This is message body");

        

         // Create a multipar message

         Multipart multipart = new MimeMultipart();

         // Set text message part

         multipart.addBodyPart(messageBodyPart);

         // Part two is attachment

         messageBodyPart = new MimeBodyPart();

         String filename = "file.txt";

         DataSource source = new FileDataSource(filename);

         messageBodyPart.setDataHandler(new DataHandler(source));

         messageBodyPart.setFileName(filename);

         multipart.addBodyPart(messageBodyPart);

         // Send the complete message parts

         message.setContent(multipart );

         // Send message

         Transport.send(message);

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

      }catch (MessagingException mex) {

         mex.printStackTrace();

      }

   }

}



Compile and run this program to send an HTML email:

$ java SendFileEmail

Sent message successfully....



User Authentication


If it is required to provide user ID and Password to the email server for authentication purpose then you can set these properties as follows:

props.setProperty("mail.user", "myuser");

props.setProperty("mail.password", "mypwd");



Rest of the email sending mechanism would remain as explained above.

JavaMail API Part 2 - Sending rich text in email

We send simple text in email in previous post in the series. In this article, we will send rich text. For rich text, MIME type is "text/html". The actual mail content is written in HTML. While sending email, HTML contents will be set and content type is set to "text/html".

We assume that mail server is running on localhost and is connected to internet to send email.

For prerequisites please refer to my previous article on JavaMail API.


Using this example, you can send as big as HTML content you like.

// File Name SendHTMLEmail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendHTMLEmail
{
   public static void main(String [] args)
   {
     
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";
      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";
      // Assuming you are sending email from localhost
      String host = "localhost";
      // Get system properties
      Properties properties = System.getProperties();
      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);
      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));
         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
         // Set Subject: header field
         message.setSubject("This is the Subject Line!");
         // Send the actual HTML message, as big as you like
         message.setContent("<h1>This is actual message</h1>", "text/html" );
         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}
Compile and run this program to send an HTML email:

$ java SendHTMLEmail
Sent message successfully....

Aug 18, 2012

JavaMail API Part 1 - Sending simple text email

There are many applications where system has to send an email to the user.
  • Notification
  • Validation
  • Reporting
  • Alarming etc
Sending email though look simple but it has many things to be considered like 
  • Whether email is a rich text or simple text
  • Whether email has attachment
  • Email using authentication
  • Emailing using secured protocols and mechanisms
Let's first take a simple case of sending a simple text email. We can write a simple standalone java application to send email. 

Prerequisites


We will need  JavaMail API and Java Activation Framework (JAF). You can download latest version from Oracle website.

Download and unzip these files, in the newly created top level directories you will find a number of jar files for both the applications. You need to add mail.jar and activation.jar files in your CLASSPATH.

We will also need mail server to send an email. There are many open source mail server we can use or we can use inbuilt mail server from operating system. Let's assume that mail server is running on localhost.

Sending Text Email


Following is the code.

// File Name SendMail.java

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;

public class SendMail
{
   public static void main(String [] args)
   {    
      // Recipient's email ID needs to be mentioned.
      String to = "abcd@gmail.com";
      // Sender's email ID needs to be mentioned
      String from = "web@gmail.com";
      // Assuming you are sending email from localhost
      String host = "localhost";
      // Get system properties
      Properties properties = System.getProperties();
      // Setup mail server
      properties.setProperty("mail.smtp.host", host);
      // Get the default Session object.
      Session session = Session.getDefaultInstance(properties);
      try{
         // Create a default MimeMessage object.
         MimeMessage message = new MimeMessage(session);
         // Set From: header field of the header.
         message.setFrom(new InternetAddress(from));
         // Set To: header field of the header.
         message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
         // Set Subject: header field
         message.setSubject("This is the Subject Line!");
         // Now set the actual message
         message.setText("This is actual message");
         // Send message
         Transport.send(message);
         System.out.println("Sent message successfully....");
      }catch (MessagingException mex) {
         mex.printStackTrace();
      }
   }
}

Compile and run this program to send a simple email:

$ java SendMail
Sent message successfully....


Sending Email to multiple recipient


If you want to send an email to multiple recipients then following methods would be used to specify multiple email IDs:

void addRecipients(Message.RecipientType type, Address [] addresses) MessagingException

Here is the description of the parameters:

  • type: This would be set to TO, CC or BCC. Here CC represents Carbon Copy and BCC represents Black Carbon Copy. Example Message.RecipientType.TO
  • addresses: This is the array of email ID. You would need to use InternetAddress() method while specifying email IDs