栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot:用腾讯企业微信邮箱发送邮件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot:用腾讯企业微信邮箱发送邮件

需求

商户审核状态需要异步发送短信、站内通知和发送邮件通知商户,且发送账户限定为腾讯企业微信邮箱

准备
  1. 准备发送邮箱的账户和密码写入配置文件
  2. 引入发送邮箱jar包
  3. 写异步线程发送固定html格式的邮件
实现代码

配置文件

mail:
  transport:
    protocol: ssl
  smtp:
    host: smtp.exmail.qq.com # 企业微信的host
    port: 465
    auth: true
    ssl:
      enable : true
  enable: true
  account: 企业邮箱账户
  password: 企业邮箱密码

引入发送邮箱jar包


com.sun.mail
jakarta.mail
1.6.7

代码块
定义一个接口:ISendEmailService

import java.util.List;


public interface ISendEmailService{
    
   void send(String fromAliasName,String to,String subject,String content, List attachFileList);
}

接口实现类:SendEmailServiceImpl

@Slf4j
@Service
public class SendEmailServiceImpl implements ISendEmailService{

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

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

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

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

    
    @Value("${mail.smtp.port}")
    private String port ;

    
    @Value("${mail.smtp.auth}")
    private String auth ;


    @Value("${mail.smtp.ssl.enable}")
    private String sslEnable ;



    
    @Override
    @Async(value = ExecutorConfig.EMAIL_ASYNC)
    public void send(String fromAliasName,String to,String subject,String content,List attachFileList) {
        // 设置邮件属性
        Properties prop = new Properties();
        prop.setProperty("mail.transport.protocol", protocol);
        prop.setProperty("mail.smtp.host", host);
        prop.setProperty("mail.smtp.port", port);
        prop.setProperty("mail.smtp.auth", auth);
        MailSSLSocketFactory sslSocketFactory = null;
        try {
            sslSocketFactory = new MailSSLSocketFactory();
            sslSocketFactory.setTrustAllHosts(true);
        } catch (GeneralSecurityException e1) {
            e1.printStackTrace();
        }
        if (sslSocketFactory == null) {
            log.error("开启 MailSSLSocketFactory 失败");
        } else {
            prop.put("mail.smtp.ssl.enable",sslEnable);
            prop.put("mail.smtp.ssl.socketFactory", sslSocketFactory);
            // 创建邮件会话(注意,如果要在一个进程中切换多个邮箱账号发信,应该用 Session.getInstance)
            Session session = Session.getDefaultInstance(prop, new MyAuthenticator(account, password));
            try {
                MimeMessage mimeMessage = new MimeMessage(session);
                // 设置发件人别名(如果未设置别名就默认为发件人邮箱)
                if (fromAliasName != null && !fromAliasName.trim().isEmpty()) {
                    mimeMessage.setFrom(new InternetAddress(account, fromAliasName));
                }
                // 设置主题和收件人、发信时间等信息
                mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
                mimeMessage.setSubject(subject);
                mimeMessage.setSentDate(new Date());
                // 如果有附件信息,则添加附件
                Multipart multipart = new MimeMultipart();
                MimeBodyPart body = new MimeBodyPart();
                body.setContent(content, "text/html; charset=UTF-8");
                multipart.addBodyPart(body);
                // 添加所有附件(添加时判断文件是否存在)
                if (CollectionUtils.isNotEmpty(attachFileList)){
                    for(String filePath : attachFileList){
                        if(Files.exists(Paths.get(filePath))){
                            MimeBodyPart tempBodyPart = new MimeBodyPart();
                            tempBodyPart.attachFile(filePath);
                            multipart.addBodyPart(tempBodyPart);
                        }
                    }
                }
                mimeMessage.setContent(multipart);
                // 开始发信
                mimeMessage.saveChanges();
                Transport.send(mimeMessage);
            }catch (Exception e) {
                log.error("发送邮件错误:{}",e.getMessage());
            }
        }
    }


    
    static class MyAuthenticator extends Authenticator {

        
        String username = null;

        
        String password = null;

        
        public MyAuthenticator(String username, String password) {
            this.username = username;
            this.password = password;
        }

        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(username, password);
        }
    }
}

异步线程池配置

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


@Configuration
@EnableAsync
public class ExecutorConfig{

    private int corePoolSize = 10;
    private int maxPoolSize = 50;
    private int queueCapacity = 100;

    
    public static final String EMAIL_ASYNC="emailAsync";




    @Bean
    public Executor emailAsync(){
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(corePoolSize);
        executor.setMaxPoolSize(maxPoolSize);
        executor.setQueueCapacity(queueCapacity);
        executor.setThreadNamePrefix(EMAIL_ASYNC);

        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }



}

调用方式

@RestController
@AllArgsConstructor
public class SendEmailController {

    @Autowired
    private ISendEmailService sendEmailService;

    
    @GetMapping("/sendMail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "发送邮件")
    public void 发送sendMail() {
    	sendEmailService.send("别名","邮件","【审核通过】","内容","附件");
    }


结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/837750.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号