Springboot2.x 整合javamail設定最大執行緒
阿新 • • 發佈:2020-11-05
由於在工作中碰到一個臺灣客戶的郵箱,在傳送郵件時,php庫的swiftmail 對該郵箱支援不夠好,經實驗測試javamail更適合做網路底層通訊,故在 原有php業務基礎上加 一套javamail用來發送特殊郵箱。
- 新增javamail座標到pom.xml
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>jakarta.mail</artifactId>
<version>1.6.5</version>
</dependency>
- 配置傳送郵件的執行緒池
@Configuration
@EnableAsync
public class AsyncThreadConfiguration {
@Bean("smtpMailer")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(10);// 核心執行緒數(最小執行緒數)
executor.setMaxPoolSize(50); // 設定最大執行緒
executor.setQueueCapacity(200); // 用來緩衝執行任務的佇列
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("smtpmail-"); // 設定執行緒名稱
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setAwaitTerminationSeconds(60);
executor.initialize();
return executor;
}
}
- 建立傳送郵件的實體
package cn.http.request;
import cn.http.request.interfaces.SendMailerInterfaces;
import lombok.Data;
import javax.validation.constraints.*;
import java.util.List;
import java.util.Map;
@Data
public class SmtpRequest
{
@NotBlank(message = "SMTP郵件伺服器不能為空",groups = {SendMailerInterfaces.class})
private String smtpHost;
private int isSSL = 1;
@Email(message = "發件箱格式有誤",groups = {SendMailerInterfaces.class})
@NotBlank(message ="發件箱不能為空")
private String sendEmail ;
@NotBlank(message = "發件密碼或授權碼不能為空",groups = {SendMailerInterfaces.class})
private String password;
// 多個收件地址使用 英文逗號隔開
@NotBlank(message = "收件人郵箱地址不能為空",groups = {SendMailerInterfaces.class})
private String receiveEmail;
// 多個回覆地址使用 英文逗號隔開
private String replyEmail;
private String cc; // 抄送 英文逗號隔開
private String bcc; // 密送 英文逗號隔開
@NotBlank(message = "發件主題不能為空",groups = {SendMailerInterfaces.class})
private String subject;
private String body; // 郵件內容
private List<Map<String,Object>> attachs = null; // 附件
private String messageId; // 郵件的 MessageId
// 是否加入回執
private int isReceipt = 0;
// 是否緊急
private int isPriority = 0;
// 是否加入追蹤
private int isTrace = 0;
// 是否非同步傳送
private int isAsync = 1;
}
- 傳送郵件的核心程式碼
package cn.task;
import cn.http.request.SmtpRequest;
import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.activation.DataHandler;
import javax.mail.*;
import javax.mail.internet.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.GeneralSecurityException;
import java.util.*;