首页 > 解决方案 > 为什么我不能发送电子邮件?

问题描述

我面临无法发送电子邮件的事实。我无法理解原因。我使用 Spting Boot 2。该示例使用 JavaMailSender 类。但是你可以不用它的实现和在 application.properties 中指定的必要参数吗?

@Configuration
public class MainConfiguration {

    @Bean
    public JavaMailSender getJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.yandex.ru");
        mailSender.setPort(465);

        mailSender.setUsername("test@yandex.ru");
        mailSender.setPassword("test122223");

        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", "smtp");
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "true");
        props.put("mail.debug", "true");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        //props.put("mail.smtp.timeout", 1000);

        return mailSender;
    }

    @Bean
    public SimpleMailMessage templateSimpleMessage() {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setText("This is the test email template for your email:");
        return message;
    }

}

2分钟后,我遇到了错误:"javax.mail.MessagingException: Could not connect to SMTP host"

标签: javaspring-bootjakarta-mail

解决方案


尝试添加

spring.mail.properties.mail.smtp.ssl.enable=true

或者

props.put("mail.smtp.ssl.enable", "true");

我不明白你为什么要使用配置类,如果你使用的是 spring boot 2,你可以把所有的电子邮件配置放在你的 application.properties 文件中:

spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.ssl.enable=true
spring.mail.host=smtp.yandex.ru
spring.mail.port=465
spring.mail.username=test@yandex.ru
spring.mail.password=test122223

推荐阅读