gmail-to-exchange365
Version:
Complete Gmail to Exchange 365 migration tool with UI - Migrate emails, attachments, and folders seamlessly
84 lines (72 loc) • 2.22 kB
text/typescript
import { Client } from "@microsoft/microsoft-graph-client";
import { FolderMapping } from "./types";
export async function getOrCreateFolder(
client: Client,
folderName: string,
parentFolderId: string = "Inbox"
): Promise<string> {
try {
// Try to find existing folder
const folders = await client
.api(`/me/mailFolders/${parentFolderId}/childFolders`)
.filter(`displayName eq '${folderName}'`)
.get();
if (folders.value && folders.value.length > 0) {
return folders.value[0].id;
}
// Create new folder
const newFolder = await client
.api(`/me/mailFolders/${parentFolderId}/childFolders`)
.post({
displayName: folderName
});
return newFolder.id;
} catch (error: any) {
console.error(`Error creating folder ${folderName}:`, error.message);
// Fallback to Inbox if folder creation fails
return parentFolderId;
}
}
export async function mapGmailLabelsToFolders(
client: Client,
gmailLabels: string[]
): Promise<FolderMapping[]> {
const mappings: FolderMapping[] = [];
// Map common Gmail labels to Exchange folders
const commonMappings: Record<string, string> = {
"INBOX": "Inbox",
"SENT": "Sent Items",
"DRAFT": "Drafts",
"TRASH": "Deleted Items",
"SPAM": "Junk Email",
"IMPORTANT": "Important"
};
for (const label of gmailLabels) {
const folderName = commonMappings[label.toUpperCase()] || label;
try {
const folderId = await getOrCreateFolder(client, folderName);
mappings.push({
gmailLabel: label,
exchangeFolderId: folderId,
exchangeFolderName: folderName
});
} catch (error: any) {
console.error(`Error mapping label ${label}:`, error.message);
}
}
return mappings;
}
export function getFolderIdForLabel(
mappings: FolderMapping[],
labels: string[]
): string {
// Find the first matching label mapping
for (const label of labels) {
const mapping = mappings.find(m => m.gmailLabel === label);
if (mapping) {
return mapping.exchangeFolderId;
}
}
// Default to Inbox
return "Inbox";
}