• springboot发送邮件


    引入maven

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

      

    yml配置

    spring:
      mail:
        host: smtp.163.com    #邮件服务器地址,邮箱不一样,服务器地址不一样
        username:  #邮箱用户名 
        password:  #一般使用授权码
        properties:
          'mail.smtp.ssl.enable': 'true'   #设置安全连接
    

      

    发送邮件工具类

    MailUtis.java

    package cn.stylefeng.guns.utils;
    
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.mail.SimpleMailMessage;
    import org.springframework.mail.javamail.JavaMailSenderImpl;
    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    
    @Component
    public class MailUtil {
    
        @Autowired
        private JavaMailSenderImpl javaMailSender;
    
        public static MailUtil mailUtil;
    
        @PostConstruct
        public void init(){
            mailUtil=this;
            mailUtil.javaMailSender=this.javaMailSender;
        }
    
           
        public static void sendMail(){
            SimpleMailMessage mailMessage=new SimpleMailMessage();
            mailMessage.setSubject("测试");   #主题
            mailMessage.setText("aaa");      #发送的内容
            mailMessage.setTo("530@qq.com");   #发送给谁邮箱地址
            mailMessage.setFrom("tfe@163.com"); #发送人,这里与yml配置的username一样
            mailUtil.javaMailSender.send(mailMessage);
        }
    
        //发送附件代码 
    public static void sendMailAttach() {
        MimeMessage mimeMessage=mailUtil.javaMailSender.createMimeMessage();
        MimeMessageHelper helper= null;
        try {
            helper = new MimeMessageHelper(mimeMessage,true);
            helper.setSubject("测试");
            helper.setText("<b>aaa<b>",true);   //发送含有html代码的内容
            helper.setTo("530@qq.com");
            helper.setFrom("tuf@163.com");
    
            helper.addAttachment("1.jpg",new File("C:\Users\Pictures\1.jpg"));  发送附件 可以多个,前面是附件名称,后面是附件绝对路径
            helper.addAttachment("2.jpg",new File("C:\Users\Pictures\1.jpg"));
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    
        mailUtil.javaMailSender.send(mimeMessage);
      }
    }
    

      

  • 相关阅读:
    一些技术摘选及随想
    新技术学习方法如何学习一门新编程语言(Lua)?
    什么时候该用ASSERT?
    MFC是否过时?如何学习MFC?
    Windows桌面开发者的必备软件
    Comet技术选择,论Is node.js best for Comet?
    关于C/C++内存管理一些乱讲
    debug
    C语言趣味题目
    CSS之简单的双引号
  • 原文地址:https://www.cnblogs.com/pxblog/p/12231127.html
Copyright © 2020-2023  润新知