I try to send SMTP email in java, but I have an error like this and I don\'t get a mail. I turn off all firewall and anti-virus.
The error:
I had the same issue. After much testing with Gmail, I discovered the issue is that Gmail requires an OAuth sign-in, and not just a password. The solution for this is to use the Gmail API. However, this is a very complicated solution that I won't go into too much detail about. If you are interested in this, read the first answer here.
If you want a simple solution, however, what I did is simply switch to a Yahoo account. Because Yahoo doesn't use the same encryption, it works perfectly. Note: Don't forget to change the SMTP server to 'smtp.mail.yahoo.com', and the port to '25'.
If you want to set it up from scratch, simply follow this tutorial to download the JavaMail API and Java Activation Framework.
Then you could just copy-and-paste my code, change the top variables, and everything should work! If I missed anything, please let me know! Thanks!
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
public class Mailer {
public static void main(String[] args) {
final String username = "your-email@yahoo.com";
final String password = "your-password";
final String recipient = "email-recipient";
final String subject = "message-subject";
final String emailmessage = "message";
Properties props = new Properties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.host", "smtp.mail.yahoo.com");
props.put("mail.smtp.port", "25");
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(username));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient));
message.setSubject(subject);
message.setText(emailmessage);
Transport.send(message);
System.out.println("Done");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
}
}