Java Code to Send Email

package Javamails;

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

public class Javamail
{
public static void main(String[] args)throws MessagingException
{
String from = "udhaya1987devtest@gmail.com",
password = "",
host = "smtp.gmail.com",
port = "8000",
subject = "Hi",
message = "Hi Team";
Properties props = new Properties();
props.put("mail.smtp.user", from);
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port",port);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallb","false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(message);
msg.setSubject(subject);
msg.setFrom(new InternetAddress(from));
msg.addRecipient(Message.RecipientType.TO,new InternetAddress(to);
Transport.send(msg);
}
catch(Exception mex)
{
mex.printStackTrace();
}
}
}

class SMTPAuthenticator extends javax.mail.Authenticator
{
String from = "sender_id@gmail.com",
password = "password",
host = "smtp.gmail.com",
port = "8000",
subject = "Hi",
message = "Hi Team";
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(from, password);
}
}

No comments:

Post a Comment

My Profile