package com.ruoyi.business.util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;
import java.io.File;
import java.util.Date;
import java.util.Properties;
public class MailMessage {
private static final Logger log = LoggerFactory.getLogger(MailMessage.class);
// 初始化参数
private static Properties prop;
// 发件人
private static InternetAddress sendMan = null;
static {
prop = new Properties();
prop.put(“mail.transport.protocol”, “smtp”); // 指定协议
prop.put(“mail.smtp.host”, “smtp.163.com”); // 主机 stmp.qq.com
// prop.put(“mail.smtp.port”, 25); // 端口
prop.put(“mail.smtp.auth”, “true”); // 用户密码认证
prop.put(“mail.debug”, “true”); // 调试模式
try {
sendMan = new InternetAddress(“rebah_1@163.com”);
} catch (AddressException e) {
throw new RuntimeException(e);
}
}
/**
*
* @param filePath 文件地址
* @param mailAddr 收件人邮箱地址
* @throws Exception
*/
public static void testSend(String filePath,String mailAddr) throws Exception {
// 1. 创建邮件会话
Session session = Session.getDefaultInstance(prop);
// 2. 创建邮件对象
MimeMessage message = new MimeMessage(session);
// 3. 设置参数:标题、发件人、收件人、发送时间、内容
message.setSubject("环球医疗健康中心");
message.setSender(sendMan);
message.setRecipient(Message.RecipientType.TO, new InternetAddress("1030245828@qq.com"));
message.setSentDate(new Date());
/*
* 带附件(图片)邮件开发
*/
// 构建一个总的邮件块
MimeMultipart mixed = new MimeMultipart("mixed");
// ---> 总邮件快,设置到邮件对象中
message.setContent(mixed);
// 右侧: 附件
MimeBodyPart mimeBodyPart = new MimeBodyPart();
// 设置到总邮件块
mixed.addBodyPart(mimeBodyPart);
/****** 附件 ********/
File file = new File(filePath);
DataSource dataSource1=new FileDataSource(file);
//DataSource dataSource1=new ByteArrayDataSource(is, "application/png");
DataHandler attr_handler = new DataHandler(dataSource1);
mimeBodyPart.setDataHandler(attr_handler);
mimeBodyPart.setFileName(MimeUtility.encodeText(file.getName()));
/*************** 设置邮件内容: 多功能用户邮件 (related) *******************/
//构建一个多功能邮件块
MimeMultipart related = new MimeMultipart("related");
// 构建多功能邮件块内容 = 左侧文本 + 右侧图片资源
MimeBodyPart content = new MimeBodyPart();
// 设置具体内容: b.文本
content.setContent("<img src='cid:mm.png'/> 好哈哈!", "text/html;charset=UTF-8");
related.addBodyPart(content);
related.addBodyPart(mimeBodyPart);
// 发送
Transport trans = session.getTransport();
trans.connect("rebh_1@163.com", "12333333");//password并不是登录密码是授权密码
trans.sendMessage(message, message.getAllRecipients());
trans.close();
}
}