Tuesday, September 30, 2008

Sending email using GMAIL using Java Mail Api

Note: Search for changeme and replace with appropriate terms.





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

public class MailSender {
final String senderEmailID = "changeme @ changeme .com";
final String senderPassword = "changeme";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
String emailSubject = null;
String emailBody = null;

public MailSender(String receiverEmailID, String emailSubject, String emailBody) {
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;


Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
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", emailServerPort);
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

SecurityManager security = System.getSecurityManager();

try {
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
// session.setDebug(true);

MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
} catch (Exception mex) {
mex.printStackTrace();
}


}
private class SMTPAuthenticator extends javax.mail.Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MailSender mailSender=new MailSender("changeme @ changeme .com","Test Mail from Puretechie","Here goes the body");
}

}

6 comments:

shubham said...

Thanks thanks thanks a million thanks....... finally i got what i wanted from past few weeks.
It was exactly the code i was looking for again THANKS

Ochieng, Edmund said...

You deserve atleast 7 kisses a week to keep up the good work. Cheers was very handy.

abdul basith m said...

how to read gmail body message...

Dodger said...

Oh My God.
It's Working as I wish.
Thanks.
Thanks a lot dear.
Hugzzzzzzzzzzzzzzzzzzzzzzzz

frel said...

no funciona por smtp.gmail.com se produce un error, que no se puede conectar error timeout

jose luis obando balvin said...

no me funciona