Search code examples
javajakarta-mail

Mail API stopped to work


I have an automated java mail application that sends automated mail to users when some important update occur in our database. It was working fine. However it started to give me errors and I realized that it's not working.

The error says: "Please log in via your web browser and then try again. Learn more at https://support.google.com/mail/bin/answer.py?answer=78754 l10sm7526045oev.7 - gsmtp"

The java mail application that I write is huge and contains some confidential values(password etc.), I decided to write a sample demo to show you what's going on. It gives me the same error. Please assume that javax.MAIL API has been imported to the project. Here is what I have:

public class MailDemo {

    public static void main(String[] args) {
        final String userName = "[email protected]";
        final String password = "dummyPassword";

        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");//Smtp server address
        props.put("mail.smtp.port", "587");//port for the smtp server

        Session session = Session.getInstance(props, new Authenticator(){
        protected PasswordAuthentication getPasswordAuthentication(){
            return new PasswordAuthentication(userName, password);
        }
    });
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("[email protected]"));//from email address
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("[email protected]"));//to email address
            message.setSubject("My first Email");//Subject of the mail
            message.setContent("<h1>This is a test email</h1>", "text/html; charset=utf-8");//Content of the mail
            Transport.send(message);//send the message
            System.out.println("Email Stiation:Done!");

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

}

Solution

  • Well, i found the problem. Actually the codes are correct. It's gmail. it blocks the sign in attempts.I think that gmail thinks the attempts are not real.