Implement Email Sending in Java

Introduction

I wanted to reset the password in the Spring Boot project, but it is a memorandum that I tried to see if I could send the initialized password by email.

First of all, environment settings

The environment is IDE:Eclipse ** Version: Java8, springframework.boot version 2.3.0 **

Also, an SMTP server is required to send mail, but it seems that it can not actually be sent locally, so this time I will use Google's SMTP easily.

build what you need for build gradle

build.gradle

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-mail'
    // https://mvnrepository.com/artifact/org.apache.commons/commons-lang3
    //Commons for randomly generating password strings-Compile lang3
    compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.10'
}

application.propeties

<!--Gmailsmtp settings-->
spring.mail.host=smtp.gmail.com
spring.mail.port=587

<!--Local smtp settings-->
<!-- spring.mail.host=localhost -->
<!-- spring.mail.port=25 -->

spring.mail.username=*****@*****
spring.mail.password=******
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

Enter the sender's email address in username and the password of the google account with that email address in password. As mentioned in the comment, ** If you are in a local environment, set host to localhost and enter the default port number **.

Create view and controller

Create an input form that specifies the post method in html. If you enter an email address and press the send button, the email will be sent to that address. (Since it is not the main line, it is omitted)

Controller

import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.entity.User;
import com.example.demo.service.UserService;

@Controller
@RequestMapping("passReset")
public class PassResetController {
	@Autowired
	private UserService userService;
	@Autowired
	private MailSender mailSender;

	@GetMapping
	public ModelAndView passResetPage(ModelAndView mav) {
		return mav;
	}

	@PostMapping
	public ModelAndView passResetSend(@RequestParam(name = "email") String email,
																User user,
																ModelAndView mav) {
		SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setTo(email);
        user = userService.findUserByEmail(email);
        if (user == null) {
        	simpleMailMessage.setTo(email);
        	simpleMailMessage.setSubject("Password reset notification");
            simpleMailMessage.setText("**Is a service\n\r\n\r" + email + "\n\r\n\r This account does not exist");
            this.mailSender.send(simpleMailMessage);
			mav.setViewName("redirect:login");
			return mav;
        }
        String password = RandomStringUtils.randomAscii(8);;
        userService.accountEdit(user.getEmail(), password);
        simpleMailMessage.setTo(email);
        simpleMailMessage.setSubject("Password reset notification");
        simpleMailMessage.setText("**Is a service\n\r\n\r" + email + "\n\r\n\r You have reset the password for this account.\n\r\n\r Reset password:" + password + "\n\r\n\r After logging in, please reset your password yourself.");
        this.mailSender.send(simpleMailMessage);
        mav.setViewName("redirect:login");
		return mav;
	}
}

What you are doing with the post method

  1. Access the DB with the email address sent from view and search for users
  2. If the user does not exist, state in the body of the email that the account does not exist
  3. If the user exists, randomly generate a password (RandomStringutils.randomAscii) and change the password of the user in the DB
  4. Enter the changed password in plain text in the body of the email

It becomes the flow of.

Notes on this implementation

Actually, it would be better to use UUID instead of RandomStringUtils for security, but considering the handling of symbols etc., I thought that StringUtils would be easier, so I used this. Also, if you have set up 2-step authentication with your Google account, you will not be able to log in to the application, so you need to disable this in advance.

Summary

With this kind of feeling, security is awkward, but I think I managed to grasp the flow. I also tried it on a local SMTP server, but I was able to check the mail sent to the server in the same way (although the settings are slightly different), so I felt that this is a realistic range in the local environment. It was.

Recommended Posts

Implement Email Sending in Java
Implement two-step verification in Java
Implement Basic authentication in Java
Implement functional quicksort in Java
Implement rm -rf in Java.
Implement XML signature in Java
Implement Table Driven Test in Java 14
I sent an email in Java
Implement reCAPTCHA v3 in Java / Spring
Implement PHP implode function in Java
Try to implement Yubaba in Java
1 Implement simple lexical analysis in Java
How to implement Kalman filter in Java
Implement API Gateway Lambda Authorizer in Java Lambda
Partization in Java
Try to implement n-ary addition in Java
Changes in Java 11
Rock-paper-scissors in Java
Implement something like a stack in Java
Pi in Java
FizzBuzz in Java
I want to send an email in Java.
Send email using Amazon SES SMTP in Java
I tried to implement deep learning in Java
[java] sort in list
Read JSON in Java
Interpreter implementation in Java
Make Blackjack in Java
Rock-paper-scissors app in Java
Constraint programming in Java
Put java8 in centos7
NVL-ish guy in Java
Combine arrays in Java
"Hello World" in Java
Comments in Java source
Azure functions in java
Format XML in Java
Simple htmlspecialchars in Java
Boyer-Moore implementation in Java
Hello World in Java
Use OpenCV in Java
Type determination in Java
Various threads in java
Heapsort implementation (in java)
Zabbix API in Java
ASCII art in Java
Compare Lists in Java
POST JSON in Java
Express failure in Java
Implement CustomView in code
Create JSON in Java
Date manipulation in Java 8
What's new in Java 8
Use PreparedStatement in Java
What's new in Java 9,10,11
Parallel execution in Java
Initializing HashMap in Java
Implement markdown in Rails
Write ABNF in Java and pass the email address
I tried to implement Firebase push notification in Java
Quickly implement a singleton with an enum in Java