Solve error javax.mail.AuthenticationFailedException

后端 未结 15 1188
太阳男子
太阳男子 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:37

    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.activation.*;
    
    public class SendMail1 {
    
        public static void main(String[] args) {
            // Recipient's email ID needs to be mentioned.
              String to = "valid email to address";
    
              // Sender's email ID needs to be mentioned
              String from = "valid email from address";
    
    
              // Get system properties
              Properties properties = System.getProperties();
    
              properties.put("mail.smtp.starttls.enable", "true"); 
              properties.put("mail.smtp.host", "smtp.gmail.com");
    
              properties.put("mail.smtp.port", "587");
              properties.put("mail.smtp.auth", "true");
              Authenticator authenticator = new Authenticator () {
                    public PasswordAuthentication getPasswordAuthentication(){
                        return new PasswordAuthentication("userid","password");//userid and password for "from" email address 
                    }
                };
    
                Session session = Session.getDefaultInstance( properties , authenticator);  
              try{
                 // Create a default MimeMessage object.
                 MimeMessage message = new MimeMessage(session);
    
                 // Set From: header field of the header.
                 message.setFrom(new InternetAddress(from));
    
                 // Set To: header field of the header.
                 message.addRecipient(Message.RecipientType.TO,
                                          new InternetAddress(to));
    
                 // Set Subject: header field
                 message.setSubject("This is the Subject Line!");
    
                 // Now set the actual message
                 message.setText("This is actual message");
    
                 // Send message
                 Transport.send(message);
                 System.out.println("Sent message successfully....");
              }catch (MessagingException mex) {
                 mex.printStackTrace();
              }
        }
    
    }
    

提交回复
热议问题