[TODO] 邮件发送工具类 #12

Closed
opened 2024-10-09 08:07:20 +00:00 by xrilang · 0 comments
Owner

依赖


		<dependency>
			<groupId>com.sun.mail</groupId>
			<artifactId>jakarta.mail</artifactId>
			<version> 2.0.1</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-mail</artifactId>
			<version>3.3.4</version>
		</dependency>

配置:

#application.properties基本配置,后面我都使用此配置来发送邮件
## 基本配置
### smtp服务器主机(163的)
spring.mail.host=smtp.qiye.163.com
spring.mail.port=25
### 服务协议SMTP(代表是发送邮件)
spring.mail.protocol=smtp
### 登录服务器邮箱账号
spring.mail.username=news@mllt.cc
### 登录服务器邮箱授权码(不是邮箱密码,这个是我们开通SMTP、POP时得到的授权码)
spring.mail.password=Qq2686485465@
### 默认邮件的编码集(MimeMessage 编码,默认UTF-8)
spring.mail.default-encoding=UTF-8

# 补充配置(这里具体可以参照Jakarta Mail的扩展配置)
## 默认发送方邮箱账号(当程序未指定发件人邮箱则默认取这个)
spring.mail.properties.mail.smtp.from=news@mllt.cc
## 开启权限认证
spring.mail.properties.mail.smtp.auth=true
## 邮件接收时间的限制
spring.mail.properties.mail.smtp.timeout=60000
## 连接时间的限制
spring.mail.properties.mail.smtp.connectiontimeout=60000
## 邮件发送时间的限制(毫秒)
spring.mail.properties.mail.smtp.writetimeout=60000
## 日志打印,邮件发送过程的日志会被输出
spring.mail.properties.mail.debug=true
# 下面这条配置请去 src/main/java/com/guaiguailang/harmony/config/MailConfig.java 修改。在这里修改是无效的。因为这里写中文会导致乱码。
email.form.nickname=[和生]消息通知

package com.guaiguailang.harmony.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.Properties;
@Data
@Configuration
@PropertySource(value = "classpath:application.properties", encoding = "UTF-8")
public class MailConfig {

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

    @Value("${spring.mail.port}")
    private int port;

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

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

    @Value("${spring.mail.default-encoding}")
    private String defaultEncoding;

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

    @Value("${spring.mail.properties.mail.debug}")
    private String debug;
    @Value("[和生]消息通知")
    private String nickname;

    @Bean
    public JavaMailSender getJavaMailSender() {
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost(host);
        mailSender.setPort(port);
        mailSender.setUsername(username);
        mailSender.setPassword(password);
        Properties props = mailSender.getJavaMailProperties();
        props.put("mail.transport.protocol", protocol);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.starttls.enable", "false"); // 关闭STARTTLS
        props.put("mail.debug", debug);
        return mailSender;
    }

}

工具类实现


package com.guaiguailang.harmony.service.impl;

import com.guaiguailang.harmony.config.MailConfig;
import com.guaiguailang.harmony.service.EmailService;
import com.guaiguailang.harmony.utils.KeyBase64;
import jakarta.mail.internet.MimeMessage;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

@Service
public class EmailServiceImpl implements EmailService {
    @Autowired
    MailConfig mailConfig;

        @Override
        public void emailSend(String nickname,String to,String subject,String content) {
            nickname = KeyBase64.strToBase64(nickname);
            nickname = "=?UTF-8?B?"+nickname+"?=";
            JavaMailSender mailSender =  mailConfig.getJavaMailSender();
            try {
                MimeMessage ms = mailSender.createMimeMessage();
                MimeMessageHelper msi = new MimeMessageHelper(ms,true);
                msi.setFrom(nickname+' '+'<'+mailConfig.getUsername()+'>');//From 合法性检查  https://service.mail.qq.com/detail/0/995
                msi.setTo(to);
                msi.setSubject(subject);
                msi.setText(content,true);//true开启HTML解析
                mailSender.send(ms);
            }catch (Exception e){
                System.out.println(e);
            }
        }
    }



测试

package com.guaiguailang.harmony;
import com.guaiguailang.harmony.utils.UtilEmailSent;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class HarmonyLifeServerApplicationTests {
	@Autowired
	UtilEmailSent utilEmailSent;
	@Test
	void testEmailSentUtil() {
		utilEmailSent.sendEmail("2952458479@qq.com","测试邮件标题","测试邮件内容");
	}

}

