I have this servlet which needs to send mail using Java Mail API, however I am getting no password specified error, although the password work with gmail.
MailServiceImpl.java:
public class MailServiceImpl extends RemoteServiceServlet implements MailService {
private static String HOST = "smtp.gmail.com";
private static int PORT = 465;
private String username = "foo@gmail.com";
private String password = "foo123";
private Properties props = new Properties();
@Override
public void sendMail(String email) {
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.socketFactory.port", "465");
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
Session session = Session.getInstance(props);
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("foo@gmail.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("foo@gmail.com"));
message.setSubject("Testing Subject");
message.setText("Subcriber Email:," +
"\n\n " + email);
Transport transport = session.getTransport("smtp");
transport.connect(HOST, PORT, username, password);
Transport.send(message);
transport.close(); // -- needed?
} c开发者_开发知识库atch (Exception e) {
e.printStackTrace();
}
}
}
However I am getting this error:
javax.mail.AuthenticationFailedException: failed to connect, no password specified?
at javax.mail.Service.connect(Service.java:329)
at javax.mail.Service.connect(Service.java:176)
at javax.mail.Service.connect(Service.java:125)
at javax.mail.Transport.send0(Transport.java:194)
at javax.mail.Transport.send(Transport.java:124)
at com.mygwtapp.server.MailServiceImpl.sendMail(MailServiceImpl.java:43)
Try using SSL connection. It worked for me.
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 javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username","password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@test.com"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("to@test.com"));
message.setSubject("Testing Subject");
message.setText("mail text");
Transport.send(message);
System.out.println("OK");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
精彩评论