51 lines
1.7 KiB
TypeScript
51 lines
1.7 KiB
TypeScript
import addressparser from "nodemailer/lib/addressparser";
|
|
|
|
export type Mailbox = { address: string; name?: string };
|
|
|
|
const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
|
|
|
export function validEmail(value: string): boolean {
|
|
return EMAIL.test(value.trim());
|
|
}
|
|
|
|
export function parseMailbox(input: string): Mailbox | null {
|
|
const parsed = addressparser(input.trim());
|
|
if (parsed.length !== 1) return null;
|
|
const address = parsed[0]?.address?.trim().toLowerCase();
|
|
if (!address || !validEmail(address)) return null;
|
|
const name = parsed[0]?.name?.replace(/[\r\n]+/g, " ").trim();
|
|
return name ? { address, name } : { address };
|
|
}
|
|
|
|
export function parseMailboxList(input: string | string[] | undefined): Mailbox[] {
|
|
if (!input) return [];
|
|
const values = Array.isArray(input) ? input : [input];
|
|
const result: Mailbox[] = [];
|
|
for (const value of values) {
|
|
const parsed = addressparser(value);
|
|
for (const item of parsed) {
|
|
const address = item.address?.trim().toLowerCase();
|
|
if (!address || !validEmail(address)) {
|
|
throw new Error(`Ungültige E-Mail-Adresse: ${item.address || value}`);
|
|
}
|
|
const name = item.name?.replace(/[\r\n]+/g, " ").trim();
|
|
result.push(name ? { address, name } : { address });
|
|
}
|
|
}
|
|
return result;
|
|
}
|
|
|
|
export function domainOf(address: string): string {
|
|
return address.split("@")[1]?.toLowerCase() ?? "";
|
|
}
|
|
|
|
export function formatMailbox(mailbox: Mailbox): string {
|
|
if (!mailbox.name) return mailbox.address;
|
|
const name = mailbox.name.replace(/["\\]/g, "").replace(/[\r\n]+/g, " ");
|
|
return `"${name}" <${mailbox.address}>`;
|
|
}
|
|
|
|
export function addressesOf(list: Mailbox[]): string[] {
|
|
return list.map((item) => item.address);
|
|
}
|