package com.ruoyi.web.controller.tool; import lombok.extern.slf4j.Slf4j; import javax.mail.*; import javax.mail.internet.*; import java.io.UnsupportedEncodingException; import java.util.Date; import java.util.Properties; @Slf4j public class EmailUtils { public static void sendEmail(String userEmail, String sendEmail, String code, String content) throws Exception { // 发送邮箱 // 收件人电子邮箱,TODO 换成自己的收件箱 String to = userEmail; // 发件人电子邮箱,TODO 换成自己的发件箱 String from = sendEmail; // 指定发送邮件的主机为 String host = "smtp.163.com"; Properties properties = new Properties(); properties.put("mail.smtp.host", host); properties.put("mail.smtp.socketFactory.port", "465"); properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.put("mail.smtp.auth", "true"); properties.put("mail.smtp.port", "465"); properties.put("mail.smtp.ssl.enable", "true"); // 明确开启SSL // 获取默认session对象 Session session = Session.getDefaultInstance(properties,new Authenticator(){ @Override public PasswordAuthentication getPasswordAuthentication() { //发件人邮件用户名、授权码,换成自己的发件箱及授权码 return new PasswordAuthentication(from, code); } }); try{ // 创建默认的 MimeMessage 对象 MimeMessage message = new MimeMessage(session); // Set From,设置发件人 InternetAddress fromMail = new InternetAddress(from); //设置发件人名称,TODO 换成自己的发件箱 fromMail.setPersonal(MimeUtility.encodeText("沿海市政<" + from + ">")); message.setFrom(fromMail); // Set To: 设置收件人 InternetAddress toMail = new InternetAddress(to); // TODO 换成自己的收件箱 InternetAddress toMail2 = new InternetAddress(to); //发多个邮箱 Address[] allRecipients = {toMail, toMail2}; message.setRecipients(Message.RecipientType.TO, allRecipients); // Set Subject: 邮件主体 message.setSubject("沿海市政"); // 设置消息体 message.setSentDate(new Date()); MimeMultipart msgMultipart = new MimeMultipart("mixed"); // 指定为混合关系 message.setContent(msgMultipart); // 邮件信息组装 //组装的顺序非常重要,一定要先组装文本域,再组装文件 MimeBodyPart htmlPart = new MimeBodyPart(); // 组装内容 htmlPart.setContent(content, "text/html;charset=UTF-8"); msgMultipart.addBodyPart(htmlPart); try { message.saveChanges(); //发送 //Transport.send(message, message.getAllRecipients()); Transport.send(message); System.out.println("发送成功"); } catch (Exception e) { e.printStackTrace(); } }catch (MessagingException | UnsupportedEncodingException mex) { mex.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }