Spring 发送邮件 使用File指定附件
  • 2023-01-17 16:59:03
  • 1932 热度
  • 0 评论

Spring 发送邮件 内嵌图片增加附件 http://cuisuqiang.iteye.com/blog/2042435

在之前代码中,因为使用的是Spring,使用获取文件的方式使用了ClassPathResource,此时,你的文件应该放到SRC下面。
对于内嵌图片,需要指定CID的内容,也说了一般不会这么干的。但是对于附件,一般就是在文件系统的某个地方,使用使用ClassPathResource就不适合了。

 

因为指定附件是MimeMessageHelper的工作,所以到官方看一下API,看到addInline()方法可以直接指定File对象,addAttachment()方法一样。
MimeMessageHelper API:http://docs.spring.io/spring/docs/2.0.x/api/org/springframework/mail/javamail/MimeMessageHelper.html

所以对于之前的代码附件部分,修改为以下:

// 邮件内容,第二个参数指定发送的是HTML格式
helper.setText("<font color='red'>强哥邀请你访问我的博客:http://javacui.com/!</font><br><img src='cid:myImg'>",true);
// 增加CID内容
// ClassPathResource img = new ClassPathResource("abc.jpg");
File img = new File("C:\\abc.jpg");
helper.addInline("myImg", img);
// 增加附件
// ClassPathResource file = new ClassPathResource("abc.zip");
File file = new File("C:\\abc.zip");
helper.addAttachment("abc.zip", file);


对于ClassPathResource的使用,可以参考API,不过一般是加载Spring的XML配置文件时会使用。

ClassPathResource API:http://docs.spring.io/spring/docs/2.5.x/api/org/springframework/core/io/ClassPathResource.html



Flame

Hello world!

0 评论
留下评论