无法连接到SMTP主机:网址:www.example.com,端口号:587;outlook.office365.comjava.net.SocketException:权限被拒绝:连接 Permission denied: connect

k5ifujac  于 2023-02-02  发布在  Java
关注(0)|答案(1)|浏览(189)

我已经编写了使用outlook.office365.com发送电子邮件的代码。当我运行程序时,得到以下错误。

    • javax.mail.messagingException:**无法连接到SMTP主机:网址:www.example.com,端口号:587;outlook.office365.com, port: 587; nested exception is:
    • java.net.SocketException:**权限被拒绝:连接
private static final String SERVIDOR_SMTP = "outlook.office365.com";
private static final int PORTA_SERVIDOR_SMTP = 587;
private static final String CONTA_PADRAO = "xxxx@xxx.com"; //Cofig  Mail Id
private static final String SENHA_CONTA_PADRAO = "XYZ"; // Password

private final String from = "xxxx@xxx.com"; 
private final String to = "xxxx@xxx.com";

private final String subject = "Teste";
private final String messageContent = "Teste de Mensagem";

public void sendEmail() {
    final Session session = Session.getInstance(this.getEmailProperties(), new Authenticator() {

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(CONTA_PADRAO, SENHA_CONTA_PADRAO);
        }

    });

    try {
        final Message message = new MimeMessage(session);
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
        message.setFrom(new InternetAddress(from));
        message.setSubject(subject);
        message.setText(messageContent);
        message.setSentDate(new Date());
        Transport.send(message);
    } catch (final MessagingException ex) {
       System.out.println(" "+ex);
    }
}

public Properties getEmailProperties() {
    final Properties config = new Properties();
    config.put("mail.smtp.auth", "true");
    config.put("mail.smtp.starttls.enable", "true");
    config.put("mail.smtp.host", SERVIDOR_SMTP);
    config.put("mail.smtp.port", PORTA_SERVIDOR_SMTP);
    return config;
}

public static void main(final String[] args) {
    new SendAttachmentInEmail().sendEmail();
}
rdrgkggo

rdrgkggo1#

我想,你没有权限访问你的电子邮件。例如,当我尝试在我的gmail帐户,如果我没有打开设置显示在下面,我得到一个授权失败,但如果我打开设置,我可以发送电子邮件与您的代码。
请检查您的电子邮件权限和设置。
settings picture

相关问题