服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - spring boot定时任务接收邮件并且存储附件的方法讲解

spring boot定时任务接收邮件并且存储附件的方法讲解

2021-07-25 16:23CLG_CSDN Java教程

今天小编就为大家分享一篇关于spring boot定时任务接收邮件并且存储附件的方法讲解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧

在spring boot中写定时任务很简单,两个注解就可以实现。在启动类中加@enablescheduling ,然后在你需要定时的方法上加上@scheduled(cron="0 10 8 * * ?");括号内为cron表达式。如下图:

spring boot定时任务接收邮件并且存储附件的方法讲解

spring boot定时任务接收邮件并且存储附件的方法讲解

接收邮件及其判断是否有附件,并且存储附件。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
public class timertaskserviceimpl implements timertaskservice {
  @autowired
  private parsetxtserviceimpl parsetxtservice;
  /**
   * 接收邮件
   */
  @override
  @scheduled(cron="0 10 8 * * ?")
  public void timertaskinfo(){
    //邮件配置信息
    string host=constants.mail_host;
    string username=constants.mail_user_name;
    string password=constants.mail_pass_word;
    //邮件配置类
    properties properties=new properties();
    //邮件配置缓存
    session session=session.getdefaultinstance(properties);
    session.setdebug(true);
    string filename=null;
    try {
      //邮件服务器的类型
      store store = session.getstore("pop3");
      //连接邮箱服务器
      store.connect(host,username,password);
      // 获得用户的邮件帐户
      folder folder=store.getfolder("inbox");
      if (folder == null) {
        logger.info("获取邮箱文件信息为空");
      }
      // 设置对邮件帐户的访问权限可以读写
      folder.open(folder.read_write);
      calendar calendar=calendar.getinstance();
      calendar.add(calendar.date,-1);
      date mondaydate = calendar.gettime();
      searchterm comparisontermle = new sentdateterm(comparisonterm.gt, mondaydate);
      searchterm address=new subjectterm( "mu report");
      searchterm comparisonandterm = new andterm(address, comparisontermle);
      message[] messages = folder.search(comparisonandterm);
      for(int i = 0 ; i < messages.length ; i++){
        mimemessage msg = (mimemessage) messages[i];
        //判断是否有附件
        boolean iscontainerattachment = iscontainattachment(msg);
        if (iscontainerattachment) {
          //保存附件
          filename=saveattachment(msg,constants.storage_file);
          //保存接收到的邮件并且收件箱删除邮件
         msg.setflag(flags.flag.deleted, true);
        }
        if(!iscontainerattachment) {
          continue;
        }
      }
      folder.close(true);
      store.close();
      parsetxtservice.readtxt(filename);
    }catch (nosuchproviderexception e){
      loggererror.error("接收邮箱信息异常:{}",e);
    }catch (messagingexception e){
      loggererror.error("连接邮箱服务器信息异常:{}",e);
    }catch (ioexception e){
      loggererror.error("接收邮箱信息解析异常:{}",e);
    }catch (illegalstateexception e){
      loggererror.error("接收邮箱信息为空:{}",e);
    }
  }
  /**
   * 判断邮件中是否包含附件
   * @return 邮件中存在附件返回true,不存在返回false
   * @throws messagingexception
   * @throws ioexception
   */
  public static boolean iscontainattachment(part part) throws messagingexception, ioexception {
    boolean flag = false;
    if (part.ismimetype(constants.multi_part)) {
      mimemultipart multipart = (mimemultipart) part.getcontent();
      int partcount = multipart.getcount();
      for (int i = 0; i < partcount; i++) {
        bodypart bodypart = multipart.getbodypart(i);
        string disp = bodypart.getdisposition();
        if (disp != null && (disp.equalsignorecase(part.attachment) ||
            disp.equalsignorecase(part.inline))) {
          flag = true;
        } else if (bodypart.ismimetype(constants.multi_part)) {
          flag = iscontainattachment(bodypart);
        } else {
          string contenttype = bodypart.getcontenttype();
          if (contenttype.indexof(constants.application_context) != -1) {
            flag = true;
          }
          if (contenttype.indexof(constants.name_context) != -1) {
            flag = true;
          }
        }
        if (flag){
          break;
        }
      }
    } else if (part.ismimetype(constants.message_rfc)) {
      flag = iscontainattachment((part)part.getcontent());
    }
    return flag;
  }
  /**
   * 保存附件
   * @param part 邮件中多个组合体中的其中一个组合体
   * @param destdir 附件保存目录
   * @throws unsupportedencodingexception
   * @throws messagingexception
   * @throws filenotfoundexception
   * @throws ioexception
   */
  public string saveattachment(part part, string destdir) throws unsupportedencodingexception,
      messagingexception, filenotfoundexception, ioexception {
    string filename=null;
    if (part.ismimetype(constants.multi_part)) {
      multipart multipart = (multipart) part.getcontent();  //复杂体邮件
      //复杂体邮件包含多个邮件体
      int partcount = multipart.getcount();
      for (int i = 0; i < partcount; i++) {
        //获得复杂体邮件中其中一个邮件体
        bodypart bodypart = multipart.getbodypart(i);
        //某一个邮件体也有可能是由多个邮件体组成的复杂体
        string disp = bodypart.getdisposition();
        if (disp != null && (disp.equalsignorecase(part.attachment) || disp.equalsignorecase
            (part.inline))) {
          inputstream is = bodypart.getinputstream();
          savefile(is, destdir, decodetext(bodypart.getfilename()));
          filename=decodetext(bodypart.getfilename());
        } else if (bodypart.ismimetype(constants.multi_part)) {
          saveattachment(bodypart,destdir);
        } else {
          string contenttype = bodypart.getcontenttype();
          if (contenttype.indexof(constants.name_context) != -1 || contenttype.indexof
              (constants.application_context) != -1) {
            savefile(bodypart.getinputstream(), destdir, decodetext(bodypart.getfilename()));
            filename=decodetext(bodypart.getfilename());
          }
        }
      }
    } else if (part.ismimetype(constants.message_rfc)) {
      saveattachment((part) part.getcontent(),destdir);
    }
    return filename;
  }
  /**
   * 读取输入流中的数据保存至指定目录
   * @param is 输入流
   * @param filename 文件名
   * @param destdir 文件存储目录
   * @throws filenotfoundexception
   * @throws ioexception
   */
  private void savefile(inputstream is, string destdir, string filename)
      throws filenotfoundexception, ioexception {
    bufferedinputstream bis = new bufferedinputstream(is);
    if(filename.contains(constants.txt_sufixx)) {
      bufferedoutputstream bos = new bufferedoutputstream(
          new fileoutputstream(new file(destdir + filename)));
      int len = -1;
      while ((len = bis.read()) != -1) {
        bos.write(len);
        bos.flush();
      }
      bos.close();
      bis.close();
    }
  }
}

其中查询邮件的条件,你可以自行更改。

spring boot定时任务接收邮件并且存储附件的方法讲解

接收邮件服务器的配置

spring boot定时任务接收邮件并且存储附件的方法讲解

可能出现的bug

说说用模板可能会碰到的bug。

怎么回事呢?代码写了,看了好几遍也没错,就是运行就报错,在网上看了别人的代码拿过来还是报错,报错如下:

spring boot定时任务接收邮件并且存储附件的方法讲解

这个错误大概意思就是我的模板的html中每个标签都要是闭标签,要这种类型的<a></a>,假如是<img xxx>这种标签就会报错。

如下所示,最坑的方法就是修改的,而且以后html的标签都要是一对一对的,坑啊、

spring boot定时任务接收邮件并且存储附件的方法讲解

后来有找了很多资料,原来发现是这里,themeleaf默认应该是2.xx版本,这个版本解析标签都要是一对一对的,到了3.xx之后,就不需要这么麻烦了!

spring boot定时任务接收邮件并且存储附件的方法讲解

都是版本问题

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对服务器之家的支持。如果你想了解更多相关内容请查看下面相关链接

原文链接:https://blog.csdn.net/CLG_CSDN/article/details/85261438

延伸 · 阅读

精彩推荐