Springboot implements the mail function: send mail with static resources (static resources generally refer to pictures)
1. Build a springboot project, import dependencies; application.properties configuration file, see
springboot send mail (1): send simple mail
2. Write the service interface and implement the class:
/** * Mail service interface * Created by ASUS on 5/5/2018 * * @Authod Grey Wolf */ public interface MailService { /** * Send mail with static resources * @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; /** * Send mail with static resources * @param to recipient * @param subject subject * @param content content * @param imgPath image path * @param imgId image number */ @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) ; //Remember to set it to true, if there is no helper.setText( content ,true ) ; FileSystemResource file= new FileSystemResource( new File(imgPath)) ; helper.addInline(imgId , file) ; mailSender .send (message) ; System.out .println ( "Successful sending mail with static resources" ) ; }catch (Exception e){ e.printStackTrace() ; System.out .println ( "Failed to send mail with static resources" ) ; } } }
3. Write the test class MailTest:
/** * Send mail test class * Created by ASUS on 5/5/2018 * * @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.看测试结果:
我的座右铭:不会,我可以学;落后,我可以追赶;跌倒,我可以站起来;我一定行。