java发送qq邮箱不成功_springboot通过qq邮箱发邮件失败??

题主贴出的配置和代码有两个问题:

1、端口号。根据QQ邮箱的官方说明,端口号可以是465或587,但我测试的时候465是超时的,587就正常。

2、运行贴出的代码尝试发邮件,会报错,报错信息

java.net.ConnectException: Connection refused: connect. Failed messages: com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1;

根据这个信息,host和port这两个参数都没有作为参数传入,运行的时候压根就没有连去QQ邮箱的服务器。

因为弄了一轮都发不出,于是归零重新找资料实现。

下面是我的代码,参考的是spring的官方文档。

配置文件沿用题主的。用了springboot,版本号2.2.3.RELEASE。

package zsh.sf_answer1.mail;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.context.ApplicationContext;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

import org.springframework.mail.javamail.JavaMailSenderImpl;

import org.springframework.mail.javamail.MimeMessageHelper;

import org.springframework.stereotype.Component;

import javax.mail.MessagingException;

import javax.mail.internet.MimeMessage;

import java.util.Date;

@Configuration

@PropertySource("classpath:application.properties")

@Component("mailRunner")

public class MailRunner {

public void func1(String sendTo) throws MessagingException {

JavaMailSenderImpl sender = new JavaMailSenderImpl();

sender.setHost(host);//发件邮箱

sender.setUsername(username);//*1

sender.setPassword(password);

sender.setPort(Integer.parseInt(port));

MimeMessage message = sender.createMimeMessage();

MimeMessageHelper helper = new MimeMessageHelper(message);

helper.setFrom(username);//与*1要一致,不配置会报错

helper.setSubject("TestMail Type I");

helper.setTo(sendTo);//收件邮箱

helper.setText("Thank you for ordering!");//邮件内容

helper.setSentDate(new Date());

sender.send(message);

}

public static void main(String[] args) {

ApplicationContext ac = new AnnotationConfigApplicationContext(MailRunner.class);

MailRunner mr = ac.getBean(MailRunner.class);

try{

mr.func1("xxx@163.com");

}catch(Exception e) {

e.printStackTrace();

}

}

String host;

String username;

String password;

String port;

@Autowired

public void setUsername(@Value("${spring.mail.username}") String username) {

this.username = username;

}

@Autowired

public void setPassword(@Value("${spring.mail.password}") String password) {

this.password = password;

}

@Autowired

public void setPort(@Value("${spring.mail.port}") String port) {

this.port = port;

}

@Autowired

public void setHost(@Value("${spring.mail.host}") String host) {

this.host = host;

}

}


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部