Sending Emails in Java using GMail ID

      

Thought of sharing following code with you all. It is a small code snippet that uses SMTP in Java to login into GMail and send email using ones GMail account.

String host = "smtp.gmail.com";
    String from = "username";
    String pass = "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 = {"to@gmail.com"}; // added this line

    Session session = Session.getDefaultInstance(props, null);
    MimeMessage message = new MimeMessage(session);
    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]);
    }
    System.out.println(Message.RecipientType.TO);

    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");
    message.setText("Welcome to JavaMail");
    Transport transport = session.getTransport("smtp");
    transport.connect(host, from, pass);
    transport.sendMessage(message, message.getAllRecipients());
    transport.close();

The code is pretty much self explanatory. Add your GMail username and password in line 7 and 8.

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

And also add the recepient email address in to array in line 12.

String[] to = {"to@gmail.com"}; // added this line

Facebook  Twitter      Stumbleupon  Delicious
  

4 Comments on “Sending Emails in Java using GMail ID”

  • manoj wrote on 4 August, 2009, 10:53

    hello

  • manoj wrote on 4 August, 2009, 10:54

    hay i am patel manoj

  • Sivasubramaniam Arunachalam wrote on 30 November, 2009, 6:05

    Can you give us the associated JARs or the complete import statements?

  • suesi Tran wrote on 29 December, 2009, 14:58

    Please send the jar file to my mail too: embedzit@gmail.com

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.