从ofice365帐户发送电子邮件时Java出错

时间:2017-09-22 10:51:57

标签: java office365

从ofice365帐户发送电子邮件时Java出错。

javax.mail.AuthenticationFailedException:535 5.7.3身份验证失败[MA1PR01CA0090.INDPRD01.PROD.OUTLOOK.COM]

这是我的代码。电子邮件和密码是正确的。请帮帮我。

    final String username = StaticParameters.adminEmail;
    final String password = StaticParameters.adminPassword;

    Properties props = new Properties();
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.host", "smtp.office365.com");
    props.put("mail.smtp.port", "587");

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

    try {
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username));
        message.setRecipients(Message.RecipientType.TO,
            InternetAddress.parse(to));
        message.setSubject(subject);
        message.setContent(body, "text/html; charset=utf-8");
        Transport.send(message);
        System.out.println("Done");
        return true;

    } catch (MessagingException e) {

        throw new RuntimeException(e);
    }

1 个答案:

答案 0 :(得分:0)

试试这个:

 private static Properties props;
    private static Session session;
    static {
        props = new Properties();
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.smtp.port", "587");
        props.put("mail.smtp.host", "m.outlook.com");
        props.put("mail.smtp.auth", "true");
        session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("office365 email address"
                        "office365 password");
            }
        });

    }