Thursday 10 October 2013

How to Send Mail Using Java Code?

Here we required some jars for this process these are:
1. mail.jar
2. activation.jar

Click here to get this Jars.....

package com.lara.mail;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailByJava
{
public static void main(String[] args)
{
final String username = "sailendra.n.jena@gmail.com";
final String password = "********";

Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");

//Here while creating session object for mail that time also we are checking credentials are authenticated.

Session session = Session.getInstance(props, new Authenticator()
{
protected  PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});

try
{
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("sailendra.n.jena@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("sailendra.n.jena@gmail.com"));
message.setSubject("This mail from Java Code");
message.setText("Hi Janu"+"\n\n"+"This mail i have sent from Java Code.....nice naa"+"\n\n"+"Yours "+"\n"+"Dhana");
Transport.send(message);
System.out.println("Message Sent Successfully");
}
catch(MessagingException ex)
{
System.out.println("Exception Generate in Message Sending Time : "+ex.toString());
}
}
}

No comments:

Post a Comment