Search code examples
spring-bootemailspring-securitysmtpgmail

how can i make it possible to automatically authenticate when sending an email through an SMTP server


I'm trying to implement a mail sender feature yet during the process of testing this error keeps popping up

Username and Password not accepted. Learn more at 535 5.7.8 https://support.google.com/mail/?p=BadCredentials h25-20020a170906855900b00993017b64a9sm7314529ejy.223 - gsmtp

the username and password are 100% correct. When I did some research I found that to make the process possible I have to "Allow less secure apps" yet google removed that feature a while ago. Here's the spring mail config and the method sendEmail .

application.yml :

mail:
    host: smtp.gmail.com
    port: 587
    username: emailtestingtool1.0@gmail.com
    password: ****
    properties:
        mail:
            smtp:
                auth: true
                starttls:
                    enable: true

sendEmail method :

private void sendEmail(String email, String resetPasswordLink) throws MessagingException, UnsupportedEncodingException {

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);

        helper.setFrom("emailtestingtool1.0@gmail.com", "SBI intern");
        helper.setTo(email);

        String subject = "Here's the link to reset your password";

        String content = "<p>Hello, </p>"
                + "<p>You have requested to reset ur password.</p>"
                + "<p>Click the link below:</p>"
                + "<p><b><a href= \"" + resetPasswordLink + "\">Change my password</a></b></p>"
                + "<p>Ignore this email if u have not made the request.</p>";

        helper.setSubject(subject);
        helper.setText(content, true);

        mailSender.send(message);
    }

Solution

  • You can also send email using javax.mail using the following code

        import javax.mail*;
        
        public String sendMails() {
    
            String resp;
    
            String host = "smtp.gmail.com";
            final String user = "sender@gmail.com"; 
            final String pwd = "**application password**"; //https://support.google.com/accounts/answer/185833?visit_id=638140255515756664-3142292480&p=InvalidSecondFactor&rd=1
            final String to = "recipient@gmail.com";
    
            Properties properties = new Properties();
            properties.put("mail.debug", "false");
            properties.put("mail.smtp.host", host);
            properties.put("mail.smtp.port", 587);
            properties.put("mail.smtp.auth", true);
            properties.put("mail.smtp.starttls.enable", true);
    
            Session session = Session.getInstance(properties,
                    new Authenticator() {
    
                @Override
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(user, pwd);
                }
            });
           
            try {
                String msg = "Test email body";
    
                MimeMessage message = new MimeMessage(session);
    
                //Set email header & From address
                message.setFrom(new InternetAddress("Email header <non-reply@domain.com>\r\n"));
                message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                message.setSubject("Test email subject");
    
                Multipart multipart = new MimeMultipart("alternative");
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.setContent(msg, "text/html; charset=utf-8");
                multipart.addBodyPart(mimeBodyPart);
                message.setContent(multipart);
    
                //send the message
                Transport.send(message);
    
                resp = "SUCCESS:Email sent successfully";
            } catch (MessagingException ex) {
                resp = "FAIL:" + ex.getMessage();
    
            }
    
            return resp;
        }
    

    to generate application password for sender's gmail account, follow this link