Browse Source

feat: "初步完成邮箱服务"

Leonezhurui 2 years ago
parent
commit
770d4d48e4

+ 6 - 0
pom.xml

@@ -114,6 +114,12 @@
             <version>5.9</version>
         </dependency>
 
+        <!--邮箱依赖-->
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-mail</artifactId>
+        </dependency>
+
 
 
     </dependencies>

+ 54 - 0
src/main/java/com/njuzr/eaibackend/service/EmailService.java

@@ -0,0 +1,54 @@
+package com.njuzr.eaibackend.service;
+
+import jakarta.mail.MessagingException;
+import jakarta.mail.internet.MimeMessage;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.mail.SimpleMailMessage;
+import org.springframework.mail.javamail.JavaMailSender;
+import org.springframework.mail.javamail.JavaMailSenderImpl;
+import org.springframework.mail.javamail.MimeMessageHelper;
+import org.springframework.stereotype.Service;
+
+/**
+ * @author: Leonezhurui
+ * @Date: 2024/2/21 - 20:35
+ * @Package: EAI-Backend
+ */
+
+@Slf4j
+@Service
+public class EmailService {
+    private final JavaMailSender javaMailSender = new JavaMailSenderImpl();
+
+    @Value("${spring.mail.username}")
+    private String sourceEmail;
+
+    public int sendPasswordEmail(String to, String username, String password) throws MessagingException {
+        try {
+            MimeMessage message = javaMailSender.createMimeMessage();
+            MimeMessageHelper helper = new MimeMessageHelper(message, true);
+
+            helper.setFrom(sourceEmail);
+            helper.setTo(to);
+            helper.setSubject("Your New Account");
+
+            String htmlContent = "<h1>欢迎来到EAI天地!</h1>" +
+                    "<p>亲爱的<b>" + username + "</b>同学,</p>" +
+                    "<p>你的EAI账号已经创建,初始密码是<b>" + password + "</b></p>" +
+                    "<p>请在登陆后尽快修改密码!</p>" +
+                    "<p><a href='https://example.com/login'>登陆的虫洞~</a></p>" +
+                    "<p>祝你的专业写作能力不断提升,<br>Seecoder EAI开发团队</p>";
+
+            helper.setText(htmlContent, true);
+
+            javaMailSender.send(message);
+            log.info("邮件发送成功!==> 收件人:{}", username);
+            return 1;
+        } catch (Exception e) {
+            log.error("邮件发送失败!==> {}",e.getMessage());
+            return 0;
+        }
+    }
+}

+ 23 - 11
src/main/java/com/njuzr/eaibackend/service/impl/UserServiceImpl.java

@@ -6,11 +6,13 @@ import com.njuzr.eaibackend.dto.UserRegisterDTO;
 import com.njuzr.eaibackend.exception.MyException;
 import com.njuzr.eaibackend.mapper.UserMapper;
 import com.njuzr.eaibackend.po.User;
+import com.njuzr.eaibackend.service.EmailService;
 import com.njuzr.eaibackend.service.UserService;
 import com.njuzr.eaibackend.utils.ModelMapperUtil;
 import com.njuzr.eaibackend.vo.UserVO;
 import com.opencsv.CSVReader;
 import com.opencsv.exceptions.CsvValidationException;
+import jakarta.mail.MessagingException;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.poi.ss.usermodel.Cell;
 import org.apache.poi.ss.usermodel.Row;
