I am running a very basic Javamail program to try sending emails. This is stand-alone program with main(). Once I get it working, I plan to use Javamail in a servlet running under tomcat.
I was getting AUTH LOGIN failed error when running this program. I tried several different property settings, none of which solved the problem.
Then I found a post on SO, which suggested lowering the required security level in my Google account. The authentication was successful when I lowered the security setting.
Of course, I went back to higher security level on the Google account immediately.
The question I have is, how can I make my application more secure so that gmail does not refuse authentication?
Program code shown below. The program is very similar to code in many other Javamail questions on SO.
TryJavamail.java
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;
public class TryJavamail {
public static void main(String args[]) throws MessagingException {
String submitName = "John Doe";
String submitEmail = "[email protected]";
String submitMessage = "This is the message";
Properties props = new Properties();
props.put("mail.transport.protocol", "smtp");
props.setProperty("mail.smtp.host", "smtp.gmail.com");
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.smtp.ssl.enable", "true");
props.setProperty("mail.smtp.port", "465");
Session session = Session.getInstance(props, null);
session.setDebug(true);
Message message = new MimeMessage(session);
message.setSubject("Message from myapp website submit");
message.setText(submitName + "; " + submitMessage);
Address toAddress = new InternetAddress(submitEmail);
message.setRecipient(Message.RecipientType.TO, toAddress);
Transport transport = session.getTransport("smtp");
transport.connect("smtp.gmail.com", "---userid---", "---password---");
transport.sendMessage(message, message.getAllRecipients());
transport.close();
}
}
You probably want to use OAuth2 authentication.