java发送邮件功能,以发送qq邮件为例

原创
2017/08/18 14:12
阅读数 1.3K

问题①: java发送qq邮件出现如下错误的解决方法:

     503 Error: need EHLO and AUTH first !

pop.put("mail.smtp.auth", "true");//注意value值不能不设置,并且不能是Boolean类型,应为字符串,否则会报如上所示错误

问题②: Could not connect to SMTP host: smtp.qq.com, port: 465, response: -1

原因:

    465端口是为SMTPS(SMTP-over-SSL)协议服务开放的,这是SMTP协议基于SSL安全协议之上的一种变种协议.

  解决方法:

       配置文件需要加上如下代码即可解决.

pop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

附上所有的代码:

配置文件:

mail:
    mailhost: smtp.qq.com
    mailport: 465
    user: 邮箱用户名
    password: 密码(qq为授权码)
    mailFrom: xxx@foxmail.com
    mailTo: xxx@qq.com,xxx@qq.com,xxx@foxmail.com
    properties:
      mail:
      	smtp:
      	  auth: true
      	  mailtimeout: 1000
      	  mailssl: javax.net.ssl.SSLSocketFactory
      	  starttls: 
      	     enable: true
      	     required: true
    

java代码:

     @Value("${mailhost}")
	private String host;
	
	@Value("${mailport}")
	private Integer port;
	
	@Value("${user}")
	private String username;

	@Value("${password}")
	private String password;
	
	@Value("${mailFrom}")
	private String from;
	
	@Value("${mailTo}")
	private String [] to;

	@Value("${auth}")
	private String auth;

	@Value("${enable}")
	private Boolean enable;

	@Value("${required}")
	private Boolean required;

	@Value("${mailtimeout}")
	private Integer timeout;
	
	@Value("${mailssl}")
	private String ssl;
	public void onApplicationEvent(ApplicationEvent event) {
		System.out.println("email cfg....");
		System.out.println("print:"+this.toString());
		//创建一个发送者对象
		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setHost(this.host);
		mailSender.setPort(this.port);
		mailSender.setUsername(this.username);
		mailSender.setPassword(this.password);
		// 加认证机制
		Properties pop = new Properties();
		pop.put("mail.smtp.host", this.host);
//		pop.put("mail.smtp.port", this.port);//已经在上面加过
		pop.put("mail.smtp.auth", this.auth);//必须是字符串而不能是boolean否则报错
		pop.put("mail.smtp.starttls.enable", this.enable);
		pop.put("mail.smtp.timeout", this.timeout);
		pop.put("mail.smtp.socketFactory.class", this.ssl);
		mailSender.setJavaMailProperties(pop);

		//组织邮件参数并执行发送
		SimpleMailMessage message = new SimpleMailMessage();
		message.setFrom(this.from);
		message.setTo(this.to);
		message.setSubject("主题:测试,spring boot发送邮件.");
		message.setText("测 试\n 邮件为程序发送,是否收到?请回答");
		mailSender.send(message);
		System.out.println("send end....");
    }
    @Override
    public String toString() {
	    return "EmailConfiguration [host=" + host + ", port=" + port + ", username=" + username
	            + ", password=" + password + ", from=" + from + ", to=" + to + ", auth=" + auth
	            + ", enable=" + enable + ", required=" + required + ", timeout=" + timeout + "]";
    }

 

  

展开阅读全文
打赏
1
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
1
分享
返回顶部
顶部