SpringBoot use configuration mail and actual combat (super detailed)

1 Introduction

        When I recently set up a school girl, it involved resetting the password, sending the new password to the user's mailbox, using a simple mail format, subject and content.        
        Sending emails should be one of the necessary extension functions of the website, registration verification, forgetting the password or sending marketing information to users. Normally we will use JavaMail related api to write related code for sending emails, but now springboot provides a set of packages that are easier to use. (This paragraph is taken from the Internet)
2. Add dependencies
        Add mail dependency in pom.xml
<!--mail-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-mail</artifactId>
</dependency>

Reload the Maven library. After loading, the mail-related jar will appear. Maybe some friends IDEA have set the pom file to be automatically loaded, so there is no need to click the refresh button at this time.

 
3. Add mail configuration in Properties
        Here I use QQ mail, QQ mail is more common
# mail
spring.mail.host=smtp.qq.com   //QQ邮箱主机地址 ;136邮箱主机地址:smtp.163.com
spring.mail.port=587            //端口号
[email protected]        //发件人QQ邮箱,修改成个人的或者企业邮箱
spring.mail.password=woqybrryawjhieh            // 授权码,需要进入QQ邮箱设置中打开权限,获取此授权码
spring.mail.default-encoding=UTF-8           //默认的编码的确是UTF-8
spring.mail.properties.mail.smtp.auth=true

 
3. Obtain spring.mail.password authorization code
        Click Settings --> Account --> Enable POP3/SMTP service and IMAP/SMTP service (there is a tutorial on the Internet that says to enable POP3/SMTP service, I don’t care about it, it’s all turned on) --> Get authorization code
Then copy the authorization code and paste it into the project.
4. Project actual combat
        After configuring the above, you can use email. I initiated the email after resetting the password . Let’s start with the back-end controller directly! Go straight to the topic, simple and rude, directly on the code!
/**
* @Desc  重置用户密码并发送邮件
* @Param
* @return
* @Date 2020/3/21 17:29
*/
@PostMapping("/sendMail")
@LoginRequired
public JsonData sendMail(@RequestParam(value = "toMail") String toMail,
                         @RequestParam(value = "userId") Long userId) {
    if (StringUtils.isEmpty(toMail)) {
        return JsonData.fail("用户邮箱不能为空");
    }
    //TODO 随机生成密码
    String defaultPassword = PasswordCreateUtil.createPassWord(8);
    User user = new User();
    user.setUserId(userId);
    user.setUserPassword(defaultPassword);
    int count = userService.updateUser(user);
    if (count > 0) {
        mailService.sendSimpleMail(toMail, "重置密码", "您的初始密码为:" + defaultPassword);
        return JsonData.success(count, "重置密码成功");
    } else {
        return JsonData.fail("重置密码失败");
    }
}

 
Let's talk about the logic roughly. First, after we click the reset password button on the front-end page, it triggers to our back-end controller, passes in the two parameters of userId and reset person's email account, and walks to our method. This method does three Thing:
1. Regenerate a password. Random numbers can be used to select abcd... and numbers to regenerate a password. As shown in row: 216
2. Assign the generated password to the new user and update the database user information. As shown in row: 217-220
3. After the database is successfully updated, go to the mailbox of the resetting person. As shown in row: 222-223
 
Next, we will introduce these three steps of logic separately
1. Regenerate a password. The Random and Math classes are mainly used here .
/**
* @param len
* @return : java.lang.String
* @author: zhupeng
* @date: 2020-03-24 21:19
* @description: 指定长度生成随机密码
*/
public static String createPassWord(int len) {
    int random = createRandomInt();
    return createPassWord(random, len);
}
private static String createPassWord(int random, int len) {
    Random rd = new Random(random);
    final int maxNum = 62;
    StringBuffer sb = new StringBuffer();
    int rdGet;//取得随机数
    char[] str = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
            'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
            'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
            'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
            'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};


    int count = 0;
    while (count < len) {
        //生成的数最大为62-1
        rdGet = Math.abs(rd.nextInt(maxNum));
        if (rdGet >= 0 && rdGet < str.length) {
            sb.append(str[rdGet]);
            count++;
        }
    }
    return sb.toString();
}


