Sunday, March 21, 2010

How to send email in Java using Gmail

If you want to send email in java via Gmail then You are at a right place, no need to go anywhere else. Follow the instructions given below.

First download EmailGmail.rar from the download section of my website:
www.siddharthindia.com

Extract it to C: drive as shown in the figure below. You will able to see 3 different jar files in the folder EmailGmail which is inside C:



After this, set the classpath of the above 3 jar files as shown in the figure below.
Copy this line :
C:\EmailGmail\activation.jar;C:\EmailGmail\javaemailgmail.jar;C:\EmailGmail\mail.jar
in the CLASSPATH variable.
After this restart the system.

If you are using IDE like Eclipse or Netbeans then you can simply import all the 3 jar files as shown below. There is no need of setting the class path.


After configuring this much, you need to just copy and paste the below sample program:

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javaemailgmail.EmailGmail;

/**
*
* @author Siddharth
*/
public class Main {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
EmailGmail.GMAIL_USERNAME="username@gmail.com";
//Enter the username as shown above
EmailGmail.GMAIL_PASSWORD="password";
//Enter the password
EmailGmail.EMAIL_DESTINATION_ADDRESS=new String[1];
//to how many mail-id you want to send the message
EmailGmail.EMAIL_DESTINATION_ADDRESS[0]="siddharthanandx@gmail.com";
//destination address
EmailGmail.GMAIL_SUBJECT="Test Mail";
//Enter suitable subject
EmailGmail.GMAIL_BODY_MESSAGE="Hello";
//Enter the message
EmailGmail.PLAIN_TEXT_MESSAGE=false;
// if the above is set to false, you can send messages including html tags.
EmailGmail.PLAIN_TEXT_MESSAGE_WITH_ATTACHMENT=false;
// if the above is true then you can send attachment with plain text but not html text
EmailGmail.HTML_MESSAGE=true;
// set the above to false if u want to send simple text message without html tags
EmailGmail.GMAIL_ATTACHMENT="D:\\EmailGmail\\card.jpg";
//Give the full path of the attachment, notice the double backslash, be careful.
EmailGmail.DEBUG_MODE=true;
//if this is false you will not be able to see the outputs of each and every step while mail is being sent in the command line
EmailGmail eg = new EmailGmail();
eg.send();
}

}

CAUTION: If you are still unable to send email then try disabling the firewall and antivirus.