当前位置: 首页 > news >正文

springboot入门_email

本文记录在springboot中发送邮件

创建springboot工程,并引入邮件服务需要的jar

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-mail</artifactId>
        </dependency>

在application.properties属性文件中配置邮件服务信息

# Email (MailProperties)
spring.mail.default-encoding=UTF-8
spring.mail.host=smtp.qq.com
spring.mail.protocol=smtp
spring.mail.port=25
spring.mail.username=emial
#第三方使用时 密码需用邮箱的授权码
spring.mail.password=your email authorization code

spring.mail.test-connection=false

spring中向我们提供了一个接口JavaMailSender帮我们实现邮件的发送,在服务启动时会根据配置信息实例化供我们使用

定义发送邮件的接口方法

public interface EmailSenderService {

    /**
     * 发送简单文本邮件
     * @param subject 邮件主题
     * @param content 邮件内容
     * @param to 收件人
     */
    void sendTextMail(String subject, String content, String... to);

    /**
     * 发送包含html标签内容的邮件
     * @param subject 邮件主题
     * @param htmlContent 邮件内容
     * @param to 收件人
     */
    void sendHtmlTextMail(String subject, String htmlContent, String to);

    /**
     * 发送带附件邮件
     * @param subject 主题
     * @param content 邮件内容
     * @param to 收件人
     * @param filePath 附件路径
     * @param fileName 附件名
     */
    void sendAttachmentMail(String subject, String content, String to, String filePath, String fileName);

    /**
     * 发送简单文本邮件 并抄送
     * @param subject
     * @param content
     * @param ccList 抄送人
     * @param tos 收件人,多个时用逗号隔开
     */
    void sendTextMail(String subject, String content, List<String> ccList, String... tos);

}

接口的实现类

@Service
public class EmailSenderServiceImpl implements EmailSenderService {

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public void sendTextMail(String subject, String content, String... to) {
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(content);
        mailMessage.setSentDate(new Date());
        javaMailSender.send(mailMessage);
    }

    @Override
    public void sendHtmlTextMail(String subject, String htmlContent, String to) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(htmlContent, true);
            helper.setSentDate(new Date());

            FileSystemResource fsr = new FileSystemResource(new File("C:\\Users\\admin\\Pictures\\Camera Roll\\光头强.jpg"));
            helper.addInline("imgSrcContentId", fsr);//此处的contentId需要和html中的对应

            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void sendAttachmentMail(String subject, String content, String to, String filePath, String fileName) {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content);
            //附件
            FileSystemResource file = new FileSystemResource(new File(filePath));
            helper.addAttachment(fileName, file);

            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    public void sendTextMail(String subject, String content, List<String> ccList, String... tos) {
        //收件人
        InternetAddress[] addressesTo = new InternetAddress[tos.length];
        if(tos != null && tos.length>0){
            for(int i=0;i<tos.length;i++){
                InternetAddress addressTo = null;
                try {
                    addressTo = new InternetAddress(tos[i]);
                    addressesTo[i] = addressTo;
                } catch (AddressException e) {
                    e.printStackTrace();
                }
            }
        }
        //抄送人
        InternetAddress[] addressesCc = new InternetAddress[ccList.size()];
        if(ccList != null && ccList.size() > 0){
            for(int i=0;i<ccList.size();i++){
                String ccAdd = ccList.get(i);
                InternetAddress address = null;
                try {
                    address = new InternetAddress(ccAdd);
                    addressesCc[i] = address;
                } catch (AddressException e) {
                    e.printStackTrace();
                }
            }
        }

        MimeMessagePreparator preparator = new MimeMessagePreparator() {
            @Override
            public void prepare(MimeMessage mimeMessage) throws Exception {
                mimeMessage.setFrom(from);
                mimeMessage.setSubject(subject);
                mimeMessage.setText(content);
                mimeMessage.setRecipients(Message.RecipientType.TO, addressesTo);
                mimeMessage.setRecipients(Message.RecipientType.CC, addressesCc);
            }
        };
        javaMailSender.send(preparator);
    }

}

单元测试,注入EmailSenderService,调用发送邮件方法

@RunWith(SpringRunner.class)
@SpringBootTest
public class EmailApplicationTests {

    @Autowired
    private EmailSenderService emailSenderService;