## 依赖 ```xml <dependency> <groupId>com.sun.mail</groupId> <artifactId>jakarta.mail</artifactId> <version> 2.0.1</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> <version>3.3.4</version> </dependency> ``` 配置: ```xml #application.properties基本配置,后面我都使用此配置来发送邮件 ## 基本配置 ### smtp服务器主机(163的) spring.mail.host=smtp.qiye.163.com spring.mail.port=25 ### 服务协议SMTP(代表是发送邮件) spring.mail.protocol=smtp ### 登录服务器邮箱账号 spring.mail.username=news@mllt.cc ### 登录服务器邮箱授权码(不是邮箱密码,这个是我们开通SMTP、POP时得到的授权码) spring.mail.password=Qq2686485465@ ### 默认邮件的编码集(MimeMessage 编码,默认UTF-8) spring.mail.default-encoding=UTF-8 # 补充配置(这里具体可以参照Jakarta Mail的扩展配置) ## 默认发送方邮箱账号(当程序未指定发件人邮箱则默认取这个) spring.mail.properties.mail.smtp.from=news@mllt.cc ## 开启权限认证 spring.mail.properties.mail.smtp.auth=true ## 邮件接收时间的限制 spring.mail.properties.mail.smtp.timeout=60000 ## 连接时间的限制 spring.mail.properties.mail.smtp.connectiontimeout=60000 ## 邮件发送时间的限制(毫秒) spring.mail.properties.mail.smtp.writetimeout=60000 ## 日志打印,邮件发送过程的日志会被输出 spring.mail.properties.mail.debug=true # 下面这条配置请去 src/main/java/com/guaiguailang/harmony/config/MailConfig.java 修改。在这里修改是无效的。因为这里写中文会导致乱码。 email.form.nickname=[和生]消息通知 ``` ```java package com.guaiguailang.harmony.config; import lombok.Data; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.JavaMailSenderImpl; import java.util.Properties; @Data @Configuration @PropertySource(value = "classpath:application.properties", encoding = "UTF-8") public class MailConfig { @Value("${spring.mail.host}") private String host; @Value("${spring.mail.port}") private int port; @Value("${spring.mail.username}") private String username; @Value("${spring.mail.password}") private String password; @Value("${spring.mail.default-encoding}") private String defaultEncoding; @Value("${spring.mail.protocol}") private String protocol; @Value("${spring.mail.properties.mail.debug}") private String debug; @Value("[和生]消息通知") private String nickname; @Bean public JavaMailSender getJavaMailSender() { JavaMailSenderImpl mailSender = new JavaMailSenderImpl(); mailSender.setHost(host); mailSender.setPort(port); mailSender.setUsername(username); mailSender.setPassword(password); Properties props = mailSender.getJavaMailProperties(); props.put("mail.transport.protocol", protocol); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "false"); // 关闭STARTTLS props.put("mail.debug", debug); return mailSender; } } ``` 工具类实现 ```java package com.guaiguailang.harmony.service.impl; import com.guaiguailang.harmony.config.MailConfig; import com.guaiguailang.harmony.service.EmailService; import com.guaiguailang.harmony.utils.KeyBase64; import jakarta.mail.internet.MimeMessage; import org.apache.ibatis.annotations.Select; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.mail.MailProperties; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; @Service public class EmailServiceImpl implements EmailService { @Autowired MailConfig mailConfig; @Override public void emailSend(String nickname,String to,String subject,String content) { nickname = KeyBase64.strToBase64(nickname); nickname = "=?UTF-8?B?"+nickname+"?="; JavaMailSender mailSender = mailConfig.getJavaMailSender(); try { MimeMessage ms = mailSender.createMimeMessage(); MimeMessageHelper msi = new MimeMessageHelper(ms,true); msi.setFrom(nickname+' '+'<'+mailConfig.getUsername()+'>');//From 合法性检查 https://service.mail.qq.com/detail/0/995 msi.setTo(to); msi.setSubject(subject); msi.setText(content,true);//true开启HTML解析 mailSender.send(ms); }catch (Exception e){ System.out.println(e); } } } ``` 测试 ```java package com.guaiguailang.harmony; import com.guaiguailang.harmony.utils.UtilEmailSent; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class HarmonyLifeServerApplicationTests { @Autowired UtilEmailSent utilEmailSent; @Test void testEmailSentUtil() { utilEmailSent.sendEmail("2952458479@qq.com","测试邮件标题","测试邮件内容"); } } ```
Sign in to join this conversation.
No Label
No Milestone
No project
No Assignees
1 Participants
Notifications
Due Date
The due date is invalid or out of range. Please use the format 'yyyy-mm-dd'.

No due date set.

Dependencies

No dependencies set.

Reference: MengLangStudio/harmony-life-server#12
No description provided.