@yuradun

Почему не работает отправка email Java Spring Boot?

Добрый день, разбираю отправку email в spring.
Создал gmail почту, включил двухэтапную авторизацию, сделал специльный пароль для сторонних приложений по статье.
https://support.google.com/accounts/answer/185833

Проверяя testController письмо не отправляет, но в ответ присылает ошибку:
spoiler

{
    "message": "error",
    "code": 500,
    "payload": {
        "cause": null,
        "stackTrace": [
            {
                "classLoaderName": "app",
                "moduleName": null,
                "moduleVersion": null,
                "methodName": "emailSend",
                "fileName": "TestController.java",
                "lineNumber": 18,
                "nativeMethod": false,
                "className": "com.example.javatestapp.Controllers.TestController"
            },
            {
                "classLoaderName": null,
                "moduleName": "java.base",
                "moduleVersion": "17.0.4.1",
                "methodName": "invoke0",
                "fileName": "NativeMethodAccessorImpl.java",
                "lineNumber": -2,
                "nativeMethod": true,
                "className": "jdk.internal.reflect.NativeMethodAccessorImpl"
            },
            {
                "classLoaderName": null,
                "moduleName": "java.base",
                "moduleVersion": "17.0.4.1",
                "methodName": "invoke",
                "fileName": "NativeMethodAccessorImpl.java",
                "lineNumber": 77,
                "nativeMethod": false,
                "className": "jdk.internal.reflect.NativeMethodAccessorImpl"
            },
            {
                "classLoaderName": null,
                "moduleName": "java.base",
                "moduleVersion": "17.0.4.1",
                "methodName": "invoke",
                "fileName": "DelegatingMethodAccessorImpl.java",
                "lineNumber": 43,
                "nativeMethod": false,
                "className": "jdk.internal.reflect.DelegatingMethodAccessorImpl"
            },
            {
                "classLoaderName": null,
                "moduleName": "java.base",
                "moduleVersion": "17.0.4.1",
                "methodName": "invoke",
                "fileName": "Method.java",
                "lineNumber": 568,
                "nativeMethod": false,
                "className": "java.lang.reflect.Method"
            },
            {
                "classLoaderName": "app",
                "moduleName": null,
                "moduleVersion": null,
                "methodName": "doInvoke",
                "fileName": "InvocableHandlerMethod.java",
                "lineNumber": 207,
                "nativeMethod": false,
                "className": "org.springframework.web.method.support.InvocableHandlerMethod"
            },
            {
                "classLoaderName": "app",
                "moduleName": null,
                "moduleVersion": null,
                "methodName": "invokeForRequest",
                "fileName": "InvocableHandlerMethod.java",
                "lineNumber": 152,
                "nativeMethod": false,
                "className": "org.springframework.web.method.support.InvocableHandlerMethod"
            },
            {
                "classLoaderName": "app",
                "moduleName": null,
                "moduleVersion": null,
                "methodName": "invokeAndHandle",
                "fileName": "ServletInvocableHandlerMethod.java",
                "lineNumber": 118,
                "nativeMethod": false,
                "className": "org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod"
            },
            {
                "classLoaderName": "app",
                "moduleName": null,
                "moduleVersion": null,
                "methodName": "invokeHandlerMethod",
                "fileName": "RequestMappingHandlerAdapter.java",
                "lineNumber": 884,
                "nativeMethod": false,
                "className": "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
            },
            {
                "classLoaderName": "app",
                "moduleName": null,
                "moduleVersion": null,
                "methodName": "handleInternal",
                "fileName": "RequestMappingHandlerAdapter.java",
                "lineNumber": 797,
                "nativeMethod": false,
                "className": "org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"
            },
            {
                "classLoaderName": "app",
                "moduleName": null,
                "moduleVersion": null,
                "methodName": "handle",
                "fileName": "AbstractHandlerMethodAdapter.java",
                "lineNumber": 87,
                "nativeMethod": false,
                "className": "org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter"
            },
]
}
}



TestController.java

package com.example.javatestapp.Controllers;

import com.example.javatestapp.Payloads.Responses.MessageResponse;
import com.example.javatestapp.Services.EmailSenderService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping(path = {"api/v1"})
public class TestController {
    private EmailSenderService emailSenderService;
    @GetMapping("/email-send")
    public MessageResponse emailSend () {
        try {
            emailSenderService.sendEmail("mail@yandex.ru", "test message subject", "hello email sending");
            return new MessageResponse("ok", 200);
        } catch (Exception e) { return new MessageResponse("error", 500, e); }
    }
}



EmailSenderService.java

package com.example.javatestapp.Services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Service
public class EmailSenderService {
    @Autowired
    private JavaMailSender javaMailSender;

    public void sendEmail (String toEmail, String subjectEmail, String bodyEmail) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(toEmail);
        message.setSubject(subjectEmail);
        message.setText(bodyEmail);

        javaMailSender.send(message);
    }
}



application.properties

spring.datasource.url=jdbc:mysql://localhost:8889/javaTest
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.hibernate.ddl-auto=create

#Mail settings
spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=mail@gmail.com
spring.mail.password=jvtcbohqdagrtmzb
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true



pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.0.5</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>java-test-app</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>java-test-app</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- Dependencies for DB connect	-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.32</version>
		</dependency>

		<!-- Dependency provides a utility class for hashing	-->
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>31.0.1-jre</version>
		</dependency>

		<!-- Dependency for working with JSON -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.13.3</version>
		</dependency>

		<!-- Dependency for working with CSV -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-csv</artifactId>
			<version>1.8</version>
		</dependency>

		<!-- Dependency for send email -->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.jetbrains</groupId>
			<artifactId>annotations</artifactId>
			<version>RELEASE</version>
			<scope>compile</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>
</project>



В чем может быть проблема? Заранее спасибо за ответ.
  • Вопрос задан
  • 202 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы