Thursday 15 August 2013

How to send email using Java and Gmail smtp server?

Send verification link to email or send an email for verification.

Sending an email from your java code is quite simple. If you need to send multiple emails or email for multiple users (cc/bcc) the best and simplest way is to use the already available java mail api for the purpose.

The javax.mail jar contains many classes that deals with various aspects of emailing, the MIME helps you configure properties of the email content, the BodyPart enables content to be send in body, the Message covers over all content and etc.

Now, before starting you should know about SMTP.

An SMTP stands for Simple Mail Transfer Protocol that establishes and configure the mail server, for our example we will be using easily available Gmail SMTP server. Before you start sending emails you need to configure your SMTP server and set properties according to our requirements.

Also, check if the SMTP port on your system is open and available, the common port for SMTP server is 25. In case it is blocked by admin you may configure it using one of the good resources freely available on internet - Mercury

All setup, let's get started:

//System properties
Properties props = new Properties(); 

// Setup our mail server
props.put("mail.smtp.host", SMTP_HOST); 

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

props.put("mail.smtp.ssl.enable", "true");

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

props.put("mail.debug", "true");

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

props.put("mail.smtp.starttls.enable","true");

props.put("mail.smtp.EnableSSL.enable","true");

props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");  

props.setProperty("mail.smtp.socketFactory.fallback", "false");  

props.setProperty("mail.smtp.port", "465");  

props.setProperty("mail.smtp.socketFactory.port", "465");

Now, SMTP_HOST  is gmail, FROM_ADDRESS is the sender's email address, TO_ADDRESS is the receiver's email and so configure all of them in our private variables:

private String SMTP_HOST = "smtp.gmail.com"; 

private String FROM_ADDRESS = "youremail@gmail.com"; 

private String FROM_PASSWORD = "yourgmailpassword";

private String TO_ADDRESS = "anotheremail@gmail.com";

private String FROM_NAME = "CodeHunk Email Verification"; 

private String SERVER_URL= "http://localhost:8080/EmailServer/EmailServlet?"; 

You see that we are using our own localhost server where we will want the user to be redirected once he clicks the verification link received in his email.

Next, setup our Message and MIME.

//Session object.

Session session = Session.getInstance(props, new AuthorizeEmail()); 

//PasswordAuthentication validates the user at first

class AuthorizeEmail extends Authenticator { 
   @Override 
   protected PasswordAuthentication getPasswordAuthentication() { 
      return new PasswordAuthentication(FROM_ADDRESS, FROM_PASSWORD); 
   } 
}

try{

  // Get the default Mime object.
  MimeMessage message = new MimeMessage(session);//if only text
  // Set our FromAddress.
  message.setFrom(new InternetAddress(FROM_ADDRESS));
  // Set our ToAddress.
  message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
  // Set our subject for the mail.
  message.setSubject("CodeHunk Email Verification Test");
}


If you wish to send email to many people you can add "Message.RecipientType.CC" or "Message.RecipientType.BCC" in your addRecipient field.

The next thing is to set the message string, you can use html in your string and that's perfectly legal and fine.

// Now set the actual message
String verificationID= "verificationID=100";
String htmlMessageContent = "<h3 align='center'>In order to proceed with CodeHunk registration click the link.</h3> <br> <h4 align = 'center' \"background-color:cyan\">Verification link: <a href = \""+SERVER_URL+verificationID+"\">Click to verify your email</a></h4>";



The verificationID will ensure only the receiver clicked the link

//for the moment we comment out below line
//message.setText(htmlMessageContent, "text/html");
//set "text/plain" if you don't need html in your message



If you need to send images also in your email you can also do that:
Let's take this image for our email:
// Create the message part for SENDING IMAGE
//This HTML mail have to 2 part, the BODY and the embedded image
MimeMultipart multipart = new MimeMultipart("related");

// first part  (the html)
BodyPart messageBodyPart = new MimeBodyPart();
String htmlText = "<H3 ><font color=\"red\" face=\"Comic sans MS\" size=\"2\">Hello CodeHunk Visitor!</font></H3><center><img src=\"cid:image\"></center><br>" + htmlMessageContent;
messageBodyPart.setContent(htmlText, "text/html");


It is important to give your image an id like cid:image


// add it
multipart.addBodyPart(messageBodyPart);

// second part (the image)
messageBodyPart = new MimeBodyPart();
messageBodyPart.setDisposition(MimeBodyPart.INLINE);// show image with msg content
DataSource dataSource = new FileDataSource("D:\\hello.jpg");
messageBodyPart.setDataHandler(new DataHandler(dataSource));
messageBodyPart.setHeader("Content-ID","<image>");

// add it
multipart.addBodyPart(messageBodyPart);

// put everything together
message.setContent(multipart);


