Authentication - Java Mail

Posted by Jagadeesh VP | Posted in ,


import java.net.URLEncoder;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class MyMail {

private String d_email = "";
private String d_password = "";

public void sendMail(String tomailid, String subject, String message)
throws Exception {

Properties mailProps = new Properties();

mailProps.load( this.getClass().getResourceAsStream("data/MailData.properties"));

d_email = mailProps.getProperty("smtp.user");
d_password = mailProps. getProperty("smtp.password");

Authenticator auth = new SMTPAuthenticator();

Session session = Session.getInstance(mailProps, auth);

MimeMessage msg = new MimeMessage(session);
msg.setHeader("Content-Type", "text/html;");

InternetAddress from = new InternetAddress(mailProps.get("mail.user").toString(),
"[EMAIL_HEADING]");
msg.setFrom(from);
InternetAddress to = new InternetAddress(tomailid);

msg.addRecipient(Message.RecipientType.TO, to);
msg.addRecipient(Message.RecipientType.BCC, new InternetAddress("emailid@test.in"));
msg.setSubject(subject);
msg.setContent(message, "text/html");

Transport.send(msg);
}

private class SMTPAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(d_email, d_password);
}
}

}

Comments (0)

Post a Comment