介绍
发邮件mail是常见的软件功能,下面利于spring和java的mail库实现发送内容支持html,带多附件的案例
开启SMTP邮件发送协议
谁提供的SMTP邮件服务,就找谁开启。QQ邮箱类似。
依赖
bash
<!--Java MAil 发送邮件API-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>javax.mail-api</artifactId>
<version>1.6.2</version>
</dependency>
代码
bash
package com.mail;
import com.sun.xml.internal.messaging.saaj.packaging.mime.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
/**
* @version v1.0 创建时间:2023/11/20 15:59
* @author: 作者:陈子枢
* @web CSDN:https://blog.csdn.net/nutony
* @description 描述:读取属性配置文件,发送邮件
*/
@Slf4j
@PropertySource("classpath:mail.properties")
public class MailClient {
@Value("${host}")
private String minioUrl;
@Value("${port}")
private int port;
public static void sender(String form, String cc, String subject, String html, List<String> attachments) throws javax.mail.MessagingException {
JavaMailSenderImpl sender = new JavaMailSenderImpl();
sender.setHost("smtp.163.com");
sender.setPort(25);
sender.setUsername(form);
sender.setPassword("配置的授权码");
sender.setDefaultEncoding("UTF-8");
// 简化对mimeMessage的封装
MimeMessage message = sender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(sender.createMimeMessage(), true, "UTF-8");
helper.setFrom(sender.getUsername()); //邮件发送人
helper.setCc(cc); //抄送
helper.setSubject(subject); //标题
helper.setText(html,true); //正文
//邮件附件
for(String attachment: attachments) {
File file = new File(attachment);
helper.addAttachment(file.getName(), file);
}
sender.send(helper.getMimeMessage());
}
public static void main(String[] args) throws MessagingException, javax.mail.MessagingException {
List<String> attachments = new ArrayList<>();
attachments.add("d:\\1.png");
attachments.add("d:\\2.png");
MailClient.sender("13261758319@163.com", "52399178@qq.com", "HTML邮件", "<h1 style='color:red'>hello,world!</h1>",attachments);
log.info("邮件发送成功!");
}
}