aero-mail/src/main/providers/imap.provider.ts

767 lines
31 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createImapClient } from './imap-client'
import { convertImapMessage } from '../lib/imap-message'
import type { MailCursor } from '@shared/types/mail-cursor'
import { getAccountEmail } from '@shared/utils/account-email'
import { SmtpSendError } from '../lib/smtp-error'
import { buildComposeAttachments } from '../lib/compose-attachments'
import type { ImapFlow } from 'imapflow'
import { simpleParser } from 'mailparser'
import nodemailer from 'nodemailer'
import type { IEmailProvider, FolderListResult, MessageListOptions, MessageListResult } from '@shared/types/provider'
import type { MessageBody, MessageFlags, MessageEnvelope, ComposeData, InlineImage, Attachment } from '@shared/types/message'
import { SpecialFolderRole } from '@shared/types/folder'
import type { Folder } from '@shared/types/folder'
import type { AccountConfig, ImapCredentials } from '@shared/types/account'
import type { FolderRetentionRule, RetentionCleanupResult } from '@shared/types/retention'
import { sanitizeHtml } from '../lib/html-sanitizer'
// imapflow MailboxObject type
interface ImapMailbox {
name: string
path: string
specialUse?: string
flags?: Set<string>
folders?: ImapMailbox[]
}
export class ImapProvider implements IEmailProvider {
private client: ImapFlow
private connected = false
private newMailCallback: ((folderId: string, envelope: MessageEnvelope) => void) | null = null
private closeCallback: (() => void) | null = null
private mailCursors: Map<string, MailCursor> = new Map<string, MailCursor>()
private readonly pollingFolders: Map<string, Promise<void>> = new Map<string, Promise<void>>()
// Промис с именем отправителя из Sent-папки; await-ится в sendMessage()
private senderNamePromise: Promise<string | null> = Promise.resolve(null)
constructor(private config: AccountConfig) {
this.client = createImapClient(config)
// Без слушателя 'error' обрыв сокета превращается в uncaught exception в main
this.client.on('error', (err: Error) => {
console.warn('[IMAP] connection error:', err.message)
this.connected = false
})
this.client.on('close', () => {
this.connected = false
this.closeCallback?.()
})
}
onClose(callback: () => void): void {
this.closeCallback = callback
}
getMailCursors(): Map<string, MailCursor> {
return new Map<string, MailCursor>(this.mailCursors)
}
seedMailCursors(cursors: Map<string, MailCursor>): void {
this.mailCursors = new Map<string, MailCursor>(cursors)
}
async connect(): Promise<void> {
let timeoutId: ReturnType<typeof setTimeout> | undefined
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error('Connection timed out (10s)')), 10_000)
})
try {
await Promise.race([this.client.connect(), timeoutPromise])
} catch (err) {
// Close any socket imapflow opened or is opening (timeout race case)
this.client.logout().catch(() => {})
throw err
} finally {
clearTimeout(timeoutId)
}
this.connected = true
// Запускаем в фоне; промис await-ится в sendMessage() — гарантия что имя готово к отправке
this.senderNamePromise = this.fetchSenderName().catch(() => null)
}
async disconnect(): Promise<void> {
this.closeCallback = null // штатное закрытие не должно запускать реконнект
this.offNewMail()
if (this.connected) {
try {
await this.client.logout()
} catch { /* ignore */ }
this.connected = false
}
}
isConnected(): boolean {
return this.connected
}
async listFolders(): Promise<FolderListResult> {
// listTree() returns { root: true, folders: ImapMailbox[] }
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
const folders = this.convertMailboxArray(tree.folders ?? [])
await this.populateUnreadCounts(folders)
return { folders }
}
private async populateUnreadCounts(folders: Folder[]): Promise<void> {
// Собираем все папки в плоский список (включая вложенные)
const flatten = (list: Folder[]): Folder[] =>
list.flatMap((f) => [f, ...flatten(f.children)])
const all = flatten(folders)
// Параллельные STATUS запросы с concurrency limit 5
const CONCURRENCY = 5
for (let i = 0; i < all.length; i += CONCURRENCY) {
const batch = all.slice(i, i + CONCURRENCY)
await Promise.all(
batch.map(async (folder) => {
if (folder.selectable === false) return
try {
const status = await this.client.status(folder.id, { unseen: true, messages: true, uidNext: true, uidValidity: true }) as
{ unseen?: number; messages?: number; uidNext?: number; uidValidity?: bigint } | null
if (status) {
folder.unreadCount = status.unseen ?? 0
folder.totalCount = status.messages ?? 0
folder.uidNext = status.uidNext
folder.uidValidity = status.uidValidity?.toString()
} else {
folder.statusError = 'Сервер не вернул статус папки'
}
} catch (error: unknown) {
folder.statusError = error instanceof Error ? error.message : String(error)
}
})
)
}
}
async listMessages(options: MessageListOptions): Promise<MessageListResult> {
const lock = await this.client.getMailboxLock(options.folderId)
try {
if (options.unseenOnly) {
return await this.listUnseenMessages(options)
}
const total = (this.client.mailbox as { exists?: number })?.exists ?? 0
if (total === 0) return { messages: [], total: 0, unseen: 0 }
// IMAP sequence numbers are 1-based, newest = highest number
const end = Math.max(1, total - options.offset)
const start = Math.max(1, end - options.limit + 1)
if (start > total) return { messages: [], total, unseen: 0 }
const messages: MessageEnvelope[] = []
for await (const msg of this.client.fetch(`${start}:${end}`, {
uid: true,
envelope: true, internalDate: true,
flags: true,
bodyStructure: true
})) {
messages.push(convertImapMessage(msg, options.folderId))
}
// Newest first
messages.reverse()
return { messages, total, unseen: 0 }
} finally {
lock.release()
}
}
private async listUnseenMessages(options: MessageListOptions): Promise<MessageListResult> {
// Mailbox lock is already held by listMessages caller
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
if (!uids || uids.length === 0) return { messages: [], total: 0, unseen: 0 }
const total = uids.length
// Sort descending — higher UID = newer message
const sorted = [...uids].sort((a, b) => b - a)
const page = sorted.slice(options.offset, options.offset + options.limit)
if (page.length === 0) return { messages: [], total, unseen: total }
const uidSet = page.join(',')
const messages: MessageEnvelope[] = []
for await (const msg of this.client.fetch(uidSet, {
uid: true,
envelope: true, internalDate: true,
flags: true,
bodyStructure: true
}, { uid: true })) {
messages.push(convertImapMessage(msg, options.folderId))
}
// Fetch returns ascending order → reverse to newest first
messages.sort((a, b) => Number(b.id) - Number(a.id))
return { messages, total, unseen: total }
}
async listMessagesAfterUid(folderId: string, afterUid: number, limit: number): Promise<MessageListResult> {
const lock = await this.client.getMailboxLock(folderId)
try {
const found = await this.client.search({ uid: `${afterUid + 1}:*` }, { uid: true })
const uids: number[] = (found || []).filter((uid: number): boolean => uid > afterUid).sort((first: number, second: number): number => first - second)
const page: number[] = uids.slice(0, limit)
if (!page.length) return { messages: [], total: 0, unseen: 0 }
const messages: MessageEnvelope[] = []
for await (const message of this.client.fetch(page.join(','), { uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true }, { uid: true })) {
messages.push(convertImapMessage(message, folderId))
}
messages.sort((first: MessageEnvelope, second: MessageEnvelope): number => Number(first.id) - Number(second.id))
return { messages, total: uids.length, unseen: messages.filter((message: MessageEnvelope): boolean => !message.flags.seen).length }
} finally { lock.release() }
}
async fetchMessageBody(folderId: string, messageId: string): Promise<MessageBody> {
const lock = await this.client.getMailboxLock(folderId)
try {
// imapflow использует BODY.PEEK[] (не BODY[]) для source-запросов — \Seen не ставится
const download = await this.client.download(messageId, undefined, { uid: true })
if (!download?.content) {
return { id: messageId, html: null, text: null, references: null, inlineImages: [], attachments: [] }
}
const parsed = await simpleParser(download.content)
const inlineImages: InlineImage[] = []
const attachments: Attachment[] = []
for (const att of parsed.attachments) {
if (att.contentDisposition === 'inline' && att.contentId && att.contentType.startsWith('image/')) {
inlineImages.push({
cid: att.contentId.replace(/[<>]/g, ''),
contentType: att.contentType,
data: att.content.toString('base64')
})
} else if (att.contentDisposition === 'attachment' || att.filename) {
attachments.push({
id: att.checksum ?? att.filename ?? '',
filename: att.filename ?? 'attachment',
contentType: att.contentType,
size: att.size ?? 0
})
}
}
// References header: mailparser returns string[] — join to space-separated string
const refsArray = (parsed as unknown as { references?: string | string[] }).references
const references = Array.isArray(refsArray)
? refsArray.join(' ')
: (typeof refsArray === 'string' ? refsArray : null)
const sanitizedHtml = parsed.html ? sanitizeHtml(parsed.html) : null
// Если text/plain части нет — деривируем из HTML (правильно: style/script уже отфильтрованы)
const text = parsed.text ?? (parsed.html ? this.htmlToPlainText(parsed.html) : null)
return {
id: messageId,
html: sanitizedHtml,
text,
references,
inlineImages,
attachments
}
} finally {
lock.release()
}
}
async downloadAttachment(folderId: string, messageId: string, attachmentId: string): Promise<Buffer> {
// TODO: имапфлоу поддерживает частичный download по part-номеру из BODYSTRUCTURE
// (client.download(uid, '2', {uid:true})). Оптимизация требует хранить part в Attachment.id
// и пробрасывать через IPC. Сейчас скачивается всё письмо целиком.
const lock = await this.client.getMailboxLock(folderId)
try {
const download = await this.client.download(messageId, undefined, { uid: true })
if (!download) throw new Error('Message not found')
const parsed = await simpleParser(download.content)
const att = parsed.attachments.find(
(a) => (a.checksum ?? a.filename ?? '') === attachmentId || a.filename === attachmentId
)
if (!att) throw new Error('Attachment not found')
return att.content
} finally {
lock.release()
}
}
async updateFlags(folderId: string, messageIds: string[], flags: Partial<MessageFlags>): Promise<void> {
const lock = await this.client.getMailboxLock(folderId)
try {
const uidSet = messageIds.join(',')
const addFlags: string[] = []
const removeFlags: string[] = []
if (flags.seen === true) addFlags.push('\\Seen')
if (flags.seen === false) removeFlags.push('\\Seen')
if (flags.flagged === true) addFlags.push('\\Flagged')
if (flags.flagged === false) removeFlags.push('\\Flagged')
if (flags.answered === true) addFlags.push('\\Answered')
if (flags.deleted === true) addFlags.push('\\Deleted')
if (addFlags.length > 0) {
await this.client.messageFlagsAdd(uidSet, addFlags, { uid: true })
}
if (removeFlags.length > 0) {
await this.client.messageFlagsRemove(uidSet, removeFlags, { uid: true })
}
} finally {
lock.release()
}
}
async markAllRead(folderId: string): Promise<void> {
const lock = await this.client.getMailboxLock(folderId)
try {
const uids = await this.client.search({ seen: false }, { uid: true }) as number[]
if (!uids || uids.length === 0) return
await this.client.messageFlagsAdd(uids.join(','), ['\\Seen'], { uid: true })
} finally {
lock.release()
}
}
async deleteMessages(folderId: string, messageIds: string[]): Promise<void> {
const lock = await this.client.getMailboxLock(folderId)
try {
const uidSet = messageIds.join(',')
await this.client.messageDelete(uidSet, { uid: true })
} finally {
lock.release()
}
}
async enforceRetention(rules: FolderRetentionRule[]): Promise<RetentionCleanupResult[]> {
if (rules.length === 0) return []
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
const folders = this.convertMailboxArray(tree.folders ?? [])
const results: RetentionCleanupResult[] = []
await this.enforceRetentionTree(folders, rules, null, results)
return results
}
// inheritedLimit — лимит, унаследованный от ближайшего предка с recursive: true (null — нет ограничения)
private async enforceRetentionTree(
folders: Folder[],
rules: FolderRetentionRule[],
inheritedLimit: number | null,
results: RetentionCleanupResult[]
): Promise<void> {
for (const folder of folders) {
const ownRule = rules.find((r) => r.folderId === folder.id)
const effectiveLimit = ownRule ? ownRule.maxMessages : inheritedLimit
if (effectiveLimit !== null) {
try {
const deletedCount = await this.trimFolder(folder.id, effectiveLimit)
if (deletedCount > 0) results.push({ folderId: folder.id, deletedCount })
} catch (err) {
console.warn(`[IMAP:retention] folder error ${folder.id}:`, (err as Error).message)
}
}
const childInheritedLimit = ownRule ? (ownRule.recursive ? ownRule.maxMessages : null) : inheritedLimit
if (folder.children.length > 0) {
await this.enforceRetentionTree(folder.children, rules, childInheritedLimit, results)
}
}
}
// Удаляет самые старые письма сверх maxMessages. Сортировка по sequence number —
// тот же порядок "старое → новое", что используется в listMessages.
private async trimFolder(folderId: string, maxMessages: number): Promise<number> {
const lock = await this.client.getMailboxLock(folderId)
try {
const total = (this.client.mailbox as { exists?: number })?.exists ?? 0
const excess = total - maxMessages
if (excess <= 0) return 0
const uidsToDelete: number[] = []
for await (const msg of this.client.fetch(`1:${excess}`, { uid: true })) {
uidsToDelete.push((msg as { uid: number }).uid)
}
if (uidsToDelete.length === 0) return 0
await this.client.messageDelete(uidsToDelete.join(','), { uid: true })
return uidsToDelete.length
} finally {
lock.release()
}
}
async sendMessage(compose: ComposeData): Promise<void> {
const creds = this.config.credentials as ImapCredentials
// SMTP-настройки: явные или авто-вывод из IMAP-хоста
const smtpHost = creds.smtpHost ?? creds.host.replace(/^imap\./i, 'smtp.')
const smtpPort = creds.smtpPort ?? 587
const smtpSecure = creds.smtpSecure ?? smtpPort === 465
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpSecure,
auth: { user: creds.username, pass: creds.password },
tls: creds.smtpAllowSelfSigned ? { rejectUnauthorized: false } : undefined
})
// Если email хранится без домена (только логин) — достраиваем из IMAP-хоста
const emailAddress = getAccountEmail(this.config)
// Имя отправителя: await-им промис из connect() — гарантирует что имя готово
const senderName = await this.senderNamePromise
const displayName = senderName ?? this.config.label
const from = displayName
? { name: displayName, address: emailAddress }
: emailAddress
// Собираем text + html из отдельных частей
const fullText = compose.quotedText
? compose.body + '\n\n' + compose.quotedText
: compose.body
const fullHtml = ImapProvider.buildComposeHtml(compose)
if (process.env.NODE_ENV !== 'production') {
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
smtpHost, smtpPort, smtpSecure, from, compose.to)
}
const info = await transporter.sendMail({
from,
to: compose.to.join(', '),
cc: compose.cc.length ? compose.cc.join(', ') : undefined,
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
subject: compose.subject,
text: fullText,
html: fullHtml,
inReplyTo: compose.inReplyTo,
references: compose.references,
attachments: buildComposeAttachments(compose)
}).catch((error: unknown): never => {
throw new SmtpSendError(error, creds)
})
// Сохраняем в папку Sent (best-effort)
try {
const raw = await this.buildRawMessage(info.messageId ?? '', compose, from)
const sentFolder = await this.findSentFolder()
if (sentFolder && raw) {
await this.client.append(sentFolder, raw, ['\\Seen'])
}
} catch { /* не критично — письмо уже отправлено */ }
}
private async findSentFolder(): Promise<string | null> {
try {
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
return this.findFolderByRole(tree.folders ?? [], SpecialFolderRole.Sent)
} catch { return null }
}
private findFolderByRole(folders: ImapMailbox[], role: SpecialFolderRole): string | null {
for (const f of folders) {
const detected = this.detectFolderRole(f.specialUse, f.name)
if (detected === role) return f.path
if (f.folders?.length) {
const found = this.findFolderByRole(f.folders, role)
if (found) return found
}
}
return null
}
private async buildRawMessage(
messageId: string,
compose: ComposeData,
from: string | { name: string; address: string }
): Promise<Buffer | null> {
try {
const transporter = nodemailer.createTransport({ streamTransport: true, newline: 'unix' })
const fullText = compose.quotedText
? compose.body + '\n\n' + compose.quotedText
: compose.body
const fullHtml = ImapProvider.buildComposeHtml(compose)
const mail = await transporter.sendMail({
from,
to: compose.to.join(', '),
cc: compose.cc.length ? compose.cc.join(', ') : undefined,
bcc: compose.bcc.length ? compose.bcc.join(', ') : undefined,
subject: compose.subject,
text: fullText,
html: fullHtml,
messageId,
inReplyTo: compose.inReplyTo,
references: compose.references,
date: new Date(),
attachments: buildComposeAttachments(compose)
})
const chunks: Buffer[] = []
await new Promise<void>((res, rej) => {
;(mail.message as NodeJS.ReadableStream).on('data', (c: Buffer) => chunks.push(c))
;(mail.message as NodeJS.ReadableStream).on('end', res)
;(mail.message as NodeJS.ReadableStream).on('error', rej)
})
return Buffer.concat(chunks)
} catch { return null }
}
onNewMail(callback: (folderId: string, envelope: MessageEnvelope) => void): void {
this.newMailCallback = callback
this.client.on('exists', (data: { path: string; count: number; prevCount: number }) => {
// Первый STATUS задаёт границу, события после неё проверяются по UID.
if (data.count > data.prevCount) {
// Немедленно опрашиваем папку, не ждём таймера — но с реальными данными сообщения
this.pollSingleFolder(data.path).catch(() => {})
}
})
}
offNewMail(): void {
this.newMailCallback = null
this.client.removeAllListeners('exists')
}
async searchMessages(query: string, limit: number): Promise<MessageEnvelope[]> {
const results: MessageEnvelope[] = []
// Не ловим ошибки здесь — они должны попасть в withAutoReconnect (AccountManager)
// для переподключения при NoConnection и прочих сетевых сбоях
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
await this.searchFolderTree(tree.folders ?? [], query, limit, results)
return results
}
private shouldSkipFolder(folder: ImapMailbox): boolean {
const n = folder.name.toLowerCase()
const p = (folder.path ?? '').toLowerCase()
return (
n === 'trash' || n === 'deleted items' || n === 'deleted messages' ||
n === 'spam' || n === 'junk' || n === 'junk e-mail' ||
p.includes('[gmail]/trash') || p.includes('[gmail]/spam')
)
}
private async searchFolderTree(
folders: ImapMailbox[],
query: string,
limit: number,
results: MessageEnvelope[]
): Promise<void> {
for (const folder of folders) {
if (results.length >= limit) break
if (this.shouldSkipFolder(folder)) {
if (folder.folders?.length && results.length < limit) {
await this.searchFolderTree(folder.folders, query, limit, results)
}
continue
}
let lock: Awaited<ReturnType<typeof this.client.getMailboxLock>> | null = null
try {
lock = await this.client.getMailboxLock(folder.path)
// SUBJECT + FROM — серверный поиск (быстрее, чем TEXT по телу)
const rawSubject = await this.client.search({ subject: query }, { uid: true })
const rawFrom = await this.client.search({ from: query }, { uid: true })
const subjectUids = Array.isArray(rawSubject) ? rawSubject : []
const fromUids = Array.isArray(rawFrom) ? rawFrom : []
// Объединяем UIDs без дублей
const merged = [...new Set([...subjectUids, ...fromUids])]
if (merged.length) {
const remaining = limit - results.length
const sorted = [...merged].sort((a, b) => b - a).slice(0, remaining)
for await (const msg of this.client.fetch(sorted.join(','), {
uid: true, envelope: true, internalDate: true, flags: true, bodyStructure: true
}, { uid: true })) {
results.push(convertImapMessage(msg, folder.path))
}
}
} catch (e) {
console.error('[IMAP:search] folder error:', folder?.path, e)
}
finally {
lock?.release()
}
if (folder.folders?.length && results.length < limit) {
await this.searchFolderTree(folder.folders, query, limit, results)
}
}
}
async pollNewMessages(): Promise<void> {
if (!this.newMailCallback) return
// Ошибки не глотаем: AccountManager по ним переподключается (withAutoReconnect)
if (!this.connected) throw Object.assign(new Error('IMAP connection lost'), { code: 'NoConnection' })
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
await this.pollFolderTree(tree.folders ?? [])
}
// Немедленная проверка одной папки — вызывается из exists-события
private async pollSingleFolder(folderPath: string): Promise<void> {
if (!this.newMailCallback) return
try {
await this.pollFolderTree([{ name: folderPath, path: folderPath }])
} catch (error: unknown) { console.warn('[IMAP] Ошибка проверки после EXISTS:', error) }
}
private async pollFolderTree(folders: ImapMailbox[]): Promise<void> {
for (const folder of folders) {
try { await this.pollMailbox(folder.path) } catch (error: unknown) {
if (!this.connected) throw error
console.warn('[IMAP] Ошибка проверки папки %s:', folder.path, error)
}
if (folder.folders?.length) await this.pollFolderTree(folder.folders)
}
}
private pollMailbox(folderPath: string): Promise<void> {
const pending: Promise<void> | undefined = this.pollingFolders.get(folderPath)
if (pending) return pending
const task: Promise<void> = this.checkMailbox(folderPath).finally(() => this.pollingFolders.delete(folderPath))
this.pollingFolders.set(folderPath, task)
return task
}
private async checkMailbox(folderPath: string): Promise<void> {
const status = await this.client.status(folderPath, { uidNext: true, uidValidity: true })
if (!status || !status.uidNext || status.uidValidity === undefined) return
const snapshot: MailCursor = { nextUid: status.uidNext, uidValidity: status.uidValidity.toString() }
const previous: MailCursor | undefined = this.mailCursors.get(folderPath)
if (!previous || previous.uidValidity !== snapshot.uidValidity) {
this.mailCursors.set(folderPath, snapshot)
return
}
let afterUid: number = previous.nextUid - 1
while (afterUid + 1 < snapshot.nextUid && this.newMailCallback) {
const page = await this.listMessagesAfterUid(folderPath, afterUid, 100)
const messages: MessageEnvelope[] = page.messages.filter((message: MessageEnvelope): boolean => Number(message.id) < snapshot.nextUid)
if (!messages.length) break
for (const message of messages) {
this.newMailCallback?.(folderPath, message)
afterUid = Math.max(afterUid, Number(message.id))
this.mailCursors.set(folderPath, { ...snapshot, nextUid: afterUid + 1 })
}
}
this.mailCursors.set(folderPath, snapshot)
}
// ---- Private helpers ----
private convertMailboxArray(mailboxes: ImapMailbox[], parentId: string | null = null): Folder[] {
return mailboxes.map((mb) => ({
id: mb.path,
name: mb.name,
role: this.detectFolderRole(mb.specialUse, mb.name),
selectable: !mb.flags?.has('\\Noselect'),
parentId,
unreadCount: 0,
totalCount: 0,
children: mb.folders ? this.convertMailboxArray(mb.folders, mb.path) : []
}))
}
private detectFolderRole(specialUse?: string, name?: string): SpecialFolderRole {
if (specialUse) {
const u = specialUse.toLowerCase()
if (u.includes('inbox')) return SpecialFolderRole.Inbox
if (u.includes('sent')) return SpecialFolderRole.Sent
if (u.includes('draft')) return SpecialFolderRole.Drafts
if (u.includes('trash') || u.includes('deleted')) return SpecialFolderRole.Trash
if (u.includes('junk') || u.includes('spam')) return SpecialFolderRole.Spam
if (u.includes('archive') || u.includes('all')) return SpecialFolderRole.Archive
}
if (name) {
const n = name.toLowerCase()
if (n === 'inbox') return SpecialFolderRole.Inbox
if (n === 'sent' || n === 'sent mail' || n === 'sent items') return SpecialFolderRole.Sent
if (n === 'drafts' || n === 'draft') return SpecialFolderRole.Drafts
if (n === 'trash' || n === 'deleted items' || n === 'deleted messages') return SpecialFolderRole.Trash
if (n === 'spam' || n === 'junk' || n === 'junk e-mail') return SpecialFolderRole.Spam
if (n === 'archive' || n === 'all mail') return SpecialFolderRole.Archive
}
return SpecialFolderRole.None
}
private static buildComposeHtml(compose: ComposeData): string | undefined {
if (!compose.contentHtml && !compose.htmlBody) return undefined
const quote: string = compose.htmlBody ?? ImapProvider.textToHtml(compose.quotedText ?? '')
return (compose.contentHtml ?? ImapProvider.textToHtml(compose.body)) + quote
}
private static textToHtml(text: string): string {
if (!text) return ''
const escaped = text
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
const paragraphs = escaped.split(/\n\n+/).filter((p) => p.trim())
if (paragraphs.length === 0) return '<p></p>'
return paragraphs
.map((p) => `<p>${p.replace(/\n/g, '<br>')}</p>`)
.join('\n')
}
/**
* Ищет имя отправителя в последнем письме папки Sent.
* Возвращает display name из заголовка From или null если Sent пуста / не найдена.
*/
private async fetchSenderName(): Promise<string | null> {
try {
const tree = await this.client.listTree() as { folders?: ImapMailbox[] }
const sentPath = this.findFolderByRole(tree.folders ?? [], SpecialFolderRole.Sent)
if (!sentPath) return null
const status = await this.client.status(sentPath, { messages: true }) as { messages?: number } | null
const total = status?.messages ?? 0
if (total === 0) return null
const lock = await this.client.getMailboxLock(sentPath)
try {
let name: string | null = null
// Берём только самое последнее письмо
for await (const msg of this.client.fetch(`${total}:${total}`, { envelope: true })) {
const fromList = (msg as { envelope?: { from?: Array<{ name?: string }> } }).envelope?.from
const candidate = fromList?.[0]?.name?.trim()
if (candidate) { name = candidate; break }
}
return name
} finally {
lock.release()
}
} catch {
return null
}
}
private htmlToPlainText(html: string): string {
return html
// Убираем целиком блоки <style> и <script> вместе с содержимым
.replace(/<style[^>]*>[\s\S]*?<\/style>/gi, '')
.replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '')
// Блочные элементы → переносы строк
.replace(/<br\s*\/?>/gi, '\n')
.replace(/<\/p>/gi, '\n\n')
.replace(/<\/div>/gi, '\n')
.replace(/<\/li>/gi, '\n')
.replace(/<\/tr>/gi, '\n')
.replace(/<\/h[1-6]>/gi, '\n\n')
// Удаляем все оставшиеся теги
.replace(/<[^>]+>/g, '')
// HTML-сущности
.replace(/&nbsp;/g, ' ')
.replace(/&lt;/g, '<')
.replace(/&gt;/g, '>')
.replace(/&quot;/g, '"')
.replace(/&#39;/g, "'")
// &amp; — последним, чтобы не двойной-декодинг
.replace(/&amp;/g, '&')
// Убираем лишние пустые строки
.replace(/\n{3,}/g, '\n\n')
.trim()
}
}