2525import org .springframework .mail .javamail .MimeMessageHelper ;
2626import org .springframework .util .CollectionUtils ;
2727
28+ import javax .imageio .ImageIO ;
2829import javax .mail .MessagingException ;
2930import javax .mail .internet .MimeMessage ;
31+ import java .awt .image .BufferedImage ;
3032import java .io .File ;
3133import java .io .UnsupportedEncodingException ;
34+ import java .util .ArrayList ;
3235import java .util .List ;
36+ import java .util .stream .Collectors ;
3337
3438@ Slf4j
3539public class EmailJob extends ScheduleJob {
3640
3741 private final MailService mailService ;
3842
43+ private final String imageHtml = "<image src='cid:$CID$' style='width:100%;height:auto;max-width:100%;display:block'>" ;
44+
3945 public EmailJob () {
4046 mailService = Application .getBean (MailService .class );
4147 }
@@ -51,10 +57,17 @@ private MimeMessage createMailMessage(ScheduleJobConfig config, List<File> attac
5157 MimeMessageHelper helper = new MimeMessageHelper (mimeMessage , !CollectionUtils .isEmpty (attachments ));
5258 helper .setSubject (config .getSubject ());
5359 helper .setTo (config .getTo () == null ? null : config .getTo ().split (";" ));
54- helper .setText (config .getTextContent (), true );
5560 if (StringUtils .isNotBlank (config .getCc ())) {
5661 helper .setCc (config .getCc () == null ? null : config .getCc ().split (";" ));
5762 }
63+ //图片插入正文
64+ List <File > images = filterImages (attachments );
65+ String imageStr = images .stream ().map (item -> imageHtml .replace ("$CID$" ,item .getName ())).collect (Collectors .joining ());
66+ helper .setText (config .getTextContent ()+imageStr , true );
67+ for (File image : images ) {
68+ helper .addInline (image .getName (), image );
69+ }
70+
5871 if (!CollectionUtils .isEmpty (attachments )) {
5972 for (File file : attachments ) {
6073 helper .addAttachment (file .getName (), file );
@@ -63,5 +76,25 @@ private MimeMessage createMailMessage(ScheduleJobConfig config, List<File> attac
6376 return mimeMessage ;
6477 }
6578
79+ /**
80+ * 筛选图片文件
81+ * @param files
82+ * @return
83+ */
84+ private List <File > filterImages (List <File > files ) {
85+ List <File > images = new ArrayList <>();
86+ for (File file : files ) {
87+ try {
88+ BufferedImage image = ImageIO .read (file );
89+ if (image == null || image .getWidth () <= 0 || image .getHeight () <= 0 ) {
90+ continue ;
91+ }
92+ images .add (file );
93+ } catch (Exception e ) {}
94+ }
95+ files .removeAll (images );
96+ return images ;
97+ }
98+
6699
67100}
0 commit comments