smtp-spring发送时出现java-mailconnectexception

y1aodyip  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(407)

我在我的spring boot应用程序中的googlesmtp出现了以下错误。

Exception in thread "pool-5-thread-1" org.springframework.mail.MailSendException: Mail server connection failed; nested exception is com.sun.mail.util.MailConnectException: Couldn't connect to host, port: smtp.gmail.com, 25; timeout -1;
  nested exception is:

下面是我的配置。我在我的网络应用程序中也执行同样的过程,但有时我会收到一封电子邮件,但大多数时候我会遇到一个错误。

spring.mail.host=smtp.gmail.com
spring.mail.username=emailAdress@gmail.com
spring.mail.password=appPassword
spring.mail.transport.protocol=smtp
spring.mail.properties.mail.smtp.port=587 (also tried 465)
spring.mail.properties.mail.smtp.auth=true (tried true and false)
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.debug=true

我不知道是什么问题,我可以说我像以前一样用尽了前面所有可能的问题。
希望有人能启发我。谢谢您!

i5desfxk

i5desfxk1#

这就是我如何在我的一个项目中实现电子邮件发送者。请看一看。

public void send(String from, String to, String subject, String body) throws MessagingException {
            final JavaMailSenderImpl javaMailSender = getJavaMailSender();
            Properties prop = javaMailSender.getJavaMailProperties();         
            Session session = Session.getInstance(prop, null);
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(javaMailSender.getUsername()));
            msg.setSubject(subject);
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));

            MimeMultipart multipart = new MimeMultipart("related");
            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(body, "text/html");
            multipart.addBodyPart(messageBodyPart);
            msg.setContent(multipart);
            msg.setSentDate(new Date());
            javaMailSender.send(msg);
        }

        private JavaMailSenderImpl getJavaMailSender() {
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            mailSender.setHost("smtp.gmail.com");
            mailSender.setPort(587);
            mailSender.setUsername(username);
            mailSender.setPassword(password);
            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.smtp.timeout", 60000);
            props.put("mail.smtp.connectiontimeout", 60000);
            props.put("mail.smtp.writetimeout", 60000);
            return mailSender;
        }

相关问题