-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
ImapSimple.ts
235 lines (201 loc) · 7.01 KB
/
ImapSimple.ts
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/* eslint-disable @typescript-eslint/no-use-before-define */
import { EventEmitter } from 'events';
import type Imap from 'imap';
import { type ImapMessage } from 'imap';
import * as qp from 'quoted-printable';
import * as iconvlite from 'iconv-lite';
import * as utf8 from 'utf8';
import * as uuencode from 'uuencode';
import { getMessage } from './helpers/getMessage';
import type { Message, MessagePart } from './types';
const IMAP_EVENTS = ['alert', 'mail', 'expunge', 'uidvalidity', 'update', 'close', 'end'] as const;
export class ImapSimple extends EventEmitter {
/** flag to determine whether we should suppress ECONNRESET from bubbling up to listener */
private ending = false;
constructor(private readonly imap: Imap) {
super();
// pass most node-imap `Connection` events through 1:1
IMAP_EVENTS.forEach((event) => {
this.imap.on(event, this.emit.bind(this, event));
});
// special handling for `error` event
this.imap.on('error', (e: Error & { code?: string }) => {
// if .end() has been called and an 'ECONNRESET' error is received, don't bubble
if (e && this.ending && e.code?.toUpperCase() === 'ECONNRESET') {
return;
}
this.emit('error', e);
});
}
/** disconnect from the imap server */
end(): void {
// set state flag to suppress 'ECONNRESET' errors that are triggered when .end() is called.
// it is a known issue that has no known fix. This just temporarily ignores that error.
// https://github.com/mscdex/node-imap/issues/391
// https://github.com/mscdex/node-imap/issues/395
this.ending = true;
// using 'close' event to unbind ECONNRESET error handler, because the node-imap
// maintainer claims it is the more reliable event between 'end' and 'close'.
// https://github.com/mscdex/node-imap/issues/394
this.imap.once('close', () => {
this.ending = false;
});
this.imap.end();
}
/**
* Search the currently open mailbox, and retrieve the results
*
* Results are in the form:
*
* [{
* attributes: object,
* parts: [ { which: string, size: number, body: string }, ... ]
* }, ...]
*
* See node-imap's ImapMessage signature for information about `attributes`, `which`, `size`, and `body`.
* For any message part that is a `HEADER`, the body is automatically parsed into an object.
*/
async search(
/** Criteria to use to search. Passed to node-imap's .search() 1:1 */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
searchCriteria: any[],
/** Criteria to use to fetch the search results. Passed to node-imap's .fetch() 1:1 */
fetchOptions: Imap.FetchOptions,
) {
return await new Promise<Message[]>((resolve, reject) => {
this.imap.search(searchCriteria, (e, uids) => {
if (e) {
reject(e);
return;
}
if (uids.length === 0) {
resolve([]);
return;
}
const fetch = this.imap.fetch(uids, fetchOptions);
let messagesRetrieved = 0;
const messages: Message[] = [];
const fetchOnMessage = async (message: Imap.ImapMessage, seqNo: number) => {
const msg: Message = await getMessage(message);
msg.seqNo = seqNo;
messages[seqNo] = msg;
messagesRetrieved++;
if (messagesRetrieved === uids.length) {
resolve(messages.filter((m) => !!m));
}
};
const fetchOnError = (error: Error) => {
fetch.removeListener('message', fetchOnMessage);
fetch.removeListener('end', fetchOnEnd);
reject(error);
};
const fetchOnEnd = () => {
fetch.removeListener('message', fetchOnMessage);
fetch.removeListener('error', fetchOnError);
};
fetch.on('message', fetchOnMessage);
fetch.once('error', fetchOnError);
fetch.once('end', fetchOnEnd);
});
});
}
/** Download a "part" (either a portion of the message body, or an attachment) */
async getPartData(
/** The message returned from `search()` */
message: Message,
/** The message part to be downloaded, from the `message.attributes.struct` Array */
part: MessagePart,
) {
return await new Promise<string>((resolve, reject) => {
const fetch = this.imap.fetch(message.attributes.uid, {
bodies: [part.partID],
struct: true,
});
const fetchOnMessage = async (msg: ImapMessage) => {
const result = await getMessage(msg);
if (result.parts.length !== 1) {
reject(new Error('Got ' + result.parts.length + ' parts, should get 1'));
return;
}
const data = result.parts[0].body as string;
const encoding = part.encoding.toUpperCase();
if (encoding === 'BASE64') {
resolve(Buffer.from(data, 'base64').toString());
return;
}
if (encoding === 'QUOTED-PRINTABLE') {
if (part.params?.charset?.toUpperCase() === 'UTF-8') {
resolve(Buffer.from(utf8.decode(qp.decode(data))).toString());
} else {
resolve(Buffer.from(qp.decode(data)).toString());
}
return;
}
if (encoding === '7BIT') {
resolve(Buffer.from(data).toString('ascii'));
return;
}
if (encoding === '8BIT' || encoding === 'BINARY') {
const charset = part.params?.charset ?? 'utf-8';
resolve(iconvlite.decode(Buffer.from(data), charset));
return;
}
if (encoding === 'UUENCODE') {
const parts = data.toString().split('\n'); // remove newline characters
const merged = parts.splice(1, parts.length - 4).join(''); // remove excess lines and join lines with empty string
resolve(uuencode.decode(merged));
return;
}
// if it gets here, the encoding is not currently supported
reject(new Error('Unknown encoding ' + part.encoding));
};
const fetchOnError = (error: Error) => {
fetch.removeListener('message', fetchOnMessage);
fetch.removeListener('end', fetchOnEnd);
reject(error);
};
const fetchOnEnd = () => {
fetch.removeListener('message', fetchOnMessage);
fetch.removeListener('error', fetchOnError);
};
fetch.once('message', fetchOnMessage);
fetch.once('error', fetchOnError);
fetch.once('end', fetchOnEnd);
});
}
/** Adds the provided flag(s) to the specified message(s). */
async addFlags(
/** The messages uid */
uid: number[],
/** The flags to add to the message(s). */
flags: string | string[],
) {
return await new Promise<void>((resolve, reject) => {
this.imap.addFlags(uid, flags, (e) => (e ? reject(e) : resolve()));
});
}
/** Returns a list of mailboxes (folders). */
async getBoxes() {
return await new Promise<Imap.MailBoxes>((resolve, reject) => {
this.imap.getBoxes((e, boxes) => (e ? reject(e) : resolve(boxes)));
});
}
/** Open a mailbox */
async openBox(
/** The name of the box to open */
boxName: string,
): Promise<Imap.Box> {
return await new Promise((resolve, reject) => {
this.imap.openBox(boxName, (e, result) => (e ? reject(e) : resolve(result)));
});
}
/** Close a mailbox */
async closeBox(
/** If autoExpunge is true, any messages marked as Deleted in the currently open mailbox will be removed @default true */
autoExpunge = true,
) {
return await new Promise<void>((resolve, reject) => {
this.imap.closeBox(autoExpunge, (e) => (e ? reject(e) : resolve()));
});
}
}