    @Test
    public void contextLoads() {
        String to = "receiver email";
        String subject = "email subject";
        //String content = "This is the test message, see when the message has been sent successfully!";
        //emailSenderService.sendTextMail(to, subject, content);

        String content = "<html><body><span style='color:yellow'>This is the test mail containing HTML, see when the message has been sent successfully!<span><img " +
                "src='cid:imgSrcContentId'></body><html>";
        emailSenderService.sendHtmlTextMail(subject, content, to);

//        String content = "This is the test with the attachment of the mail, when you see that the mail with attachment has been sent successfully!";
//        String filePath = "your file path";
//        String fileName = "your file name";
//        emailSenderService.sendAttachmentMail(subject, content, to, filePath, fileName);

//        List<String> ccList = new ArrayList<String>();
//        ccList.add("Cc 'er 1's mailbox");
//        ccList.add("Cc 'er 2's mailbox");
//        ...
//        ccList.add("Cc 'er n's mailbox");
//        emailSenderService.sendTextMail(subject, content, ccList, "Recipient 1's mailbox", "Recipient 2's mailbox",
// ..., "Recipient n's mailbox");

    }

}

查看源码

转载于:https://www.cnblogs.com/wlzq/p/9856412.html

相关文章:

  • Python MetaClass深入分析
  • Python中常见的字符串的操作方法:
  • 记录LNMP多主机架构Wordpress博客实施过程中的一些坑
  • 表单提交时问题总结
  • iOS:The operation couldn’t be completed. (DVTCoreSimulatorAdditionsErrorDomain error 0.)
  • python关于标识符说明
  • 类的自动加载
  • 【DP复习】背包 ovo
  • CSS3 Transform变形(3D转换)
  • Python——数据存储:XML操作
  • python 求助!
  • OpenGL step by step 38 : Skeletal Animation with Assimp
  • 顺为资本第四期美元基金募集完成 规模12.1亿美元
  • 【经验分享】:如何将PDF格式的文件进行翻译
  • 当奶猫来敲门
  • 《Javascript高级程序设计 (第三版)》第五章 引用类型
  • android高仿小视频、应用锁、3种存储库、QQ小红点动画、仿支付宝图表等源码...
  • CentOS7简单部署NFS
  • CSS3 聊天气泡框以及 inherit、currentColor 关键字
  • Docker容器管理
  • Git初体验
  • gulp 教程
  • Nginx 通过 Lua + Redis 实现动态封禁 IP
  • SegmentFault 社区上线小程序开发频道,助力小程序开发者生态
  • vue-cli3搭建项目
  • 坑!为什么View.startAnimation不起作用?
  • 罗辑思维在全链路压测方面的实践和工作笔记
  • 如何实现 font-size 的响应式
  • 入门到放弃node系列之Hello Word篇
  • 三分钟教你同步 Visual Studio Code 设置
  • 设计模式 开闭原则
  • 微信开源mars源码分析1—上层samples分析
  • raise 与 raise ... from 的区别
  • 摩拜创始人胡玮炜也彻底离开了,共享单车行业还有未来吗? ...
  • ​软考-高级-系统架构设计师教程(清华第2版)【第20章 系统架构设计师论文写作要点(P717~728)-思维导图】​
  • # include “ “ 和 # include < >两者的区别
  • #我与Java虚拟机的故事#连载05:Java虚拟机的修炼之道
  • ${ }的特别功能
  • (翻译)terry crowley: 写给程序员
  • (原創) X61用戶,小心你的上蓋!! (NB) (ThinkPad) (X61)
  • (转)EOS中账户、钱包和密钥的关系
  • (转)关于pipe()的详细解析
  • ./indexer: error while loading shared libraries: libmysqlclient.so.18: cannot open shared object fil
  • .NET Core 2.1路线图
  • .net core 6 使用注解自动注入实例,无需构造注入 autowrite4net
  • .Net FrameWork总结
  • .net mvc 获取url中controller和action
  • .NET Reactor简单使用教程
  • .Net程序猿乐Android发展---(10)框架布局FrameLayout
  • ?php echo $logosrc[0];?,如何在一行中显示logo和标题?
  • @data注解_SpringBoot 使用WebSocket打造在线聊天室(基于注解)
  • @Service注解让spring找到你的Service bean
  • @取消转义
  • [ Linux ] Linux信号概述 信号的产生
  • [《百万宝贝》观后]To be or not to be?