JavaMail-利用JavaMail实现发送基础邮件工具类

本文介绍 利用 javamail 实现发送简单的邮件方法。

引入依赖

<!-- javax mail -->
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1</version>
</dependency>
<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4</version>
</dependency>

新建工具类 EmailSendUtil



import com.sun.mail.util.MailSSLSocketFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @ClassName :EmailSendUtil
 * @Description :2019/1/4
 * @date :2019/1/4
 */
@Slf4j
public class EmailSendUtil {

    /* 系统属性 */
    private boolean isProxy;
    /* 系统属性 */
    private Properties props;
    /* 邮件会话对象 */
    private Session session;
    /* MIME邮件对象 */
    private MimeMessage mimeMsg;
    /* Multipart对象,邮件内容,标题,附件等内容均添加到其中后再生成MimeMessage对象 */
    private Multipart mp;

    private static EmailSendUtil instance = null;
	/**
	*
	*/
    public EmailSendUtil() {
    }
	/**
     * 构造方法
     * @map 发件人信息
     */
    public EmailSendUtil(Map<String, String> map) {
        props = System.getProperties();
        props.put("mail.smtp.auth", "true");
        props.put("mail.transport.protocol", map.get("userName"));
        props.put("mail.smtp.host", map.get("host"));
        props.put("mail.smtp.port", map.get("port"));
        props.put("username", map.get("userName"));
        props.put("password", map.get("passWord"));
        if (map.get("port").equals("465")) {
            MailSSLSocketFactory mailSSLSocketFactory = null;
            try {
                mailSSLSocketFactory = new MailSSLSocketFactory();
            } catch (GeneralSecurityException e) {
                e.printStackTrace();
            }
            mailSSLSocketFactory.setTrustAllHosts(true);
            props.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
            props.put("mail.smtp.ssl.enable", "true");
        }
        isProxy = false;
        if(isProxy){
            props.put("proxySet", "true");
            props.put("http.proxyhost", "10.19.108.2");
            props.put("http.proxyport", "8080");
        }

        /* 建立会话 */
        session = Session.getDefaultInstance(props);
        session.setDebug(false);
    }
	/**
     * 返回实例
     * @map 发件人信息
     */
    public static EmailSendUtil getInstance(Map<String, String> map) {
        if (instance == null) {
            instance = new EmailSendUtil(map);
        }
        return instance;
    }

    /**
     * 发送邮件
     *
     * @return
     * @param_from 发件人
     * @param_to 收件人, 多个Email以英文逗号分隔
     * @param_cc 抄送, 多个Email以英文逗号分隔
     * @param_subject 主题
     * @param_content 内容
     * @param_fileList 附件列表
     */
    public boolean sendMail(Map<String, String> map, String[] fileList) {
        String from = map.get("userName");
        boolean success = true;
        try {
            mimeMsg = new MimeMessage(session);
            mp = new MimeMultipart();

            /* 自定义发件人昵称 */
            String nick = "";
            try {
                nick = javax.mail.internet.MimeUtility.encodeText(map.get("senderNick"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            /* 设置发件人 */
            mimeMsg.setFrom(new InternetAddress(from, nick));
            /* 设置收件人 */
            if (map.get("to") != null && map.get("to").length() > 0) {
                mimeMsg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(map.get("to")));
            }
            /* 设置抄送人 */
            if (map.get("copyTo") != null && map.get("copyTo").length() > 0) {
                mimeMsg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(map.get("copyTo")));
            }
            /* 设置主题 */
            mimeMsg.setSubject(map.get("subject"));
            /* 设置正文 */
            BodyPart bp = new MimeBodyPart();
            bp.setContent(map.get("content"), "text/html;charset=utf-8");
            mp.addBodyPart(bp);

            /* 设置附件 */
            if (fileList != null && fileList.length > 0) {
                for (int i = 0; i < fileList.length; i++) {
                    if (!"".equals(fileList[i]) && null != fileList[i]) {
                        bp = new MimeBodyPart();
                        FileDataSource fds = new FileDataSource(fileList[i]);
                        bp.setDataHandler(new DataHandler(fds));
                        bp.setFileName(MimeUtility.encodeText(fds.getName()));
                        mp.addBodyPart(bp);
                    }
                }
            }
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            /* 发送邮件 */
            if (props.get("mail.smtp.auth").equals("true")) {
                Transport transport = session.getTransport("smtp");
                transport.connect((String) props.get("mail.smtp.host"), (String) props.get("username"),
                        (String) props.get("password"));
                transport.sendMessage(mimeMsg, mimeMsg.getAllRecipients());
                transport.close();
            } else {
                Transport.send(mimeMsg);
            }
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = new Date();
            log.info("邮件发送成功:{}",format.format(date));
        } catch (MessagingException e) {
            e.printStackTrace();
            success = false;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            success = false;
        }
        return success;
    }

    public String getMailList(String[] mailArray) {
        StringBuffer toList = new StringBuffer();
        int length = mailArray.length;
        if (mailArray != null && length < 2) {
            toList.append(mailArray[0]);
        } else {
            for (int i = 0; i < length; i++) {
                toList.append(mailArray[i]);
                if (i != (length - 1)) {
                    toList.append(",");
                }

            }
        }
        return toList.toString();
    }

}
public static void main(String[] args) {
        String[] fileList = new String[1];
		//定义发件方
        Map<String, String> map1 = new HashMap<String, String>();
        map1.put("userName","邮箱");
        map1.put("passWord","密码");
        map1.put("host","smtp.exmail.qq.com");
        map1.put("port","587");
		//定义收件方
        Map<String, String> map2 = new HashMap<String, String>();
        map2.put("userName", map1.get("userName"));
        map2.put("senderNick", "快捷标题");
        //主送 多个用,分隔
        map2.put("to", "收件方邮箱");
        //抄送
        map2.put("copyTo","收件方邮箱");
        map2.put("subject", "标题");
        map2.put("content", "内容:XXXX您好!<br>附件为xxx,请查收!");
        //文件目录 可多个
        fileList[0] = "E:\\2-companyFile\\CXRB_DAY.xls";
		//调用
        EmailSendUtil.getInstance(map1).sendMail(map2, fileList);
    }

利用EnableScheduling 实现简单的定时调用

开启注解:
@Configuration //1.主要用于标记配置类,兼备Component的效果。
@EnableScheduling // 2.开启定时任务
在这里插入图片描述
标记定时执行的方法:
每天9点50执行
@Scheduled(cron = “0 50 9 * * *”)
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值