Solve error javax.mail.AuthenticationFailedException

后端 未结 15 1176
太阳男子
太阳男子 2020-11-29 05:45

I\'m not familiar with this function to send mail in java. I\'m getting an error while sending email to reset a password. Hope you can give me a solution.

Below is m

15条回答
  •  清歌不尽
    2020-11-29 06:11

    The solution that works for me has two steps.

    1. First step

      package com.student.mail;
      
      import java.util.Properties;
      
      import javax.mail.Authenticator;
      import javax.mail.Message;
      import javax.mail.MessagingException;
      import javax.mail.PasswordAuthentication;
      import javax.mail.Session;
      import javax.mail.Transport;
      import javax.mail.internet.InternetAddress;
      import javax.mail.internet.MimeMessage;
      
      /**
       *
       * @author jorge santos
       */
      public class GoogleMail {
          public static void main(String[] args) {
              Properties props = new Properties();
              props.put("mail.smtp.host", "smtp.gmail.com");
              props.put("mail.smtp.socketFactory.port", "465");
              props.put("mail.smtp.socketFactory.class",
                  "javax.net.ssl.SSLSocketFactory");
              props.put("mail.smtp.auth", "true");
              props.put("mail.smtp.port", "465"); 
              Session session = Session.getDefaultInstance(props,
              new javax.mail.Authenticator() {
                                  @Override
                  protected PasswordAuthentication getPasswordAuthentication() {
                      return new PasswordAuthentication("conaderindicadores@gmail.com","Silueta95#");
                  }
              });
      
          try {
      
              Message message = new MimeMessage(session);
              message.setFrom(new InternetAddress("conaderindicadores@gmail.com"));
              message.setRecipients(Message.RecipientType.TO,
                      InternetAddress.parse("netneillip@gmail.com"));
              message.setSubject("Testing Subject");
              message.setText("Test Mail");
      
              Transport.send(message);
      
              System.out.println("Done");
      
          } catch (MessagingException e) {
              throw new RuntimeException(e);
          }
      }
      
      }
      
    2. Enable the gmail security

      https://myaccount.google.com/u/2/lesssecureapps?pli=1&pageId=none
      

提交回复
热议问题