Wednesday, March 30, 2011

Send email in Java with attachment

Java Mail API is required to work with this code to send email in Java from your email account with attachments
import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.*;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

public class MailWithAttachment


public static void main(String args[]) throws Exception


    String host = "";//host name

    String from = "";//sender id

    String to = "";//reciever id

    String pass = "***";//sender's password 

    String fileAttachment = "test.txt";//file name for attachment 

    //system properties

    Properties prop = System.getProperties();

    // Setup mail server properties

    prop.put("", host);

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

    prop.put("", host);

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

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

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

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


    Session session = Session.getInstance(prop, null);

    // Define message

    MimeMessage message = new MimeMessage(session);

    message.setFrom(new InternetAddress(from));

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

    message.setSubject("Hello Java Mail Attachment");

    // create the message part 

    MimeBodyPart messageBodyPart = new MimeBodyPart();

    //message body


    Multipart multipart = new MimeMultipart();



    messageBodyPart = new MimeBodyPart();

    DataSource source = new FileDataSource(fileAttachment);

    messageBodyPart.setDataHandler(new DataHandler(source));




    //send message to reciever

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

    transport.connect(host, from, pass);

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




Monday, March 28, 2011

Database Connctions in Java

This example Works with MS Access to explain DB concepts and can be changed accordingly to any other database for that you will need to configure their respective JAR libraries to your project i.e. for MY-SQL you will need MySQL-Connector JAR
import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

public class dbConnections


public static void main(String args[])



      Class.forName("sun.jdbc.odbc.JdbcOdbc");  //load DB drivers

      Connection con=DriverManager.getConnection("jdbc:odbc:DBName",username,pwd);

      //create db connections

      Statement stmt = con.createStatement(); // creates statement for db access

      String query = "SELECT * FROM Job"; // sql query

      ResultSet rs = stmt.executeQuery(query);

      //execute sql query and stores the result in the result set rs

      while( ) {

       System.out.println("Job  "+rs.getString("Job_Id"));


      rs.close(); //close resultset

      stmt.close(); // close statement 

      con.close();  // close connection   


    catch(SQLException e)




    catch(ClassNotFoundException e)






Wednesday, March 16, 2011

Read emails from Gmail Account

This code reads emails from a Gmail account to work with this code you will need javax.mail API






import java.util.Properties;

import javax.mail.*;

public class ReadMail {

  public static void main(String args[]) throws IOException {

         Properties properties = System.getProperties();

         properties.setProperty("", "imaps");

             try {

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

                 //create session instance

                 Store store = session.getStore("imaps");//create store instance

                 store.connect("", "", "****");

                 //set your user_name and password


                 Folder inbox = store.getFolder("inbox");

                 //set folder from where u wants to read mails

       ;//set access type of Inbox

                 Message messages[] = inbox.getMessages();// gets inbox messages

                 for (int i = 0; i < messages.length; i++) {

                System.out.println("------------ Message " + (i + 1) + " ------------");

                System.out.println("SentDate : " + messages[i].getSentDate()); //print sent date

                System.out.println("From : " + messages[i].getFrom()[0]); //print email id of sender

                System.out.println("Sub : " + messages[i].getSubject()); //print subject of email



                      Multipart mulpart = (Multipart) messages[i].getContent();

                      int count = mulpart.getCount();

                      for (int j = 0; j+1 < count; j++)





                catch (Exception ex)


                     System.out.println("Exception arise at get Content");






catch (Exception e) {




  public static void storePart(Part part) throws Exception


          InputStream input = part.getInputStream();

          if (!(input instanceof BufferedInputStream))


              input = new BufferedInputStream(input);


          int i;

         System.out.println("msg : ");

          while ((i = != -1)





Send email using javax.mail source