简体   繁体   中英

Sending email using java authentication error

I've seen a lot of error regarding authentication error on sending email and the host is gmail. I have tried different properties also without authentication but still nothing happens. I do not know why on other tutorial, this code is working but when I am trying to run it here it is authentication error. I have imported my library but still it is error. I also tried different gmail account but nothing happens. All of the accounts that I've tried are all verified. Whats wrong? Here's the code:

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;

public class SendEmail {
  public static void main(String[] args) {
        Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
        properties.put("mail.smtp.host", "smtp.gmail.com");
        properties.put("mail.smtp.port", "587");


        Session session = Session.getDefaultInstance(properties, new Authenticator(){
            protected PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication("mine@gmail.com", "minepass");
            }
        });


        try{
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("yours@gmail.com"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("theirs@yahoo.com"));
            message.setSubject("Send meessage");
            message.setText("Email received");
            Transport.send(message);

            System.out.println("Sent");
        }
        catch(MessagingException e){
            throw new RuntimeException(e);
        }


  }
}

Here is the output log:

Exception in thread "main" java.lang.RuntimeException: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/answer/14257 hg3sm8230925pbb.52 - gsmtp

    at SendEmail.main(SendEmail.java:40)
Caused by: javax.mail.AuthenticationFailedException: 535-5.7.8 Username and Password not accepted. Learn more at
535 5.7.8  https://support.google.com/mail/answer/14257 hg3sm8230925pbb.52 - gsmtp

    at com.sun.mail.smtp.SMTPTransport$Authenticator.authenticate(SMTPTransport.java:809)
    at com.sun.mail.smtp.SMTPTransport.authenticate(SMTPTransport.java:752)
    at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:669)
    at javax.mail.Service.connect(Service.java:317)
    at javax.mail.Service.connect(Service.java:176)
    at javax.mail.Service.connect(Service.java:125)
    at javax.mail.Transport.send0(Transport.java:194)
    at javax.mail.Transport.send(Transport.java:124)
    at SendEmail.main(SendEmail.java:35)

If you are using gmail account for Emails (SMTP) then make sure you have correct Email password in the application and also enable this setting allow less secure apps for your gmail account.

Allow Secure apps-->Go to manage Account settings-->Left side navigation click security--> then enable less secure apps.

Make sure that you have enabled connection to your gmail account from external and uncertified apps. For more info on enabling less secure apps to connect to your google account check: https://support.google.com/accounts/answer/6010255?hl=en This could be your problem from the very beginning, enable less secure apps to connect to your gmail account and re-run your app.

If this wont help try putting username and password in properties then there will be no need to use Authenticator . Here is a working example of method that is able to send multiple emails.
Note: it requires javax.mail library

Method parameters:
from - is your email address (from gmail)
pass - your password
to - an array of recipients
subject - message title
body - a message body

public static void sendFromGMail(String from, String pass, String[] to, String subject, String body) {
        Properties props = System.getProperties();
        String host = "smtp.gmail.com";
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.user", from);
        props.put("mail.smtp.password", pass);
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(props);
        MimeMessage message = new MimeMessage(session);

        try {
            message.setFrom(new InternetAddress(from));
            InternetAddress[] toAddress = new InternetAddress[to.length];

            // To get the array of addresses
            for( int i = 0; i < to.length; i++ ) {
                toAddress[i] = new InternetAddress(to[i]);
            }

            for( int i = 0; i < toAddress.length; i++) {
                message.addRecipient(Message.RecipientType.TO, toAddress[i]);
            }

            message.setSubject(subject);
            message.setText(body);
            Transport transport = session.getTransport("smtp");
            transport.connect(host, from, pass);
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
        }
        catch (AddressException ae) {
            ae.printStackTrace();
        }
        catch (MessagingException me) {
            me.printStackTrace();
        }
}

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