Example Code to send mail in JAVA

package javaapplication27;
import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
*
* @author SANAT
*/
public class Main {

/**
* @param args the command line arguments
*/

private String mailhost = "smtp.gmail.com";

public synchronized void sendMail(String subject, String body, String sender, String recipients)
throws Exception
{
try
{

Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", mailhost);
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
props.setProperty("mail.smtp.quitwait", "false");

Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{ return new PasswordAuthentication("USER","PASS"); }
});

MimeMessage message = new MimeMessage(session);
message.setSender(new InternetAddress(sender));
message.setSubject(subject);
message.setContent(body, "text/plain");
if (recipients.indexOf(',') > 0)
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
else
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recipients));


Transport.send(message);
}
catch(Exception ex)
{
ex.printStackTrace();
}

}


public static void main(String args[]) throws Exception
{
Main mailutils = new Main();
mailutils.sendMail("Test", "dl;fkglkdjgjdlkgjlk;djglkdlkgjdlkgjlkdjglkfdj", "TO@gmail.com", "FROM@GMAIL.com");
}


// TODO code application logic here
}

Comments

Popular posts from this blog

Using Java Script detect if OS is 64 bit version or 32 bit.

Get correct OS version on win 8.1 without using GetVesionEx API (deprecated )

ESENT –JET APIs to create database in Metro Style App on Windows 8