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