Thursday, November 13, 2008

MailSending In Java

MailSending Injava




import java.util.Date;
import java.util.Properties;
import com.sun.mail.smtp.SMTPTransport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author arnab dutta
*/
public class SendMail
{

SendMail( String to, String message,String subject,String User)
{


String from =User;

String mailhost = "smtp.gmail.com"; //it is googles mail host use proper mail host for proper server
String user = "authenticator@gmail.com"; ///authentication mail id
String password = "authenticator"; //password

boolean auth = true;
boolean ssl = true;//make it false if server is not SSL enabled
Properties props = System.getProperties();

if (mailhost != null) {
props.put("mail.smtp.host", mailhost);
}
if (auth) {
props.put("mail.smtp.auth", "true");
}

javax.mail.Session session = javax.mail.Session.getInstance(props, null);


javax.mail.Message msg = new MimeMessage(session);

try {

msg.setFrom(new InternetAddress(from));
msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(to));
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setText(message);


SMTPTransport t = (SMTPTransport)session.getTransport(ssl ? "smtps" : "smtp");

try {
if (auth) {

t.connect(mailhost, user, password);

} else {

t.connect();

}

t.sendMessage(msg, msg.getAllRecipients());

}
catch(Exception e)
{
System.out.println(e.toString());
}
finally {
t.close();
}
System.out.println("message Send");
} catch (Exception e)
{
System.out.println(e.toString());
}

}
public static void main(String Ar[])
{
new SendMail("recever@gmail.com", "msgbody", "subject", "sender") ;//edit this parameters properly
}



}