发送邮件工具类

发送邮件工具类

import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.*;

public class Sendmail {
    /**
     * 自动读取配置文件发件人信息,然后发送指定内容到指定人员
     * 创建时间: 2019年9月17日上午10:03:23
     * @param subject 邮件的主题
     * @param text 邮件的内容
     * @param toEmail 发送邮箱的数组
     * @throws CustomException sendEmailHtml  FilesUtil
     */
	public static void sendEmailHtmlNoFrom(String subject,String text,String... toEmail){
		for (String email : toEmail) {// 遍历发送邮箱
			sendEmailHtml(FilesUtil.FILE_PATH.get("fromEmailName"),FilesUtil.FILE_PATH.get("fromEmailUser"),
					FilesUtil.FILE_PATH.get("fromEmailPassword"),FilesUtil.FILE_PATH.get("fromEmailSubject")+":"+subject, text,email);
		}
	}
    /**
     * 自动读取配置文件发件人信息,然后发送指定内容到指定人员 拥有附件
     * 创建时间: 2020年8月07日上午10:03:23
     * @param subject 邮件的主题
     * @param text 邮件的内容
     * @param toEmail 发送邮箱的数组
     * @param filePath 文件路径
     * @param fileName 文件名称
     * @throws CustomException sendEmailHtml  FilesUtil
     */
	public static void sendEmailHtmlNoFromWithFile(String subject,String text,String filePath,String fileName,String... toEmail) {
		for (String email : toEmail) {// 遍历发送邮箱
			sendEmailHtmlWithFile(FilesUtil.FILE_PATH.get("fromEmailName"),FilesUtil.FILE_PATH.get("fromEmailUser"),
					FilesUtil.FILE_PATH.get("fromEmailPassword"),FilesUtil.FILE_PATH.get("fromEmailSubject")+":"+subject,filePath,fileName, text,email);
		}
    }
	/**
	 * 指定发件人发送指定内容到指定人员
	 * 创建时间: 2019年9月17日上午10:03:27
	 * @param name 发件人名称
	 * @param fromEmail 发件人邮箱
	 * @param password 发件人客户端授权码
	 * @param subject 邮件的主题
     * @param text 邮件的内容
     * @param toEmail 发送邮箱的数组
	 * @throws CustomException 邮件发送失败
	 */
	public static void sendEmailHtml(String name,final String fromEmail,final String password,
			String subject,String text,String... toEmail) { // 收件人电子邮箱
        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp."+fromEmail.substring(fromEmail.lastIndexOf("@")+1); 
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication(){
           return new PasswordAuthentication(fromEmail,password); //发件人邮件用户名、授权码
            }
         });
        try{
           // 创建默认的 MimeMessage 对象
           MimeMessage message = new MimeMessage(session);
   
           // Set From: 头部头字段
           name=MimeUtility.encodeText(name); 
           message.setFrom(new InternetAddress(name+"<"+fromEmail+">"));
           if(toEmail.length>1) {// 抄送发件人
               message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(fromEmail)); 
           }
           // Set To: 头部头字段
           for (String string : toEmail) {
               message.addRecipient(Message.RecipientType.TO,
                       new InternetAddress(string));
          }
           // Set Subject: 头部头字段
           message.setSubject(subject);
           message.setContent("<div>"+text+"</div>" ,
                   "text/html;charset=UTF-8" ); // 设置消息体
           Transport.send(message);  // 发送消息
        }catch (Exception mex) {
           mex.printStackTrace();
           System.err.println("邮箱发送失败:"+mex.getMessage());
        }
    }
    /**
     * 指定发件人发送指定内容到指定人员 拥有附件
     * 创建时间: 2020年08月07日上午15:03:27
     * @param name 发件人名称
     * @param fromEmail 发件人邮箱
     * @param password 发件人客户端授权码
     * @param subject 邮件的主题
     * @param text 邮件的内容
     * @param filePath 附件路径
     * @param fileName 附件名称
     * @param toEmail 发送邮箱的数组
     * @throws CustomException 邮件发送失败
     */
    public static void sendEmailHtmlWithFile(String name,final String fromEmail,final String password,
                                     String subject,String filePath,String fileName,String text,String... toEmail){ // 收件人电子邮箱
        // 指定发送邮件的主机为 smtp.qq.com
        String host = "smtp."+fromEmail.substring(fromEmail.lastIndexOf("@")+1);
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        properties.put("mail.smtp.auth", "true");
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties,new Authenticator(){
            @Override
            public PasswordAuthentication getPasswordAuthentication(){
                return new PasswordAuthentication(fromEmail,password); //发件人邮件用户名、授权码
            }
        });
        try{
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // Set From: 头部头字段
            name=MimeUtility.encodeText(name);
            message.setFrom(new InternetAddress(name+"<"+fromEmail+">"));
            if(toEmail.length>1) {// 抄送发件人
                message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(fromEmail));
            }
            // Set To: 头部头字段
            for (String string : toEmail) {
                message.addRecipient(Message.RecipientType.TO,
                        new InternetAddress(string));
            }
            // Set Subject: 头部头字段
            message.setSubject(subject);
            //设置邮件内容,混合模式
            MimeMultipart msgMultipart = new MimeMultipart("mixed");
            message.setContent(msgMultipart);
            //设置消息正文
            MimeBodyPart content = new MimeBodyPart();
            msgMultipart.addBodyPart(content);

            MimeMultipart bodyMultipart = new MimeMultipart("related");
            content.setContent(bodyMultipart);

            MimeBodyPart htmlPart = new MimeBodyPart();
            bodyMultipart.addBodyPart(htmlPart);
            htmlPart.setContent("<div>"+text+"</div>" ,
                    "text/html;charset=UTF-8" );
            File file =new File(filePath);
            MimeBodyPart filePart = new MimeBodyPart();
            FileDataSource dataSource = new FileDataSource(file);
            DataHandler dataHandler = new DataHandler(dataSource);
            // 文件处理
            filePart.setDataHandler(dataHandler);
            // 附件名称 注意文件名乱码
            filePart.setFileName(MimeUtility.encodeWord(fileName,"utf-8","B"));
            // 放入正文(有先后顺序,所以在正文后面)
            msgMultipart.addBodyPart(filePart);
            Transport.send(message);  // 发送消息
        }catch (Exception mex) {
            mex.printStackTrace();
            System.err.println("邮箱发送失败:"+mex.getMessage());
        }
    }
}

调用方法

 public static void main(String [] args) {
//       sendEmailHtml("发件人","1340573572@qq.com","ahhcqtswjqfsgibc","广州社会工作管理系统",
//			   "您的验证码为:8SYZ","1832105689@qq.com");
//       sendEmailHtmlWithFile("发件人","zwq15210498715@163.com","zhu19920728","广州社会工作管理系统",
//			   "D:\\standardfile\\testProjectPath\\40288075732c208201732c21bb610003\\40288075732c208201732c21bb610003.docx","测试报告.docx",
//			   "您的验证码为:8SYZ","940507025@qq.com");
       sendEmailHtmlNoFrom("广州社会工作管理系统","ces","1340573572@qq.com", "1832105689@qq.com","2647409627@qq.com","24683082556@qq.com");
   }

引用的jar包

链接:https://pan.baidu.com/s/1-EcEu1dZFdLhD_FZKGoUQg
提取码:ix1d

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值