springboot发送邮件

springboot引入spring-boot-starter-mail可以更加方便发送邮件,具体应用场景如下:

1、发送简单文本

2、发送html格式文本

3、发送带附件的邮件

4、发送带静态图片邮件

5、发送指定模板的邮件

下面将上述场景封装成工具类JavaMailUtil:

1 首先导入jar包

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

2 配置文件:

spring.mail.host=smtp.163.com
spring.mail.username=自己的邮箱
spring.mail.password=密码
spring.mail.default-encoding=UTF-8
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
mail.fromMail.addr=自己的邮箱

3 工具类JavaMailUtil:

package com.yc.util;

import org.apache.catalina.webresources.FileResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.IEngineConfiguration;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolution;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.util.Map;

/**
 * @author an-ping
 * @date 2018/12/4
 */
@Component
public class JavaMailUtil  {
    @Autowired
     JavaMailSender MailSender;

    @Value("${mail.fromMail.addr}")
    private String from;

    //发送简单消息
    public   int sendSimpleMail(String to,String text,String subject){
        SimpleMailMessage simpleMailMessage=new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(text);

        try {
            System.out.println(simpleMailMessage);
            System.out.println(MailSender);
            MailSender.send(simpleMailMessage);
            return 1;//发送成功
        } catch (MailException e) {
            e.printStackTrace();
            return 0;//发送失败
        }

    }

//发送html格式文本
    public int sendHtmlMail(String to,String subject,String text){
        MimeMessage mimeMessage=MailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(text,true);//html格式为true
            MailSender.send(mimeMessage);
            return 1;
        } catch (MessagingException e) {
            e.printStackTrace();
            return 0;
        }


    }

//发送带附件邮件
    public int sendAttachMail(String to,String text,String subject,String path){
        MimeMessage mimeMessage=MailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage,true,"utf-8");
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setText(text,true);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setTo(to);
            FileSystemResource fileSystemResource=new FileSystemResource(new File(path));
            String fileName=path.substring(path.lastIndexOf(File.separator));
            mimeMessageHelper.addAttachment(fileName,fileSystemResource);
            MailSender.send(mimeMessage);
            return 1;

        } catch (MessagingException e) {
            e.printStackTrace();
            return 0;
        }

    }


//发送带静态图片邮件
    public int sendPicMail(String to,String text,String subject,String path,String id){
        MimeMessage mimeMessage=MailSender.createMimeMessage();
        try {
            MimeMessageHelper mimeMessageHelper=new MimeMessageHelper(mimeMessage,true);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setText(text,true);
            mimeMessageHelper.setSubject(subject);
            FileSystemResource fileSystemResource=new FileSystemResource(new File(path));
            mimeMessageHelper.addInline(id,fileSystemResource);
            MailSender.send(mimeMessage);
            return 1;


        } catch (MessagingException e) {
            e.printStackTrace();
            return 0;
        }

    }


//发送邮件模板
@Autowired
TemplateEngine templateEngine;

    public int sendTemplateMail(String to,String subject,String name){
        //创建邮件正文
        Context context = new Context();
        context.setVariable("name", name);
        String emailContent = templateEngine.process("MailTemplate", context);
        int result=sendHtmlMail(to,subject,emailContent);
        return result;
    }

}

 

4 测试类:

package com.example.demo;

import com.yc.DemoApplication;
import com.yc.util.JavaMailUtil;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(classes=DemoApplication.class)


public class DemoApplicationTests {
    @Autowired
    JavaMailUtil javaMailUtil;
    @Test
    public void sendmail(){
      int result=  javaMailUtil.sendSimpleMail("3249899068@qq.com","新年快乐","节日祝福");

    }
    @Autowired
    private JavaMailSender mailSender;

    //测试发送简单文本
    @Test  
    public void sendSimpleMail() throws Exception {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom("tap3249899068@163.com");
        message.setTo("3249899068@qq.com");
        message.setSubject("主题:简单邮件");
        message.setText("测试邮件内容");

        mailSender.send(message);
    }
    
    //测试发送html文本邮件
@Test
public void testHtmlMail(){

        javaMailUtil.sendHtmlMail("3249899068@qq.com","录取通知","<html><body align='center'><h1>通知书</h1></br>亲爱的同学</br>恭喜你通过高级软件工程师考试</body></html>");

}


//测试发送带附件邮件
@Test
public void testAttachMail(){
        String path="D:\\kechengsheji\\demo-springboot-web\\src\\main\\java\\com\\yc\\filter\\LoginFilter.java";
        javaMailUtil.sendAttachMail("3249899068@qq.com","这是带有附件的邮件","附件传输",path);
}

//测试发送带静态图片
@Test
public void testpicMail(){
        String path="D:\\8.jpg";
    String Id = "neo006";
    String content="<html><body>这是有图片的邮件:<img src=\'cid:" + Id + "\' ></body></html>";
        javaMailUtil.sendPicMail("3249899068@qq.com",content,"主题:图片传输",path,Id);
}


//测试发送邮件模板
@Test
public void sendTemplateMail(){
        javaMailUtil.sendTemplateMail("3249899068@qq.com","主题:模测试","张无忌");
}



}

实现效果:

1 简单文本:

2 html文本

3 带附件邮件

4 静态图片邮件

5 模板邮件

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值