@@ -44,6 +46,8 @@ public class UserServiceImpl implements UserService {
 
     private final UserMapper userMapper;
 
+    private final EmailService emailService = new EmailService();
+
     private final PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
 
     @Autowired
@@ -109,6 +113,7 @@ public class UserServiceImpl implements UserService {
 
     /**
      * 解析文件,批量创建用户。其中,文件必须包含姓名、邮箱、学号。
+     * TODO 完善邮箱服务(需要公邮和stmp秘钥)
      * @param file
      * @return
      */
@@ -141,6 +146,7 @@ public class UserServiceImpl implements UserService {
 
         int res = userMapper.batchInsert(users);
         if (res == 0) throw new MyException(500, "批量创建失败");
+        processUsers(users);
     }
 
     @Override
@@ -169,6 +175,7 @@ public class UserServiceImpl implements UserService {
 
         int res = userMapper.batchInsert(users);
         if (res == 0) throw new MyException(500, "批量创建失败");
+        processUsers(users);
     }
 
     private int findColumnIndex(Row headerRow, String columnName) {
@@ -189,16 +196,21 @@ public class UserServiceImpl implements UserService {
         return -1;
     }
 
-//    private void processUsers(List<User> users) {
-//        for(User user: users) {
-//            // 随机生成密码,并使用BCryptPasswordEncoder加密密码
-//            String randomPassword = UUID.randomUUID().toString();
-//            String encodedPassword = passwordEncoder.encode(randomPassword);
-//            user.setPassword(encodedPassword);
-//        }
-//        int res = userMapper.batchInsert(users);
-//        if (res == 0) throw new MyException(500, "批量创建失败");
-//        // TODO 通过邮箱服务,将初始密码发送给指定邮箱
-//    }
+    private void processUsers(List<User> users) throws MessagingException {
+        List<String> passwordStage = new ArrayList<>();
+        for(User user: users) {
+            // 随机生成密码,并使用BCryptPasswordEncoder加密密码
+            String randomPassword = UUID.randomUUID().toString();
+            passwordStage.add(randomPassword);
+            String encodedPassword = passwordEncoder.encode(randomPassword);
+            user.setPassword(encodedPassword);
+        }
+        int res = userMapper.batchInsert(users);
+        if (res == 0) throw new MyException(500, "批量创建失败");
+        // TODO 通过邮箱服务,将初始密码发送给指定邮箱
+        for (int i = 0; i < users.size(); i++) {
+            emailService.sendPasswordEmail(users.get(i).getOfficialEmail(), users.get(i).getName(), passwordStage.get(i));
+        }
+    }
 
 }

+ 9 - 0
src/main/resources/application.yaml

@@ -4,9 +4,18 @@ spring:
     username: root
     password: Zr200012
     url: jdbc:mysql://localhost:3306/EAI?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
+  mail:
+    host: smtp.163.com
+    port: 25
+    username: xxx # Seecoder的公共邮箱
+    password: xxx # 邮箱开启stmp的秘钥
+    default-encoding: UTF-8
+
+
 
 jwt:
   # jjwt密钥算法HS256,要求secret长度至少是256位
   secret: xTv@UA7e2q$*n&92AHo5Wj$@KAnguhxTv@UA7e2q$*n&92AHo5Wj$@KAnguhxTv@UA7e2q$*n&92AHo5Wj$@KAnguhxTv@UA7e2q$*n&92AHo5Wj$@KAnguhxTv@UA7e2q$*n&92AHo5Wj$@KAnguhxTv@UA7e2q$*n&92AHo5Wj$@KAnguhxTv@UA7e2q$*n&92AHo5Wj$@KAnguhxTv@UA7e2q$*n&92AHo5Wj$@KAnguh92AHo5Wj$@KAnguh92AHo5Wj$@KAnguh92AHo5Wj$@KAnguh
   issuer: eai
   expiration: 86400
+

+ 32 - 0
src/test/java/com/njuzr/eaibackend/service/EmailServiceTest.java

@@ -0,0 +1,32 @@
+package com.njuzr.eaibackend.service;
+
+import jakarta.mail.MessagingException;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.test.context.SpringBootTest;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+/**
+ * @author: Leonezhurui
+ * @Date: 2024/2/21 - 21:15
+ * @Package: EAI-Backend
+ */
+
+@SpringBootTest
+public class EmailServiceTest {
+    private final EmailService emailService;
+
+    @Autowired
+    public EmailServiceTest(EmailService emailService) {
+        this.emailService = emailService;
+    }
+
+
+    @Test
+    public void testEmailSender() throws MessagingException {
+        int res = emailService.sendPasswordEmail("Leonezhurui@gmail.com", "小苏", "123456");
+        assertEquals(1, res);
+
+    }
+}