javax.mail.AuthenticationFailedException: failed to connect, no password specified?

前端 未结 14 2029
广开言路
广开言路 2020-12-17 10:46

This program attempts to send e-mail but throws a run time exception:

javax.mail.AuthenticationFailedException: failed to connect, no password specified?
         


        
14条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 11:01

    In addition to RMT's answer. I also had to modify the code a bit.

    1. Transport.send should be accessed statically
    2. therefor, transport.connect did not do anything for me, I only needed to set the connection info in the initial Properties object.

    here is my sample send() methods. The config object is just a dumb data container.

    public boolean send(String to, String from, String subject, String text) {
        return send(new String[] {to}, from, subject, text);
    }
    
    public boolean send(String[] to, String from, String subject, String text) {
    
        Properties props = new Properties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.host", config.host);
        props.put("mail.smtp.user", config.username);
        props.put("mail.smtp.port", config.port);
        props.put("mail.smtp.password", config.password);
    
        Session session = Session.getInstance(props, new SmtpAuthenticator(config));
    
        try {
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            InternetAddress[] addressTo = new InternetAddress[to.length];
            for (int i = 0; i < to.length; i++) {
                addressTo[i] = new InternetAddress(to[i]);
            }
            message.setRecipients(Message.RecipientType.TO, addressTo);
            message.setSubject(subject);
            message.setText(text);
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    

提交回复
热议问题