How to send email using java

In this program we are going to discuss about how to sent mail in java using javax.mail.
SOURCE : EmailSender.java

package com.ocg.post;

import java.io.File;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;

public class EmailSender {
private String username = "";//use gamil username
private String password ="";//use gmail password
private String senderMailID = ""; //sender mail id
private String receiverMailID = "";// receiver mail id
public boolean sentMail(String subject, String pageContent, File fileName) {
boolean isMailSent = false;
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");

Session session = Session.getDefaultInstance(props,
new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username,
password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(senderMailID));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(receiverMailID));
message.setSubject(subject);
BodyPart messageBodyPart = new MimeBodyPart();
message.setContent(pageContent, "text/html");
Transport.send(message);
isMailSent = true;
System.out.println("Mail sent successfully");
} catch (MessagingException e) {
isMailSent = false;
throw new RuntimeException(e);
}
return isMailSent;
}
}



OUTPUT

Mail sent successfully






Sandeep Kumar D

Hi, I have written and developed this post so that most of people will be benefited. I'm committed to provide easy and in-depth tutorials on various technologies.I hope it will help you a lot.

- Sandeep Kumar D

Follow Me @Google+





SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment