Tuesday, March 3, 2009

java : simple program to send mails using Gmail (ie javamail API)

Here is the code to send mail using gmail

Note: to run this code u need to download JavaMail 1.4.2  jar files

/*Here is the complete tested code for Gmail.java */

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

public class Gmail
{
public static void main(String[] args)
{
Properties props = new Properties();
props.put("mail.smtp.user","madan712@gmail.com");
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.port","465");

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

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

props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback","false");

try
{
Session session = Session.getDefaultInstance(props, null);
session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setSubject("Testing");
msg.setText("Hi !! how are you??");

msg.setFrom(new InternetAddress("madan712@gmail.com"));

msg.addRecipient(Message.RecipientType.TO, new InternetAddress("madan@indiagames.com"));

msg.addRecipient(Message.RecipientType.CC, new InternetAddress("madan_chaudhary@rediffmail.com"));

msg.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com","madan712@gmail.com","********");//password
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

}
catch (Exception ex)
{
System.out.println("Exception occured");
ex.printStackTrace();
}
}
}




this is common exception every one gets if your server doesn't responds....



Exception in thread "main" javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 25;
nested exception is:
java.net.ConnectException: Connection refused: connect
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1282)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
at javax.mail.Service.connect(Service.java:288)
at javax.mail.Service.connect(Service.java:169)
at javax.mail.Service.connect(Service.java:118)
at SimpleMail.main(SimpleMail.java:23)
Caused by: java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at com.sun.mail.util.SocketFetcher.createSocket(SocketFetcher.java:232)
at com.sun.mail.util.SocketFetcher.getSocket(SocketFetcher.java:189)
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1250)
... 5 more

No comments:

Post a Comment