Using Java mail API 1.4.7 the following code works. The problem is that Google now requires two-step authentication.
public class Mail {
public static void main(String[] args) {
Mail mail = new Mail("[email protected]", "....");
mail.enviaStartTLS("[email protected]", "[email protected]", "test", "startTLSTest");
}
private String usuario;
private String pass;
public Mail(String usuario, String pass){
this.usuario=usuario;
this.pass=pass;
}
public void enviaStartTLS(String from, String to, String subject, String text){
final String username = usuario;
final String password = pass;
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "smtp.gmail.com");
props.put("mail.smtp.port", "587");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse(to));
message.setSubject(subject);
message.setText(text);
Transport.send(message);
System.out.println("Enviado");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}
As I receive negative votes for a correct, safe and proven solution without any indication because, or a question in the wedding that did not work, apparently I have to elaborate a little more:
If you are referring to the use of a API , that implies having an implementation of the API in the build path . In the specific case that refers to javaee.jar
and mail-1.4.7.jar
. It is recommended to use the search engine of your confidence to download the correct libraries for reproduction.
If you have an electrical problem, do you solve it by bridging the fuse with a nail? I have done it, but in desperate cases, only in the short term and knowing the risks.