java 邮件发送

该博客介绍了如何使用Java发送不同类型的邮件,包括普通邮件、带附件的邮件和HTML模板邮件。通过设置邮件会话参数,如SMTP服务器地址、端口、认证方式等,以及使用MimeMessage和MimeMessageHelper类来构建邮件内容和附件,实现了邮件的发送功能。代码中还包含了异常处理以确保邮件发送的稳定性。
摘要由CSDN通过智能技术生成

1、普通邮件发送

/**
     * 发送普通邮件
     */
    @Async
    @Override
    public void sendSimpleMail(String emailHost, String port, String senderAccount, String senderPassword, String title, String content, String receiveEmail) {
        try {
            log.info("---------- start send email -------------");
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            // final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            // 设置邮件会话参数
            Properties props = new Properties();
            // 邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", emailHost);
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            // 邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", port);
            props.setProperty("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.auth", "true");
            // String username = getOneMailSender();
            // 获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(senderAccount, senderPassword);
                }
            });
            // 通过会话,得到一个邮件,用于发送
            Message msg = new MimeMessage(session);
            // 设置发件人
            msg.setFrom(new InternetAddress(senderAccount));
            // 设置收件人,to为收件人,cc为抄送,bcc为密送
            msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receiveEmail, false));
            // msg.setRecipients(Message.RecipientType.CC, InternetAddress.parse(recipientEmail, false));
            // msg.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(recipientEmail, false));
            // 设置邮件标题
            String subject = MimeUtility.encodeWord(title, "UTF-8", "B");
            msg.setSubject(subject);
            // 设置邮件消息
            msg.setContent(content, "text/html;charset=UTF-8");
            // 设置发送的日期
            msg.setSentDate(new Date());
            log.info("mailHost:{},mailPort:{},mailSender:{}", props.getProperty("mail.smtp.host"), props.getProperty("mail.smtp.port"), senderAccount);
            // 调用Transport的send方法去发送邮件
            Transport.send(msg);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2、带附件邮件发送

/**
     * 发送带附件的邮件
     */
    private static void sendAnnexMail(String emailHost, String port, String senderAccount, String senderPassword, String title, String content, String receiveEmail, String annexFileName,
        String annexFilePath) {
        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            // 设置邮件会话参数
            Properties props = new Properties();
            // 邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", emailHost);
            props.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            // 邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", port);
            props.setProperty("mail.smtp.socketFactory.port", port);
            props.put("mail.smtp.auth", "true");
            // 获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(senderAccount, senderPassword);
                }
            });
            // 通过会话,得到一个邮件,用于发送
            MimeMessage msg = new MimeMessage(session);
            System.setProperty("mail.mime.splitlongparameters", "false");
            MimeMessageHelper helper = new MimeMessageHelper(msg, true, "UTF-8");
            // 设置发件人
            helper.setFrom(new InternetAddress(senderAccount));
            // 设置收件人
            helper.setBcc(InternetAddress.parse(receiveEmail));
            // 设置邮件标题
            String subject = MimeUtility.encodeWord(title, "UTF-8", "Q");
            helper.setSubject(subject);
            // 设置邮件消息
            helper.setText(content, false);
            // 添加附件
            FileSystemResource file = new FileSystemResource(new File(annexFilePath));
            helper.addAttachment(MimeUtility.encodeWord(annexFileName, "utf-8", null), file);
            // 设置发送的日期
            helper.setSentDate(new Date());
            // 调用Transport的send方法去发送邮件
            Transport.send(msg);
            // 发送后删除zip
            deleteFile(annexFilePath);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

3、发送html模版邮件

@Data
public class MailBean {

    /**
     * 主题
     */
    private String subject;
    /**
     * 收件人
     */
    private String recipient;

    /**
     * 附件集合
     * key 附件名称
     * value 附件路径
     */
    private Map<String,String> annexMap;
    /**
     * 模版名称
     */
    private String templateName;
    /**
     * 模版参数
     */
    private Object params;
}
@Override
    public void sendSimpleMail(MailBean mailBean) {

        try {
            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
            //设置邮件会话参数
            Properties props = new Properties();
            //邮箱的发送服务器地址
            props.setProperty("mail.smtp.host", host);
            props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            props.setProperty("mail.smtp.socketFactory.fallback", fallback);
            //邮箱发送服务器端口,这里设置为465端口
            props.setProperty("mail.smtp.port", port);
            props.setProperty("mail.smtp.socketFactory.port", porth);
            props.put("mail.smtp.auth", auth);
            //String username = getOneMailSender();
            //获取到邮箱会话,利用匿名内部类的方式,将发送者邮箱用户名和密码授权给jvm
            Session session = Session.getInstance(props, new Authenticator() {
                protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(username, password);
                }
            });
            //通过会话,得到一个邮件,用于发送
            MimeMessage msg = new MimeMessage(session);
            System.setProperty("mail.mime.splitlongparameters", "false");
            MimeMessageHelper helper = new MimeMessageHelper(msg, true,"UTF-8");
            //设置发件人
            helper.setFrom(new InternetAddress(username));
            //设置收件人
            helper.setTo(InternetAddress.parse(mailBean.getRecipient()));
            //设置邮件标题
            String subject = MimeUtility.encodeWord(mailBean.getSubject(),"UTF-8","Q");
            helper.setSubject(subject);

            //添加附件
            if(mailBean.getAnnexMap()!=null && mailBean.getAnnexMap().size()>0){
                for(Map.Entry<String, String> entry : mailBean.getAnnexMap().entrySet()){
                    FileSystemResource file1 = new FileSystemResource(new File(entry.getValue()));

                    helper.addAttachment(MimeUtility.encodeWord(entry.getKey(),"utf-8",null), file1);
                }
            }
            //添加模版
            if(mailBean.getTemplateName()!=null && mailBean.getParams()!=null){
                //设置模版
                Template template = configurer.getConfiguration().getTemplate(mailBean.getTemplateName());
                //添加模版参数
                Map<String, Object> model = new HashMap<>();
                model.put("params", mailBean.getParams());
                String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
                helper.setText(text, true);
            }

            //设置发送的日期
            helper.setSentDate(new Date());
            log.info("mailHost:{},mailPort:{},mailSender:{}",props.getProperty("mail.smtp.host"),props.getProperty("mail.smtp.port"),username);
            //调用Transport的send方法去发送邮件
            Transport.send(msg);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值