依賴:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.4.7</version>
</dependency>
代碼:
public class MailUtil {
private static final String HOST = "stmp.xxxxx.com";
private static final String SENDER = "xxxxxxx@qq.com";
private static final String PASS_TOKEN = "xfvraxxxxxhirxxxbighe";
private Session session;
private Message msg;
private InternetAddress[] sendTo;
private String subject;
private String content;
public MailUtil(String subject, String content, List<String> toList) throws Exception {
this.init(subject, content, toList);
}
private void init(String subject, String content, List<String> toList) throws MessagingException {
this.subject = subject;
this.content = content;
Properties props = new Properties();
props.setProperty("mail.smtp.auth", "true");
props.setProperty("mail.transport.protocol", "smtp");
props.put("mail.smtp.HOST", HOST);//服務(wù)器地址
//初始化session
this.session = Session.getInstance(props);
session.setDebug(true);
//初始化發(fā)送地址列表
this.sendTo = new InternetAddress[toList.size()];
for (int i = 0, j = toList.size(); i < j; i++) {
this.sendTo[i] = new InternetAddress(toList.get(i));
}
//初始化message
this.msg = new MimeMessage(session);
this.msg.setSubject(this.subject);
this.msg.setSentDate(new Date());
//發(fā)件人郵箱
this.msg.setFrom(new InternetAddress(this.SENDER));
//收件人郵箱
this.msg.setRecipients(Message.RecipientType.TO,
this.sendTo);
}
private void sendMessage() throws Exception {
//這時Transport對象與相應(yīng)傳輸協(xié)議通信,這里是SMTP協(xié)議
Transport transport = session.getTransport();
// 登錄郵箱 。配置發(fā)件人郵箱,密碼或授權(quán)碼
transport.connect(SENDER, PASS_TOKEN);
//發(fā)送郵件
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();
}
public void send() throws Exception {
msg.setText(content);
this.sendMessage();
}
public void send(List<String> files) throws Exception {
List<File> fileList = new ArrayList<>(files.size());
files.forEach(x -> fileList.add(new File(x)));
Multipart multipart = new MimeMultipart();
// 設(shè)置正文
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(content, "text/html;charset=utf-8");
multipart.addBodyPart(messageBodyPart);
if (files.size() > 0) {
for (File file : fileList) {
BodyPart attachmentPart = new MimeBodyPart();
DataSource source = new FileDataSource(file);
attachmentPart.setDataHandler(new DataHandler(source));
//避免中文亂碼的處理
attachmentPart.setFileName(file.getName());
multipart.addBodyPart(attachmentPart);
}
}
// 發(fā)送完整消息
msg.setContent(multipart);
msg.saveChanges();
this.sendMessage();
}
public static void main(String[] args) throws Exception {
List<String> sendTo = new ArrayList<>();
sendTo.add("1111111@qq.com");
List<String> files = new ArrayList<>();
files.add("C:\\阿里巴巴Java開發(fā)...1528268103.pdf");
files.add("C:\\Desktop\\數(shù)據(jù)庫.txt");
//帶附件
new MailUtil("java主題", "java內(nèi)容 hello world", sendTo).send(files);
//不帶附件
new MailUtil("java主題", "java內(nèi)容 hello world", sendTo).send();
}