I'm working on the tutorial at http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/javamail/javamail.html which shows how to send email with JavaMail API.
So I wrote the following code snippet
public class EmailSessionBean {
private int port = 465;
private String host = "smtp.gmail.com";
private String from = "[email protected]";
private boolean auth = true;
private String username = "[email protected]";
private String password = "mypassword";
private Protocol protocol = Protocol.SMTPS;
private boolean debug = true;
public void sendEmail(String to, String subject, String body) {
// Create a Properties object to contain settings for
// the SMTP protocol provider.
Properties props = new Properties();
props.put("mail.smtp.host", host);
props.put("mail.smtp.port", port);
switch (protocol) {
case SMTPS:
props.put("mail.smtp.ssl.enable", true);
break;
case TLS:
props.put("mail.smtp.starttls.enable", true);
break;
}
// If SMTP authentication is required you must set the mail.smtp.auth
// property and construct a Authenticator instance that returns
// a PasswordAuthentication instance with your username and password.
Authenticator authenticator = null;
if (auth) {
props.put("mail.smtp.auth", true);
authenticator = new Authenticator() {
private PasswordAuthentication pa
= new PasswordAuthentication(username, password);
@Override
public PasswordAuthentication getPasswordAuthentication() {
return pa;
}
};
}
//Create a Session instance using the Properties object
// and the Authenticator object.
Session session = Session.getInstance(props, authenticator);
session.setDebug(debug);
// Construct a MimeMessage instance, populate the message headers
// and content and then send the message
MimeMessage message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(from));
InternetAddress[] address = {new InternetAddress(to)};
message.setRecipients(Message.RecipientType.TO, address);
message.setSubject(subject);
message.setSentDate(new Date());
message.setText(body);
Transport.send(message);
} catch (MessagingException ex) {
ex.printStackTrace();
}
}
}
When I try to send Email with the WEB APP, Gmail stops me from doing that and mail me "Sign-in attempt prevented".
P.S. I also disabled the "Access for less secure apps" in my Gmail account. But in the next attempt for doing that Gmail suspended my Account.
Any useful comment/solution will be appreciated.
Ensure that you have checked everything listed here especially the DisplayUnlockCaptcha