Tuesday, 26 February 2013
How to send Mail from your gmail account using java.
import java.security.Security;
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.*;
public class SendMail
{
public static int status=0;
private String from;
private String to;
private String subject;
private String text;
private String host;
private String pass;
private String username;
public SendMail(){}
public SendMail(String from, String to, String subject, String text)
{
this.from = from;
this.to = to;
this.subject = subject;
this.text = text;
status=0;
}
public void send()
{
username="panjariixxxx"; //here u have to write your user name
pass="ishwaxxxx"; //here your gmail password
host = "smtp.gmail.com";
Properties props = new Properties();
props.put("mail.smtp.host",host);
props.put("mail.smtp.auth","true");
props.put("mail.smtp.port", "25");
props.put("mail.smtp.protocolo","smtps");
//this follwoing need to set for server authentication.
props.put("mail.smtp.starttls.enable", "true");
Session mailSession=Session.getDefaultInstance(props,new javax.mail.Authenticator(){
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username,pass);
}
});
Message simpleMessage = new MimeMessage(mailSession);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;
try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
simpleMessage.setFrom(fromAddress);
simpleMessage.setRecipient(RecipientType.TO,toAddress);
simpleMessage.setSubject(subject);
//this following line for other formate message e.g this support html and simple formate too
simpleMessage.setContent(text,"text/html");
Transport.send(simpleMessage);
status=1;
}
catch (MessagingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[])
{
String femailid="xxxxx@gmail.com"; //this is from email id
String temailid="xxxxx@gmail.com"; //this is too email id
String sub="Good Morining";
String message="<h1>This is mail from local server and sent using gmail account..by java program <h1>";
SendMail sendmail=new SendMail(femailid,temailid,sub,message);
sendmail.send();
}
}
for above program you need to download two jar file
1)jaf-1.1.1
2)javamail-1.4.5
You can download this example from the following link
https://sites.google.com/site/poolofjava/Sending%20Mail.zip?attredirects=0&d=1
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment