feat: имя отправителя берётся из Sent-папки, а не из названия аккаунта

При подключении к IMAP фетчим envelope последнего письма из Sent-папки
и извлекаем display name из заголовка From. Результат кешируется в памяти
провайдера (senderName) и используется как From при отправке через SMTP.

Fallback-цепочка: имя из Sent → config.label → только email-адрес.
Запрос выполняется асинхронно (fire-and-forget) и не блокирует connect().

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Aero Mail Dev 2026-04-17 04:55:52 +00:00
parent e348e10994
commit 7061d566a5

View file

@ -37,6 +37,8 @@ export class ImapProvider implements IEmailProvider {
// uid → expiry timestamp; prevents double-toast when exists + poll both fire for the same message
private notifiedUids = new Map<string, number>()
private static readonly NOTIF_TTL_MS = 5 * 60 * 1000 // 5 minutes
// Настоящее имя отправителя, полученное из Sent-папки при подключении
private senderName: string | null = null
constructor(private config: AccountConfig) {
const creds = config.credentials as ImapCredentials
@ -58,6 +60,8 @@ export class ImapProvider implements IEmailProvider {
)
await Promise.race([this.client.connect(), timeout])
this.connected = true
// Пробуем получить имя отправителя из Sent-папки (best-effort, не блокирует)
this.fetchSenderName().then((name) => { this.senderName = name }).catch(() => {})
}
async disconnect(): Promise<void> {
@ -299,8 +303,10 @@ export class ImapProvider implements IEmailProvider {
? this.config.email
: `${this.config.email}@${creds.host.replace(/^[^.]+\./, '')}`
const from = this.config.label
? { name: this.config.label, address: emailAddress }
// Имя отправителя: берём с сервера (из Sent), иначе label аккаунта
const displayName = this.senderName ?? this.config.label
const from = displayName
? { name: displayName, address: emailAddress }
: emailAddress
console.log('[SMTP] host=%s port=%d secure=%s from=%j to=%j',
@ -619,6 +625,38 @@ export class ImapProvider implements IEmailProvider {
}
}
/**
* Ищет имя отправителя в последнем письме папки 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> вместе с содержимым