SpringBoot傳送郵件(三)

leepandar發表於2024-05-23

jdk:17
springboot:3.0+

POM依賴

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4.1</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.0.2</version>
</dependency>

工具類

/**
 * 郵件傳送訊息
 */
@UtilityClass
public class MailUtil {

	/**
	 * 郵件傳送訊息
	 *
	 * @param host     SMTP伺服器
	 * @param port     SMTP埠
	 * @param username SMTP使用者名稱
	 * @param password SMTP密碼
	 * @param from     發件人
	 * @param to       收件人
	 * @param subject  主題
	 * @param content  內容
	 */
	public Boolean sendNotice(String host, int port, String username, String password, String from, String protocol, String to, String subject, String content) {
		SimpleMailMessage message = new SimpleMailMessage();
		message.setSubject(subject);
		message.setText(content);
		message.setTo(to);
		message.setFrom(from);

		JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
		mailSender.setHost(host);
		mailSender.setPort(port);
		mailSender.setUsername(username);
		mailSender.setPassword(password);
		mailSender.setProtocol(protocol);
		mailSender.setDefaultEncoding(CommonConstants.UTF8);
		Properties properties = new Properties();
		Map<String, String> source = new HashMap<>();
		source.put("mail.smtp.auth", "true");
		source.put("mail.smtp.socketFactory.port", String.valueOf(port));
		source.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		source.put("mail.smtp.socketFactory.fallback", "false");
		source.put("mail.smtp.starttls.enable", "true");
		source.put("mail.smtp.starttls.required", "true");
		properties.putAll(source);
		mailSender.setJavaMailProperties(properties);
		mailSender.send(message);
		return Boolean.TRUE;
	}
}

相關文章