//finally send our email:
 Transport.send(message);


Finally, let's put everything together at one place.

The SendEmail Class:

package com.codehunk.email;

import java.util.HashMap;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
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;



/**
 * 
 * @author Atif Imran 2013
 * @blog codehunk.blogspot.in
 * @website www.strizen.com
 *
 */

public class SendEmail {
 private String SMTP_HOST = "smtp.gmail.com";  
 private String FROM_ADDRESS = "youremail@gmail.com";  
 private String FROM_PASSWORD = "yourpassword";
 private String TO_ADDRESS = "anotheremail@gmail.com";  
 private String FROM_NAME = "CodeHunk Email Verification";  
 private String SERVER_URL = "http://localhost:8080/EmailServer/EmailServlet?";  


 //PasswordAuthentication validates the user at first
 class AuthorizeEmail extends Authenticator {  
  @Override  
  protected PasswordAuthentication getPasswordAuthentication() {  
   return new PasswordAuthentication(FROM_ADDRESS, FROM_PASSWORD);  
  }  
 }

 public static void main(String[] args){
  SendEmail se = new SendEmail();
  se.sendEmail();
 }

 public void sendEmail(){
  //verify a user before registering

  // System properties
  Properties props = new Properties();  

  // Setup our mail server
  props.put("mail.smtp.host", SMTP_HOST);  
  props.put("mail.smtp.user",FROM_NAME); 
  props.put("mail.smtp.ssl.enable", "true"); 
  props.put("mail.smtp.port", "25"); 
  props.put("mail.debug", "true"); 
  props.put("mail.smtp.auth", "true"); 
  props.put("mail.smtp.starttls.enable","true"); 
  props.put("mail.smtp.EnableSSL.enable","true");
  props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");   
  props.setProperty("mail.smtp.socketFactory.fallback", "false");   
  props.setProperty("mail.smtp.port", "465");   
  props.setProperty("mail.smtp.socketFactory.port", "465"); 



  // Session object.
  Session session = Session.getInstance(props, new AuthorizeEmail());  

  try{
   // Get the default Mime object.
   MimeMessage message = new MimeMessage(session);//if only text
   // Set our FromAddress.
   message.setFrom(new InternetAddress(FROM_ADDRESS));
   // Set our ToAddress.
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(TO_ADDRESS));
   // Set our subject for the mail.
   message.setSubject("CodeHunk Email Verification Test");


   // Now set the actual message
   String verificationID= "verificationID=100";
   String htmlMessageContent = "

In order to proceed with CodeHunk registration click the link.

Verification link: Click to verify your email

"; //for the moment we comment out below line //message.setText(htmlMessageContent, "text/html"); //set "text/plain" if you don't need html in your message // Create the message part for SENDING IMAGE // This HTML mail have to 2 part, the BODY and the embedded image MimeMultipart multipart = new MimeMultipart("related"); // first part (the html) BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "

Hello CodeHunk Visitor!

" + htmlMessageContent; messageBodyPart.setContent(htmlText, "text/html"); // add it multipart.addBodyPart(messageBodyPart); // second part (the image) messageBodyPart = new MimeBodyPart(); messageBodyPart.setDisposition(MimeBodyPart.INLINE);// show image with msg content DataSource dataSource = new FileDataSource("D:\\hello.jpg"); messageBodyPart.setDataHandler(new DataHandler(dataSource)); messageBodyPart.setHeader("Content-ID",""); // add it multipart.addBodyPart(messageBodyPart); // put everything together message.setContent(multipart); // Send message Transport.send(message); }catch (MessagingException mex) { System.out.println("MessagingException: "+mex.getMessage()); mex.printStackTrace(); } } }
The EmailServlet:

package com.codehunk.email;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class EmailServlet
 */
public class EmailServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmailServlet() {
        super();
    }

 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  //check if the parameter contains verificationID
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  if(request.getParameter("verificationID")!=null && request.getParameter("verificationID").equals("100")){
   out.write(""+
     "Success"+
     "

Email successfully verified!

"); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }

The Result:




When verification link is clicked:




That's all. I hope you've enjoyed it. Cheers ;)
Read more »

Tuesday 2 July 2013

Mavenize your BlackBerry project

How to create and build your BlackBerry project through Maven?

I was recently faced with a situation where it was required to mavenize my BlackBerry project. The purpose was to get automated builds through Hudson.

The problem: There isn't any Maven plugin for BlackBerry!
The solution: Get it done manually.

So here's what I did:
Since there wasn't any plugin I realized that I needed to manually create a maven structure and then use command line to build it.
Once I had created the structure and completed the initial steps I was faced with an even bigger issue.
The localization I used in my project won't compile and package through maven.
BlackBerry application creates .crb files against its localization files. Somehow these files are not generated through maven and so the application is not packaged.
The work around I used was to create a .properties file for my localization and put my localized strings in it like a key-value pair. The pom.xml file should add plugin for these resource files to be incuded in the build.
Now we know our work arounds, its time to start with coding.

The BlackBerry Maven project requires the following prerequisites to be achieved.

System Requirements:
  • Java SE JDK v6.0
  • Eclipse 3.4 (the JDE plugin does not run on 3.5 yet)
  • Windows 2000 SPI or later, or Windows XP
  • Windows Vista (BlackBerry JDE v4.2.1 and higher)
  • Monitor with a resolution of 1024 x 768 or higher
Development setup:
  • Windows OS (Blackberry tools do not support Linux and Mac OS yet. Cross platform support is finally on the roadmap for some time this year) 
  • Java SE JDK v6.0 (check with java --version on the command line)
  • Eclipse IDE with Blackberry JDE plugin
  • Maven2
  • RIM_JDE_HOME environment variable must be set. This point to the directory where the RIM JDE development environment is installed. On machine this values looks like:
C:\projects\eclipse\plugins\net.rim.eide.componentpack4.5.0_4.5.0.16\components\lib 
OR
D:\EclipseBlackBerry\plugins\net.rim.ejde.componentpack5.0.0_5.0.0.25\components\lib

Maven configuration and installation:
1.       Download Maven from Apache Maven project: http://maven.apache.org/download.html
2.       Extract the zip/tar.gz to the location of your choice. Preferably C:\Program Files
3.       Add PATH to the Environment Variables.
PATH= C:\Program Files\apache-maven-2.2.1\bin;C:\ProgramFiles\Java\jdk1.6.0_21\bin;D:\BlackBerryEclipseIDE\plugins\net.rim.ejde.componentpack5.0.0_5.0.0.25\components\bin

By default when the project is run from the maven .m2 repository is created in the local maven repository C:\Documents and Settings\username\.m2.  This path can be changed in the setting.xml file.
<settings>
  <!-- localRepository
   | The path to the local repository maven will use to store artifacts.
   |
   | Default: ~/.m2/repository
  <localRepository>/path/to/local/repo</localRepository>
  -->

<localRepository>D:/maven_repo</localRepository>


Now we have all the development environment setup. Let’s start with the project.


Setting up Maven Project:
1.       Setup a maven project in your workspace or any other location. Keep in mind that choosing a location like C:\Documents and Settings\username\MyProject will cause trouble as Maven doesn’t recognize any white spaces as we see between “Documents^and^Settings”.
2.       Put the pom.xml file in the project directory.
3.       Create maven like folder structure in the project directory like this:
      • src\main\java
      • src\main\resources       
4.       On the command line (cmd) type mvn eclipse:eclipse
That’s it this should create a mavenized project structure for the moment. It will also create the necessary project settings files. Now open the Eclipse and create a new BlackBerry project using existing source option. Give path to our maven project we created above. The structure should look like this:



v  Create the Java file that contains our code and put it under src/main/java: HelloBB.java
v  Desirably add an icon to the src/main/resources for our project: icon.png
v  Add application configuration file: app.rapc
Run and deploy the application on Simulator:
Run the following command in cmd: mvn clean package. This will create the necessary .cod files that can be run on a simulator using the “Load Java Program” option.


Now, the below figure shows the eclipse project structure that appears finally.

The app.rapc
MIDlet-Name: HelloBB
MIDlet-Version: 1.0
MIDlet-Vendor: Your Name Here
MIDlet-Jar-URL: hellobb.jar
MIDlet-Jar-Size: 0
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
MIDlet-1: ,icon.png,
RIM-MIDlet-Flags-1: 1



The HelloBB.java
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.RichTextField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.container.MainScreen;

public class HelloBB extends UiApplication
{ public static void main(String[] args)
 {
  UiApplication app = new HelloBB();
  app.enterEventDispatcher();
 }
 public void activate()
 {
  this.pushScreen(new HelloBBScreen());
 }
 //create a new screen that extends MainScreen, which provides
 //default standard behavior for BlackBerry applications
 private static final class HelloBBScreen extends MainScreen
 {
         private HelloBBScreen()
         {
                 //invoke the MainScreen constructor
                 super();

                 //add a title to the screen
                 LabelField title = new LabelField("HelloBB", LabelField.ELLIPSIS
                                 | LabelField.USE_ALL_WIDTH);
                 setTitle(title);
                 //add the text "Hello Blackberry!!" to the screen
                 add(new RichTextField("Hello Blackberry!!"));
         }

         //override the onClose() method to display a dialog box to the user
         //with "Goodbye!!" when the application is closed
         public boolean onClose()
         {
             Dialog.alert("Good Bye!!");
             //exits the app cleanly
             System.exit(0);
             return true;
         }
 }
}


The pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.hello.bb</groupId>
<artifactId>hellobb</artifactId>
<name>HelloBB</name>
<packaging>jar</packaging>
<version>1.0</version>
<!--
      Specifies the RIM API version..All RIM device software is backward
      compatible
-->
<properties>
<version.net.rim.api>5.0.0</version.net.rim.api>
      </properties>


      <dependencies>
            <dependency>
                  <groupId>net.rim</groupId>
                  <artifactId>net_rim_api</artifactId>
                  <version>${version.net.rim.api}</version>
                  <scope>system</scope>
                  <systemPath>${env.RIM_JDE_HOME}\net_rim_api.jar</systemPath>
            </dependency>
      </dependencies>
      <build>
            <plugins>
                  <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-eclipse-plugin</artifactId>
                        <configuration>
                              <outputDirectory>bin</outputDirectory>
                        </configuration>
                  </plugin>
                 
<!--makes sure the Application code is JDK 1.2 compliant since that’s what RIM devices mandate-->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
            <source>1.2</source>
            <target>1.2</target>
            </configuration>
</plugin>
<!-- makes proper environmental setup check -->
<plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-antrun-plugin</artifactId>
      <executions><execution>
      <id>OS_Environment_Validation</id>
      <phase>validate</phase>
      <configuration><tasks>
      <property environment="env" />                                               
      <fail message="RIM_JDE_HOME environment variable must be set to the home directory of the Blackberry JDE Environment. For instance, when using the eclipse JDE plugin, it could look something like: C:\projects\eclipse\plugins\net.rim.eide.componentpack4.5.0_4.5.0.16\components">
      <condition><and>
<os family="windows" />
<not><isset property="env.RIM_JDE_HOME" /></not>
      </and></condition>
      </fail>
</tasks></configuration>
      <goals><goal>run</goal></goals>
      </execution>
<execution><id>App_Creation_Deployment</id>
       <phase>package</phase>
         <configuration>
   <tasks>
<property name="preverify_target" value="${basedir}\target\app-binary" />
              <property name="preverify_src"                                                          value="${basedir}\target\${project.artifactId}.jar" />
<property name="rapc_src"                                                                         value="${preverify_target}\${project.artifactId}.jar" />
              <property name="rapc_config" value="${basedir}\app.rapc" />

                  <delete dir="${preverify_target}" />
                  <delete file="${preverify_src}" />
                  <mkdir dir="${preverify_target}" />
                  <jar file="${preverify_src}">
<fileset dir="${basedir}\target\classes" />
                  </jar>
            <echo>Generating the BlackBerry App....</echo>
            <echo>Preverifying....</echo>
                  <exec dir="${preverify_target}" executable="preverify">
<arg line="-classpath ${env.RIM_JDE_HOME}\net_rim_api.jar -d ${preverify_target} ${preverify_src}" />
                  </exec>
           
            <echo>Generating the Executable....</echo>
                  <exec dir="${preverify_target}" executable="rapc">
                  <arg line="import=${env.RIM_JDE_HOME}\net_rim_api.jar codename=${project.name} ${rapc_config} ${rapc_src}" />
                  </exec>
                  <echo>Deploying the App into the Simulator....</echo>
                  <copy todir="${env.RIM_JDE_HOME}\simulator" overwrite="true">
                  <fileset dir="${basedir}\target\app-binary">
                  <include name="*.cod" />
                  <include name="*.debug" />
                  </fileset>
                  </copy>
      <echo>Generating the Desktop Application Loader......</echo>
                  <copy todir="${basedir}\target\app-binary" overwrite="true"
                  file="${basedir}\app.alx"/>              
         </tasks>
         </configuration>
                        <goals><goal>run</goal></goals>
                              </execution>
                        </executions>
                  </plugin>
            </plugins>
      </build>

</project>


Now, we need to update our pom.xml to serve our purpose. Here's what I did:

We need to create a .properties file and use them as our localization bundle files.
Create .properties file in eclipse and fill it with key=value pair for our localization. Create method in class files that fetches localized string from these files whenever required.

Inform maven about the use of properties file.

We need to update the pom.xml as shown:
<!-- add more resources to build project -->
      <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <configuration>
                  <version>2.4</version>
            </configuration>
      </plugin>

The above plugin tag is required to inform maven about the use of resource files in our project.
Now, add the resource file and its location in the pom.xml
<!-- Adding .properties file to project -->
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-2</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>src\main\resources\LocaleBundleES.properties</file>
                <file>src\main\resources\LocaleBundleEN.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
 <!-- Adding .properties file to project  -->


And that's all. Run it through maven. Enjoy :)
Read more »

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Best Web Hosting