diff --git a/application/imap-service.js b/application/imap-service.js index 1123ec8..dd00831 100644 --- a/application/imap-service.js +++ b/application/imap-service.js @@ -6,6 +6,7 @@ const pSeries = require('p-series') const retry = require('async-retry') const debug = require('debug')('48hr-email:imap') const _ = require('lodash') +const moment = require('moment') const Mail = require('../domain/mail') @@ -198,7 +199,6 @@ class ImapService extends EventEmitter { * @param {Date} deleteMailsBefore delete mails before this date instance */ async deleteOldMails(deleteMailsBefore) { - debug(`deleting mails before ${deleteMailsBefore}`) const uids = await this._searchWithoutFetch([ ['!DELETED'], ['BEFORE', deleteMailsBefore] @@ -208,10 +208,27 @@ class ImapService extends EventEmitter { } debug(`deleting mails ${uids}`) - await this.connection.deleteMessage(uids) - console.log(`deleted ${uids.length} old messages.`) - uids.forEach(uid => this.emit(ImapService.EVENT_DELETED_MAIL, uid)) + const DeleteOlderThan = moment() + .subtract(this.config.email.deleteMailsOlderThanDays, 'days') + .toDate() + + let toDelete = [] + const uidwithHeaders = await this._getMailHeaders(uids) + uidwithHeaders.forEach(mail => { + if (mail['attributes'].date < DeleteOlderThan) { + toDelete.push(mail['attributes'].uid) + } + }) + + if (toDelete.length === 0) { + debug('no mails to delete.') + return + } + + await this.connection.deleteMessage(toDelete) + toDelete.forEach(uid => this.emit(ImapService.EVENT_DELETED_MAIL, uid)) + console.log(`deleted ${toDelete.length} old messages.`) } /** diff --git a/application/mail-processing-service.js b/application/mail-processing-service.js index 9d5a2e4..637f9ca 100644 --- a/application/mail-processing-service.js +++ b/application/mail-processing-service.js @@ -73,7 +73,11 @@ class MailProcessingService extends EventEmitter { try { await this.imapService.deleteOldMails( moment() - .subtract(this.config.email.deleteMailsOlderThanDays, 'days') + // Because of how we have to handle the times (IMAP isnt time-aware), we need to subtract one day + // to get all mails in their last few hours before technical purge + // + // This is a bit of a hack, but it works. See imap-service.js#deleteOldMails (L211-227) for more info + .subtract(this.config.email.deleteMailsOlderThanDays - 1, 'days') .toDate() ) } catch (error) {