Sending Email in Java through Gmail Server
We can send email by using the SMTP server of gmail. It is good if
you are don't have any SMTP server and reliable. Here we will learn how to send
email through gmail server by SSL (Secured Socket Layer). SSL is basically used
for security if you are sending email through gmail server.
Example of Sending Email through
Gmail Server with SSL
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
class Mailer{
public static void send(String from,String password,String to,String sub,Str ing msg){
//Get properties object
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class",
"javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", "465");
//get Session
Session session = Session.getDefaultInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(from,password);
}
});
//compose message
try {
MimeMessage message = new MimeMessage(session);
message.addRecipient(Message.RecipientType.TO,new InternetAddress( to));
message.setSubject(sub);
message.setText(msg);
//send message
Transport.send(message);
System.out.println("message sent successfully");
} catch (MessagingException e) {throw new RuntimeException(e);}
}
}
public class SendMailSSL{
public static void main(String[] args) {
//from,password,to,subject,message
Mailer.send("from@gmail.com","xxxxx","to@gmail.com","hello pramod","How r u?");
//change from, password and to
}
}
No comments:
Post a Comment