小记:生活有望穿秋水的期待,也会有意想不到的欣喜,给自己发个邮件吧(SpringBoot整合Java Mail)

身份认证失败

Caused by: javax.mail.AuthenticationFailedException: 535 Error: authentication failed

  • 1.检查邮箱是否已开启客户端授权密码,以及POP3/SMTP/IMAP服务是否开启
    在这里插入图片描述
    在这里插入图片描述

若都已开启,那么身份认证失败的原因很有可能是密码不对,仔细检查配置文件中参数mail.auth.password= 的值是否与邮箱中配置的一致!!!

SMTP发送失败异常

Failed messages: com.sun.mail.smtp.SMTPSendFailedException: 554 DT:SPM 163 smtp8,DMCowAAn5Ag8LvxdHlwYYw

这个问题就很坑爹了,之前一直以为是代码问题,反复的弄来弄去,最后发现,居然是网易把邮件当成了垃圾邮件没有发送出去。解决的方法也很简单就是发送邮件的时候顺便抄送一份给自己,这样就不会被当成垃圾邮件处理了…
测试控制台结果如下:
在这里插入图片描述
成功接收到邮件
在这里插入图片描述

项目目录与代码

在这里插入图片描述

添加依赖:pom.xml

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
        <!-- javax.mail -->
        <dependency>
            <groupId>com.sun.mail</groupId>
            <artifactId>javax.mail</artifactId>
            <version>1.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>4.2.6.RELEASE</version>
        </dependency>

用户请求的控制器:UserController.java

package com.send_email.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.send_email.utils.EmailUtils;
import com.send_email.utils.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 用户请求的控制器
 */
@RestController
@ResponseBody
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    /**
     * 发送邮件
     *
     * @param email 收件人邮箱
     * @throws JsonProcessingException
     */

    @RequestMapping(value = "/users/sendEmail", method = {RequestMethod.POST, RequestMethod.GET})
    public ResponseResult sendEmail(String email) {
        logger.info("email = " + email);
        boolean isSend = true;
        System.err.println("准备发送");
        if (email != null && email.trim() != "") {
            isSend = EmailUtils.sendEmail("这是一封很重要邮件", new String[]{email}, new String[]{"ydy9601221614@163.com"}, "有内鬼,终止交易", null);
        }
        if (isSend == false || email.trim() == "") {
            logger.info("执行完毕,发送失败");
            return new ResponseResult(-1, "发送失败");
        } else {
            logger.info("执行完毕,发送成功");
            return new ResponseResult(200, "发送成功");
        }
    }


}

发送邮件的工具类:EmailUtils.java

package com.send_email.utils;



import com.sun.mail.util.MailSSLSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.security.GeneralSecurityException;
import java.util.List;
import java.util.Map;
import java.util.Properties;


/**
 * 发送邮件的工具类
 */
@Component
public class EmailUtils {

    private static final Logger logger = LoggerFactory.getLogger(EmailUtils.class);

    @Autowired
    private Environment env;

    private static String auth;
    private static String host;
    private static String protocol;
    private static int port;
    private static String authName;
    private static String password;
    private static boolean isSSL;
    private static String charset ;
    private static String timeout;

    @PostConstruct
    public void initParam () {
        auth = env.getProperty("mail.smtp.auth");
        host = env.getProperty("mail.host");
        protocol = env.getProperty("mail.transport.protocol");
        port = env.getProperty("mail.smtp.port", Integer.class);
        authName = env.getProperty("mail.auth.name");
        password = env.getProperty("mail.auth.password");
        charset = env.getProperty("mail.send.charset");
        isSSL = env.getProperty("mail.is.ssl", Boolean.class);
        timeout = env.getProperty("mail.smtp.timeout");
    }


    /**
     * 发送邮件
     * @param subject 主题
     * @param toUsers 收件人
     * @param ccUsers 抄送
     * @param content 邮件内容
     * @param attachfiles 附件列表  List<Map<String, String>> key: name && file
     */
    public static boolean sendEmail(String subject, String[] toUsers, String[] ccUsers, String content, List<Map<String, String>> attachfiles) {
        boolean flag = true;
        try {
            JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
            javaMailSender.setHost(host);
            javaMailSender.setUsername(authName);
            javaMailSender.setPassword(password);
            javaMailSender.setDefaultEncoding(charset);
            javaMailSender.setProtocol(protocol);
            javaMailSender.setPort(port);

            Properties properties = new Properties();
            properties.setProperty("mail.smtp.auth", auth);
            properties.setProperty("mail.smtp.timeout", timeout);
            if(isSSL){
                MailSSLSocketFactory sf = null;
                try {
                    sf = new MailSSLSocketFactory();
                    sf.setTrustAllHosts(true);
                    properties.put("mail.smtp.ssl.enable", "true");
                    properties.put("mail.smtp.ssl.socketFactory", sf);
                } catch (GeneralSecurityException e) {
                    e.printStackTrace();
                }
            }
            javaMailSender.setJavaMailProperties(properties);

            MimeMessage mailMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, true);
            messageHelper.setTo(toUsers);
            if (ccUsers != null && ccUsers.length > 0) {
                messageHelper.setCc(ccUsers);
            }
            messageHelper.setFrom(authName);
            messageHelper.setSubject(subject);
            messageHelper.setText(content, true);

            if (attachfiles != null && attachfiles.size() > 0) {
                for (Map<String, String> attachfile : attachfiles) {
                    String attachfileName = attachfile.get("name");
                    File file = new File(attachfile.get("file"));
                    messageHelper.addAttachment(attachfileName, file);
                }
            }
            javaMailSender.send(mailMessage);
        } catch (Exception e) {
            logger.error("发送邮件失败!", e);
            flag = false;
        }
        return flag;
    }
}

定义JSON返回:ResponseResult.java

package com.send_email.utils;

/**
 * 定义JSON返回
 */
public class ResponseResult {

	private Integer state;
	private String message;

	public ResponseResult(Integer state, String message) {
		super();
		this.state = state;
		this.message = message;
	}

	public Integer getState() {
		return state;
	}

	public void setState(Integer state) {
		this.state = state;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

}

项目默认启动类:SendEmailApplication.java

package com.send_email;

import com.send_email.controller.UserController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SendEmailApplication {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    public static void main(String[] args) {
        SpringApplication.run(SendEmailApplication.class, args);
        logger.info("启动完毕");
    }
}

默认访问页面:index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<body>
<form id="form-send-email">
    请输入收件邮箱:<input type="text" id="email" name="email">
</form>
<button id="btn_send">发送</button>
</body>
<script>
    $("#btn_send").click(function () {
        $.ajax({
            "url": "/users/sendEmail",
            "data": $("#form-send-email").serialize()+"",
            "type": "POST",
            "dataType": "json",
            "success": function (data) {
                alert(data.message);
            }
        });
    });
</script>
</html>

配置文件:application.properties

mail.smtp.auth=true
mail.transport.protocol=smtp
mail.send.charset=UTF-8
mail.smtp.port=465
mail.is.ssl=true
mail.host=smtp.163.com
#自己邮箱账号
mail.auth.name=XXX@163.com
#邮箱设置的秘钥非邮箱密码
mail.auth.password=XXX
mail.smtp.timeout=50000

测试:启动项目,访问localhost,输入邮箱点击发送
在这里插入图片描述
查看后台日志:
在这里插入图片描述
查看邮箱
在这里插入图片描述在这里插入图片描述
欢迎大家留言交流,共同进步,万分感谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值