private static int createRandomInt() {
    //得到0.0到1.0之间的数字,并扩大100000倍
    double temp = Math.random() * 100000;
    //如果数据等于100000,则减少1
    if (temp >= 100000) {
        temp = 99999;
    }
    int tempint = (int) Math.ceil(temp);
    return tempint;
}

2. Assign the generated password to the new user and update the database user information.

The password is re-assigned here. MD5 is used for encryption. The user assignment uses lombok syntax. If you are interested, you can look at the usage of lombok, which can greatly simplify the code.
/**
* @Desc  更新用户
* @Param
* @return
* @Date 2020/3/21 17:39
*/
@Override
public int updateUser(User user) {
    if (checkUserNameExist(user.getUserName(), user.getUserId())) {
        throw new ParamException("用户名已被占用");
    }
    if (checkUserTrueNameExist(user.getUserTrueName(), user.getUserId())) {
        throw new ParamException("真实姓名已经存在");
    }
    if (checkUserEmailExist(user.getUserEmail(), user.getUserId())) {
        throw new ParamException("邮箱已被占用");
    }
    if (checkUserPhoneExist(user.getUserPhone(), user.getUserId())) {
        throw new ParamException("手机号已被占用");
    }
    User before = userMapper.selectByPrimaryKey(user.getUserId());
    Preconditions.checkNotNull(before, "需更新的用户不存在");
    User after = User.builder()
            .userId(user.getUserId())
            .userName(user.getUserName())
            .userTrueName(user.getUserTrueName())
            .userPassword(Md5Util.md5(user.getUserPassword(), Md5Util.SALT))
            .userEmail(user.getUserEmail())
            .userPhone(user.getUserPhone())
            .userState(user.getUserState())
            .build();
    int count = userMapper.updateByPrimaryKeySelective(after);
    return count;
}

3. After the database is successfully updated, go to the mailbox of the resetting person.


@Resource
private JavaMailSender mailSender;


@Value("${spring.mail.username}")
private String from;


/**
* @Desc  发送简单邮件
* @Param
* @return
* @Date 2020/3/21 17:36
*/
@Override
public void sendSimpleMail(String to, String subject, String content) {
    SimpleMailMessage message = new SimpleMailMessage();
    message.setFrom(from);
    message.setTo(to);
    message.setSubject(subject);
    message.setText(content);
    try {
        mailSender.send(message);
        log.info("简单邮件发送成功!");
    } catch (MailException e) {
        log.error("发送简单邮件时发生异常!" + e);
    }
}

 
Need to inject the JavaMailSender class, need to add this annotation @Resource, as shown in the figure above row: 25-26
Get the sender's email address. We have maintained the email address in Properties. You need to add a value annotation, which is the key of the parameter in order to obtain information. As shown above row: 28-29
Write a method of sending. I use a simple email method, and input three parameters, to: recipient's mailbox, subject: subject, which is the title of the email, content: content of the email
It is also a new SimpleMailMessage object, assigning the sender, recipient, subject, and content. Then call the send method of JavaMailSender.
The following is attached to the complex mail code, compared with simple mail, complex mail processing can not only send subject content, but also send picture files, etc. If you are interested, you can try it yourself!
  //复杂邮件
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom("[email protected]");
        messageHelper.setTo("[email protected]");
        messageHelper.setSubject("Happy New Year");
        messageHelper.setText("新年快乐!");
        messageHelper.addInline("doge.gif", new File("xx/xx/doge.gif"));
        messageHelper.addAttachment("work.docx", new File("xx/xx/work.docx"));
        mailSender.send(mimeMessage);

4. Actual combat effect

 
 
Record, summarize, share! Learning is always on the way!
 
 

Guess you like

Origin blog.csdn.net/qq_35340913/article/details/105469041