简体   繁体   中英

Unable to send email using JavaMail API

I'm trying to send a simple email using Java Mail API but its throwing error as below

Exception in thread "main" javax.mail.AuthenticationFailedException: No authentication mechansims supported by both server and client
        at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:765)
        at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:685)
        at javax.mail.Service.connect(Service.java:295)
        at javax.mail.Service.connect(Service.java:176)
        at JavaMail.main(JavaMail.java:50)

Below is my code

        Properties props = new Properties();
        //props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.auth.plain.disable", true);
        props.put("mail.smtp.host", "127.0.0.1");
        props.put("mail.smtp.port", "25");


        Transport transport = null;
//      Session session = Session.getInstance(props,
//        new javax.mail.Authenticator() {
//          protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
//              return new PasswordAuthentication(username, password);
//          }
//        });
// 

        Session session = Session.getDefaultInstance(props,null);
        session.setDebug(true);
        System.out.println(" session was created "+session.toString());
        MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress("me@example.com"));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse("you@example.com"));
        message.setSubject("Testing Java EMail  Subject");
        message.setText("Dear Mail Crawler,"
            + "\n\n Test Email....!!! please!");


        transport = session.getTransport("smtp");
        transport.connect("127.0.0.1", "user", "pass");
        transport.sendMessage(message, message.getAllRecipients());

        System.out.println("email was SEnt sUcessfully ");

you need to uncoment and put this code after Session session = Session.getDefaultInstance(props,null); ...

  session = Session.getInstance(props,
  new javax.mail.Authenticator() {
     protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
      return new PasswordAuthentication(username, password);
      }
   });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM