package com.sdj.cashier.agent.center.common.utils;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* Copyright (C),
*
* @Description: email工具
* @ClassName: MailUtil
* @Package com.common.utils
* @Author: hanning
* @Date: 2022/1/14 下午2:26
* CREATE WITH IntelliJ IDEA
* History:
* <author> <time> <version> <desc>
* 作者姓名 修改时间 版本号 描述
*/
public class MailUtil {
private static JavaMailSenderImpl javaMailSender;
// 发件人
private static final String SENDER = "xxx@126.com";
static {
javaMailSender = new JavaMailSenderImpl();
javaMailSender.setHost("smtp.126.com");// 链接服务器
// javaMailSender.setPort(25);// 默认使用25端口发送
javaMailSender.setUsername("xxx@126.com");// 邮箱账号
// javaMailSender.setPassword("VMJKKSSQJQHZWPHM");// 授权码
javaMailSender.setPassword("xxx");// 授权码
javaMailSender.setDefaultEncoding("UTF-8");
// javaMailSender.setProtocol("smtp");
// Properties properties = new Properties();
// properties.setProperty("mail.debug", "true");// 启用调试
// properties.setProperty("mail.smtp.timeout", "1000");// 设置链接超时
// 设置通过ssl协议使用465端口发送、使用默认端口(25)时下面三行不需要
// properties.setProperty("mail.smtp.auth", "true");// 开启认证
// properties.setProperty("mail.smtp.socketFactory.port", "465");// 设置ssl端口
// properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
// javaMailSender.setJavaMailProperties(properties);
}
public static void main(String[] args) throws Exception {
// sendSimpleMail(new String[]{"xxx@qq.com"}, "邮件主题", "邮件内容", false);
File file = new File("xx../file/xxx.docx");
Map map = new HashMap();
map.put(file.getName(),file);
sendAttachmentMail(new String[]{"xxx@qq.com"}, "邮件主题", "邮件内容", map);
}
/**
* 发送普通邮件
*
* @param to 收件人
* @param subject 主题
* @param text 正文
* @param isHtml 正文是否为html格式
*/
public static void sendSimpleMail(String[] to, String subject, String text, boolean isHtml) throws Exception {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(SENDER, "通知");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text, isHtml);
javaMailSender.send(message);
}
/**
* 发送带附件邮件
*
* @param to 收件人
* @param subject 主题
* @param text 正文
* @param files 附件
*/
public static void sendAttachmentMail(String[] to, String subject, String text, Map<String, File> files) throws Exception {
MimeMessage message = javaMailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message, true);
helper.setFrom(SENDER, "通知");
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
Set<Map.Entry<String, File>> fileSet = files.entrySet();
for (Map.Entry f : fileSet) {
helper.addAttachment((String) f.getKey(), (File) f.getValue());
}
javaMailSender.send(message);
}
}
email工具
最新推荐文章于 2024-06-09 18:24:15 发布