zoukankan      html  css  js  c++  java
  • spring boot 实现发送邮件

    1、导入pom依赖

    <dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.0</version>
    </dependency>
    2、邮箱到邮箱的配置文件

     3、发送邮箱接口api

    /**
     * 通知服务
     */
    public interface NotifyService {
    
        boolean sendEmail(String to, String title, String body);
    
        boolean sendpdfEmail(String[] to, String title, String body, InputStream inputStream);
    }

    4、实现

    package com.fyun.common.utils.impl;
    import com.fyun.common.utils.NotifyService;
    import com.fyun.common.utils.model.EmailModel;
    import com.fyun.common.utils.util.ObjectUtils;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.mail.javamail.JavaMailSender;
    import org.springframework.mail.javamail.JavaMailSenderImpl;
    import org.springframework.mail.javamail.MimeMessageHelper;
    import org.springframework.stereotype.Service;
    
    import javax.activation.DataSource;
    import javax.mail.internet.MimeMessage;
    import javax.mail.util.ByteArrayDataSource;
    import java.io.InputStream;
    import java.util.Properties;
    
    @Service
    public class DefaultNotifyService implements NotifyService {
    
        private static final Logger logger = LoggerFactory.getLogger(ObjectUtils.class);
    
        private EmailModel emailAccount;
    
        public DefaultNotifyService() {
        }
    
        public DefaultNotifyService(EmailModel emailAccount) {
            this.emailAccount = emailAccount;
        }
    
        @Override
        public boolean sendEmail(String to, String title, String body) {
            try {
                JavaMailSender javaMailSender = buildMailSender();
                MimeMessage message = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                helper.setFrom(emailAccount.getFrom());
                if (null == to) {
                    logger.error("接收者邮箱错误!");
                    return false;
                }
                helper.setTo(to);
                helper.setSubject(title);
                helper.setText(body, true);
                javaMailSender.send(message);
                logger.info("邮件发送成功...");
                return true;
            } catch (Exception e) {
                logger.error(String.format("邮件发送 失败 e:{%s}", e));
                return false;
            }
        }
        public boolean sendpdfEmail(String[] to, String title, String body, InputStream is) {
            try {
                System.getProperties().setProperty("mail.mime.splitlongparameters", "false");  //发送至网易邮箱文件名过长会导致附件变成bin文件
                logger.info("邮件发送至:" + to );
                for (int i =0;i<to.length;i++)
                {
                    System.out.println("发送给:"+to[i]);
                }
                JavaMailSender javaMailSender = buildMailSender();
                MimeMessage message = javaMailSender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
                helper.setFrom(emailAccount.getFrom());
                if (null == to) {
                    logger.error("接收者邮箱错误!");
                    return false;
                }
                helper.setTo(to);
    //            helper.setCc(emailAccount.getCcs());                        //抄送人
                helper.setSubject(title);                                   //标题
                helper.setText(body, true);                           //内容
                if (is != null){
                    DataSource source = new ByteArrayDataSource(is, "application/msexcel");
                    helper.addAttachment(title+".pdf",source);  //发送附件
                }
                javaMailSender.send(message);
                logger.info("邮件发送成功...");
                return true;
            } catch (Exception e) {
                logger.error(String.format("邮件发送传失败 e:{%s}", e));
                return false;
            }
        }
        private JavaMailSender buildMailSender() {
            JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
            mailSender.setHost(emailAccount.getHost());
            mailSender.setPort(emailAccount.getPort());
            mailSender.setUsername(emailAccount.getFrom());
            mailSender.setPassword(emailAccount.getPassword());
            //加认证机制
            Properties javaMailProperties = new Properties();
            javaMailProperties.put("mail.smtp.auth", "true");
            javaMailProperties.put("mail.smtp.ssl.enable", emailAccount.getEnableSSL());
            mailSender.setJavaMailProperties(javaMailProperties);
            logger.info("发送邮件配置信息:{}", mailSender.getHost() + "," + mailSender.getPort() + "," + mailSender.getUsername() + "," + mailSender.getPassword());
            return mailSender;
        }
    }

    6、emailconfig 主要初始化邮箱ip port 等的properties配置文件

    package com.fyun.tewebcore.config;
    
    import com.fyun.common.utils.NotifyService;
    import com.fyun.common.utils.impl.DefaultNotifyService;
    import com.fyun.common.utils.model.EmailModel;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;
    @Configuration
    @PropertySource(value = "classpath:config/email-${spring.profiles.active:dev}.properties")
    public class EmailConfig {
        @Value("${email.host}")
        private String host;
    
        @Value("${email.port}")
        private Integer port;
    
        @Value("${email.enableSSL}")
        private Boolean enableSSL;
    
        @Value("${email.from}")
        private String from;
    
        @Value("${email.password}")
        private String password;
        @Bean
        public NotifyService notifyService() {
            EmailModel account = new EmailModel();
            account.setHost(host);
            account.setPort(port);
            account.setEnableSSL(enableSSL);
            account.setFrom(from);
            account.setPassword(password);
            return new DefaultNotifyService(account);
        }
    }
     
    
    
    
    
    
    
    
    
    
     
  • 相关阅读:
    【Ubuntu使用技巧】在Ubuntu下制作ISO镜像的方法
    【Linux调试技术1】初步基础
    【算法研究与实现】最小二乘法直线拟合
    【嵌入式学习】移植konquerorembed
    【Asterisk应用】利用Asterisk产生呼叫的脚本
    【LDAP学习】OpenLDAP学习笔记
    一个.NET通用JSON解析/构建类的实现(c#)
    .net泛型在序列化、反序列化JSON数据中的应用
    C#字符串数组排序
    c#中的Json的序列化和反序列化
  • 原文地址:https://www.cnblogs.com/zrboke/p/12565985.html
Copyright © 2011-2022 走看看