springboot实现邮件功能:发送带静态资源的邮件(静态资源一般指的是图片)
1.建springboot项目,导入依赖;application.properties配置文件,看
2.编写服务接口,实现类:
/** * 邮件服务接口 * Created by ASUS on 2018/5/5 * * @Authod Grey Wolf */ public interface MailService { /** * 发送带静态资源的邮件 * @param to * @param subject * @param content * @param imgPath * @param imgId */ void sendInlineResourceMail(String to,String subject,String content,String imgPath,String imgId); }
/** * * 邮件服务类 * Created by ASUS on 2018/5/5 * * @Authod Grey Wolf */ @Service("mailService") public class MailServiceImpl implements MailService { @Autowired private JavaMailSender mailSender; @Value("${mail.fromMail.addr}") private String form; /** * 发送带静态资源的邮件 * @param to 接受者 * @param subject 主题 * @param content 内容 * @param imgPath 图片路径 * @param imgId 图片编号 */ @Override public void sendInlineResourceMail(String to, String subject, String content, String imgPath, String imgId) { MimeMessage message=mailSender.createMimeMessage(); try { MimeMessageHelper helper=new MimeMessageHelper(message,true); helper.setFrom(form); helper.setTo(to); helper.setSubject(subject); //记得设置为true,没有的话图片时显示不了的 helper.setText(content,true); FileSystemResource file=new FileSystemResource(new File(imgPath)); helper.addInline(imgId,file); mailSender.send(message); System.out.println("发送带静态资源的邮件成功"); }catch (Exception e){ e.printStackTrace(); System.out.println("发送带静态资源的邮件失败"); } } }
3.编写测试类MailTest:
/** * 发送邮件测试类 * Created by ASUS on 2018/5/5 * * @Authod Grey Wolf */ @RunWith(SpringRunner.class) @SpringBootTest public class MailTest { @Autowired private MailService mailService; @Value("${mail.fromMail.addr}") private String form; @Test public void sendInlineResourceMail(){ String imgId="2"; String content="<html><body>这是有图片的邮件:<img src=\'cid:"+imgId + "\'></body></html>"; String imgPath="C:\\Users\\ASUS\\Pictures\\SharedImageServer\\contentpic\\2.jpg"; mailService.sendInlineResourceMail(form,"这是有图片的邮件",content,imgPath,imgId); } }
4.看测试结果:
我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。