mail page imap connection mime 4

This commit is contained in:
alma 2025-04-15 22:31:49 +02:00
parent 75aa93e286
commit 641d7ddb8a

View File

@ -28,17 +28,18 @@ interface Account {
}
interface Email {
id: number;
accountId: number;
id: string;
accountId: string;
from: string;
fromName: string;
fromName?: string;
to: string;
subject: string;
body: string;
date: string;
preview: string;
category: string;
date: Date;
read: boolean;
starred: boolean;
category: string;
}
// Improved MIME Decoder Implementation for Infomaniak
@ -319,6 +320,27 @@ function cleanHtml(html: string): string {
if (!html) return '';
return html
// Fix common Infomaniak-specific character encodings
.replace(/=C2=A0/g, ' ') // non-breaking space
.replace(/=E2=80=93/g, '\u2013') // en dash
.replace(/=E2=80=94/g, '\u2014') // em dash
.replace(/=E2=80=98/g, '\u2018') // left single quote
.replace(/=E2=80=99/g, '\u2019') // right single quote
.replace(/=E2=80=9C/g, '\u201C') // left double quote
.replace(/=E2=80=9D/g, '\u201D') // right double quote
.replace(/=C3=A0/g, 'à')
.replace(/=C3=A2/g, 'â')
.replace(/=C3=A9/g, 'é')
.replace(/=C3=A8/g, 'è')
.replace(/=C3=AA/g, 'ê')
.replace(/=C3=AB/g, 'ë')
.replace(/=C3=B4/g, 'ô')
.replace(/=C3=B9/g, 'ù')
.replace(/=C3=BB/g, 'û')
.replace(/=C3=80/g, 'À')
.replace(/=C3=89/g, 'É')
.replace(/=C3=87/g, 'Ç')
// Clean up HTML entities
.replace(/ç/g, 'ç')
.replace(/é/g, 'é')
.replace(/è/g, 'ë')
@ -329,48 +351,38 @@ function cleanHtml(html: string): string {
.replace(/\xA0/g, ' ');
}
// Update the decodeMimeContent function to use the new implementation
function decodeMimeContent(content: string): string {
if (!content) return '';
try {
// Handle the special case with InfomaniakPhpMail boundary
if (content.includes('---InfomaniakPhpMail')) {
const boundaryMatch = content.match(/---InfomaniakPhpMail[\w\d]+/);
if (boundaryMatch) {
const boundary = boundaryMatch[0];
const result = processMultipartEmail(content, boundary);
return result.html || result.text || content;
}
// Check if this is an Infomaniak multipart message
if (content.includes('Content-Type: multipart/')) {
const boundary = content.match(/boundary="([^"]+)"/)?.[1];
if (boundary) {
const parts = content.split('--' + boundary);
let htmlContent = '';
let textContent = '';
parts.forEach(part => {
if (part.includes('Content-Type: text/html')) {
const match = part.match(/\r?\n\r?\n([\s\S]+?)(?=\r?\n--)/);
if (match) {
htmlContent = cleanHtml(match[1]);
}
} else if (part.includes('Content-Type: text/plain')) {
const match = part.match(/\r?\n\r?\n([\s\S]+?)(?=\r?\n--)/);
if (match) {
textContent = cleanHtml(match[1]);
}
}
});
// Prefer HTML content if available
return htmlContent || textContent;
}
// Regular email parsing
const result = parseFullEmail(content);
if ('html' in result && result.html) {
return extractHtmlBody(result.html);
} else if ('text' in result && result.text) {
return result.text;
}
// If parsing fails, try simple decoding
if (content.includes('Content-Type:') || content.includes('Content-Transfer-Encoding:')) {
const simpleDecoded = processSinglePartEmail(content);
return simpleDecoded.text || simpleDecoded.html || content;
}
// Try to detect encoding and decode accordingly
if (content.includes('=?UTF-8?B?') || content.includes('=?utf-8?B?')) {
return decodeMIME(content, 'base64', 'utf-8');
} else if (content.includes('=?UTF-8?Q?') || content.includes('=?utf-8?Q?') || content.includes('=20')) {
return decodeMIME(content, 'quoted-printable', 'utf-8');
}
// If nothing else worked, return the original content
return content;
} catch (error) {
console.error('Error decoding email content:', error);
return content;
}
// If not multipart or no boundary found, clean the content directly
return cleanHtml(content);
}
export default function MailPage() {
@ -383,7 +395,7 @@ export default function MailPage() {
// State declarations
const [selectedAccount, setSelectedAccount] = useState(1);
const [currentView, setCurrentView] = useState('inbox');
const [selectedEmail, setSelectedEmail] = useState<number | null>(null);
const [selectedEmail, setSelectedEmail] = useState<Email | null>(null);
const [sidebarOpen, setSidebarOpen] = useState(true);
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
const [composeOpen, setComposeOpen] = useState(false);
@ -391,7 +403,7 @@ export default function MailPage() {
const [foldersDropdownOpen, setFoldersDropdownOpen] = useState(false);
const [showAccountActions, setShowAccountActions] = useState<number | null>(null);
const [showEmailActions, setShowEmailActions] = useState(false);
const [selectedEmails, setSelectedEmails] = useState<number[]>([]);
const [selectedEmails, setSelectedEmails] = useState<string[]>([]);
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
const [deleteType, setDeleteType] = useState<'email' | 'emails' | 'account'>('email');
const [itemToDelete, setItemToDelete] = useState<number | null>(null);
@ -399,37 +411,29 @@ export default function MailPage() {
const [showCc, setShowCc] = useState(false);
const [showBcc, setShowBcc] = useState(false);
const [emails, setEmails] = useState<Email[]>([]);
const [loading, setLoading] = useState(true);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [composeSubject, setComposeSubject] = useState('');
const [composeRecipient, setComposeRecipient] = useState('');
const [composeContent, setComposeContent] = useState('');
// Fetch emails from IMAP API
useEffect(() => {
async function fetchEmails() {
try {
setError(null);
setLoading(true);
const res = await fetch('/api/mail');
if (!res.ok) {
throw new Error('Failed to fetch emails');
}
const data = await res.json();
if (data.error) {
throw new Error(data.error);
}
setEmails(data.messages || []);
} catch (error) {
console.error('Error fetching emails:', error);
setError('Unable to load emails. Please try again later.');
} finally {
setLoading(false);
const loadEmails = async () => {
setLoading(true);
setError(null);
try {
const response = await fetch('/api/mail');
if (!response.ok) {
throw new Error('Failed to fetch emails');
}
const data = await response.json();
setEmails(data);
} catch (err) {
setError(err instanceof Error ? err.message : 'An error occurred');
} finally {
setLoading(false);
}
fetchEmails();
}, [currentView]);
};
// Mock folders data
const folders = [
@ -445,11 +449,23 @@ export default function MailPage() {
...accounts
];
// Filter emails based on selected account and view
const filteredEmails = emails.filter(email =>
(selectedAccount === 0 || email.accountId === selectedAccount) &&
(currentView === 'starred' ? email.starred : email.category === currentView)
);
// Filter emails based on current view
const filteredEmails = emails.filter(email => {
if (selectedAccount !== 'all' && email.accountId !== selectedAccount) {
return false;
}
switch (currentView) {
case 'starred':
return email.starred;
case 'sent':
return email.category === 'sent';
case 'trash':
return email.category === 'trash';
default:
return email.category === 'inbox';
}
});
// Format date for display
const formatDate = (dateString: string) => {
@ -470,17 +486,12 @@ export default function MailPage() {
};
// Update email click handler to work without mark-read endpoint
const handleEmailClick = (emailId: number) => {
// Since the mark-read endpoint is not available, just update the UI
const updatedEmails = emails.map(email =>
email.id === emailId ? { ...email, read: true } : email
);
setEmails(updatedEmails);
setSelectedEmail(emailId);
const handleEmailSelect = (email: Email) => {
setSelectedEmail(selectedEmail?.id === email.id ? null : email);
};
// Toggle starred status
const toggleStarred = async (emailId: number, e: React.MouseEvent) => {
const toggleStarred = async (emailId: string, e: React.MouseEvent) => {
e.stopPropagation();
// Toggle star in IMAP
@ -501,7 +512,7 @@ export default function MailPage() {
};
// Handle bulk selection
const toggleEmailSelection = (emailId: number, e: React.MouseEvent) => {
const toggleEmailSelection = (emailId: string, e: React.MouseEvent) => {
e.stopPropagation();
setSelectedEmails(prev =>
prev.includes(emailId)
@ -608,6 +619,66 @@ export default function MailPage() {
setComposeContent(content);
};
const handleEmailCheckbox = (e: React.ChangeEvent<HTMLInputElement>, emailId: string) => {
e.stopPropagation();
if (e.target.checked) {
setSelectedEmails([...selectedEmails, emailId]);
} else {
setSelectedEmails(selectedEmails.filter(id => id !== emailId));
}
};
// Update the mock data with all required properties
const mockEmails: Email[] = [
{
id: "1",
accountId: "1",
from: "john@example.com",
fromName: "John Doe",
to: "me@example.com",
subject: "Hello",
body: "This is a test email",
preview: "This is a test email",
category: "inbox",
date: new Date(),
read: false,
starred: false
}
];
// Update the email action handlers to use string IDs
const handleMarkAsRead = (emailId: string, isRead: boolean) => {
setEmails(emails.map(email =>
email.id === emailId ? { ...email, read: isRead } : email
));
};
const handleDeleteEmail = (emailId: string) => {
setEmails(emails.filter(email => email.id !== emailId));
setSelectedEmails(selectedEmails.filter(id => id !== emailId));
};
// Update the bulk action handlers
const handleBulkAction = (action: 'delete' | 'mark-read' | 'mark-unread') => {
selectedEmails.forEach(emailId => {
const email = emails.find(e => e.id === emailId);
if (email) {
switch (action) {
case 'delete':
handleDeleteEmail(emailId);
break;
case 'mark-read':
handleMarkAsRead(emailId, true);
break;
case 'mark-unread':
handleMarkAsRead(emailId, false);
break;
}
}
});
setSelectedEmails([]);
};
if (loading) {
return (
<div className="flex h-[calc(100vh-theme(spacing.12))] items-center justify-center bg-gray-100 mt-12">
@ -898,347 +969,82 @@ export default function MailPage() {
)}
{/* Email List */}
{filteredEmails.length > 0 ? (
<ul>
{filteredEmails.map(email => (
<li
key={email.id}
className={`border-b border-gray-100 cursor-pointer ${email.read ? 'bg-white/95' : 'bg-blue-50/95'} hover:bg-gray-50/95`}
onClick={() => handleEmailClick(email.id)}
>
<div className="p-4">
<div className="flex justify-between items-start mb-1">
<div className="flex items-center gap-3">
<Checkbox
checked={selectedEmails.includes(email.id)}
onClick={(e) => toggleEmailSelection(email.id, e)}
/>
<div className="flex items-center">
<div className={`w-2 h-2 rounded-full ${!email.read ? 'bg-blue-600' : 'bg-transparent'} mr-2`}></div>
<span className={`font-medium ${!email.read ? 'font-semibold' : ''} text-gray-900`}>{email.fromName}</span>
</div>
</div>
<div className="text-xs text-gray-500">{formatDate(email.date)}</div>
</div>
<div className="flex justify-between items-center mb-1">
<h3 className={`${!email.read ? 'font-semibold' : ''} text-gray-800`}>{email.subject}</h3>
<Button
variant="ghost"
size="sm"
className="text-gray-400 hover:text-yellow-500"
onClick={(e) => toggleStarred(email.id, e)}
>
<Star className="h-4 w-4" fill={email.starred ? 'currentColor' : 'none'} color={email.starred ? '#F59E0B' : 'currentColor'} />
</Button>
</div>
<p className="text-sm text-gray-600 truncate">
{decodeMimeContent(email.body)}
</p>
</div>
</li>
))}
</ul>
) : (
<div className="flex flex-col items-center justify-center h-64 text-gray-500">
<Mail className="h-12 w-12 mb-4 opacity-30" />
<p>No emails in this folder</p>
</div>
)}
</div>
{/* Email detail view */}
<div className="flex-1 overflow-y-auto bg-white">
{selectedEmail ? (
<div className="h-full flex flex-col">
{/* Email actions header */}
<div className="p-4 border-b border-gray-100 flex items-center justify-between">
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
className="text-gray-700 hover:bg-gray-100 hover:text-gray-900"
onClick={() => handleReply('reply')}
>
<Reply className="h-4 w-4 mr-2" />
Reply
</Button>
<Button
variant="ghost"
size="sm"
className="text-gray-700 hover:bg-gray-100 hover:text-gray-900"
onClick={() => handleReply('replyAll')}
>
<ReplyAll className="h-4 w-4 mr-2" />
Reply all
</Button>
<Button
variant="ghost"
size="sm"
className="text-gray-700 hover:bg-gray-100 hover:text-gray-900"
onClick={() => handleReply('forward')}
>
<Forward className="h-4 w-4 mr-2" />
Forward
</Button>
<div className="flex flex-col flex-1 overflow-hidden">
<div className="flex-1 overflow-auto">
{loading ? (
<div className="flex items-center justify-center h-full">
<div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-blue-500"></div>
<span className="ml-3 text-gray-600">Loading emails...</span>
</div>
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="icon"
className="text-gray-500 hover:text-gray-700"
onClick={() => setShowEmailActions(!showEmailActions)}
) : error ? (
<div className="flex flex-col items-center justify-center h-full">
<div className="text-red-500 mb-4">Error loading emails</div>
<button
onClick={() => loadEmails()}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
<MoreHorizontal className="h-4 w-4" />
</Button>
Try Again
</button>
</div>
</div>
{/* Email content */}
<div className="flex-1 p-6">
<div className="max-w-3xl mx-auto">
{getSelectedEmail() && (
<>
<div className="mb-6">
<div className="flex justify-between items-center mb-4">
<h1 className="text-xl font-bold">{getSelectedEmail()?.subject}</h1>
<Button
variant="ghost"
size="sm"
className="text-gray-400 hover:text-yellow-400"
onClick={(e) => getSelectedEmail() && toggleStarred(getSelectedEmail()!.id, e)}
>
<Star className="h-5 w-5" fill={getSelectedEmail()?.starred ? 'currentColor' : 'none'} />
</Button>
</div>
<div className="flex items-center">
<Avatar>
<AvatarFallback className={`${getAccountColor(getSelectedEmail()!.accountId)}`}>
{getSelectedEmail()?.fromName.charAt(0)}
</AvatarFallback>
</Avatar>
<div className="ml-3">
<div className="font-medium">{getSelectedEmail()?.fromName}</div>
<div className="text-sm text-gray-500 flex items-center">
<span>{getSelectedEmail()?.from}</span>
<span className="mx-2"></span>
<span>{new Date(getSelectedEmail()!.date).toLocaleString([], { dateStyle: 'medium', timeStyle: 'short' })}</span>
) : emails.length === 0 ? (
<div className="flex flex-col items-center justify-center h-full">
<div className="text-gray-500 mb-4">No emails found</div>
</div>
) : (
<ul className="divide-y divide-gray-200">
{filteredEmails.map((email) => (
<li
key={email.id}
className={`flex items-center p-4 hover:bg-gray-50 cursor-pointer ${
selectedEmail?.id === email.id ? 'bg-blue-50' : ''
}`}
onClick={() => handleEmailSelect(email)}
>
<div className="flex-1 min-w-0">
<div className="flex items-center justify-between">
<div className="flex items-center space-x-4">
<input
type="checkbox"
checked={selectedEmails.includes(email.id)}
onChange={(e) => handleEmailCheckbox(e, email.id)}
onClick={(e) => e.stopPropagation()}
className="h-4 w-4 text-blue-600"
/>
<div className="min-w-0">
<p className="text-sm font-medium text-gray-900 truncate">
{email.fromName || email.from}
</p>
<p className="text-sm text-gray-500 truncate">{email.subject}</p>
</div>
</div>
<div className="flex items-center space-x-2">
<span className="text-sm text-gray-500">
{formatDate(email.date.toISOString())}
</span>
<button
onClick={(e) => {
e.stopPropagation();
toggleStarred(email.id, e);
}}
className="text-gray-400 hover:text-yellow-400"
>
{email.starred ? (
<Star className="h-5 w-5 text-yellow-400" />
) : (
<Star className="h-5 w-5" />
)}
</button>
</div>
</div>
</div>
<div className="border-t border-gray-200 pt-6 prose max-w-none">
<p className="whitespace-pre-wrap">{decodeMimeContent(getSelectedEmail()?.body || '')}</p>
</div>
</>
)}
</div>
</div>
</li>
))}
</ul>
)}
</div>
) : (
<div className="h-full flex items-center justify-center">
<div className="text-center">
<Mail className="h-16 w-16 mx-auto mb-4 text-gray-300" />
<p className="text-gray-500">No email selected</p>
<p className="text-sm text-gray-400">Choose an email from the list to read its contents</p>
</div>
</div>
)}
</div>
</div>
</div>
{/* Compose email modal */}
{composeOpen && (
<div className="fixed inset-0 bg-black/25 backdrop-blur-sm flex items-center justify-center p-4 z-50">
<Card className="w-full max-w-2xl bg-white max-h-[90vh] flex flex-col">
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2 border-b">
<CardTitle className="text-xl">New Message</CardTitle>
<Button
variant="ghost"
size="icon"
className="text-gray-500 hover:text-gray-700"
onClick={() => setComposeOpen(false)}
>
<X className="h-4 w-4" />
</Button>
</CardHeader>
<CardContent className="space-y-3 overflow-y-auto flex-1 pt-2">
<div className="space-y-2 border-b border-gray-100 pb-3">
<div>
<Label className="text-sm text-gray-700 mb-0.5">From</Label>
<select className="w-full bg-white border border-gray-200 rounded-lg px-3 py-1.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent">
{accounts.map(account => (
<option key={account.id} value={account.id}>
{account.name} ({account.email})
</option>
))}
</select>
</div>
<div>
<div className="flex items-center justify-between mb-0.5">
<Label className="text-sm text-gray-700">To</Label>
<div className="flex items-center gap-2">
{!showCc && (
<Button
variant="ghost"
size="sm"
className="h-6 text-xs text-gray-500 hover:text-gray-700"
onClick={() => setShowCc(true)}
>
Add Cc
</Button>
)}
{!showBcc && (
<Button
variant="ghost"
size="sm"
className="h-6 text-xs text-gray-500 hover:text-gray-700"
onClick={() => setShowBcc(true)}
>
Add Bcc
</Button>
)}
</div>
</div>
<Input
type="email"
placeholder="email@example.com"
value={composeRecipient}
onChange={(e) => setComposeRecipient(e.target.value)}
className="bg-white border-gray-200 py-1.5"
/>
</div>
{showCc && (
<div>
<div className="flex items-center justify-between mb-0.5">
<Label className="text-sm text-gray-700">Cc</Label>
<Button
variant="ghost"
size="sm"
className="h-6 text-xs text-gray-500 hover:text-gray-700"
onClick={() => setShowCc(false)}
>
Remove
</Button>
</div>
<Input
type="email"
placeholder="cc@example.com"
className="bg-white border-gray-200 py-1.5"
/>
</div>
)}
{showBcc && (
<div>
<div className="flex items-center justify-between mb-0.5">
<Label className="text-sm text-gray-700">Bcc</Label>
<Button
variant="ghost"
size="sm"
className="h-6 text-xs text-gray-500 hover:text-gray-700"
onClick={() => setShowBcc(false)}
>
Remove
</Button>
</div>
<Input
type="email"
placeholder="bcc@example.com"
className="bg-white border-gray-200 py-1.5"
/>
</div>
)}
<div>
<Label className="text-sm text-gray-700 mb-0.5">Subject</Label>
<Input
type="text"
placeholder="Subject"
value={composeSubject}
onChange={(e) => setComposeSubject(e.target.value)}
className="bg-white border-gray-200 py-1.5"
/>
</div>
</div>
<div className="flex-1">
<Label className="text-sm text-gray-700 mb-0.5">Message</Label>
<Textarea
className="mt-0.5 h-[calc(100%-1.5rem)] min-h-[200px] bg-white border-gray-200 resize-none"
placeholder="Write your message here..."
value={composeContent}
onChange={(e) => setComposeContent(e.target.value)}
/>
</div>
{/* File Attachment Section */}
<div className="border-t border-gray-100 pt-3">
<div className="flex items-center gap-4">
<Button
variant="ghost"
size="sm"
className="border border-gray-200 text-blue-600 hover:bg-blue-50 hover:text-blue-700"
onClick={() => document.getElementById('file-upload')?.click()}
>
<Paperclip className="h-4 w-4 mr-2" />
Attach files
</Button>
<span className="text-xs text-gray-500">Maximum file size: 25 MB</span>
</div>
<input
type="file"
id="file-upload"
multiple
className="hidden"
onChange={(e) => {
// Handle file upload
console.log(e.target.files);
}}
/>
</div>
<div className="flex justify-end gap-3 pt-3 border-t border-gray-100">
<Button
variant="ghost"
className="border border-gray-200 text-blue-600 hover:bg-blue-50 hover:text-blue-700"
onClick={() => setComposeOpen(false)}
>
Cancel
</Button>
<Button
className="bg-blue-600 text-white hover:bg-blue-700"
onClick={() => setComposeOpen(false)}
>
Send
</Button>
</div>
</CardContent>
</Card>
</div>
)}
{/* Delete Confirmation Dialog */}
<AlertDialog open={showDeleteConfirm} onOpenChange={setShowDeleteConfirm}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you sure?</AlertDialogTitle>
<AlertDialogDescription>
{deleteType === 'email' && "This email will be moved to trash."}
{deleteType === 'emails' && `${selectedEmails.length} emails will be moved to trash.`}
{deleteType === 'account' && "This account will be permanently removed. This action cannot be undone."}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel onClick={() => setShowDeleteConfirm(false)}>Cancel</AlertDialogCancel>
<AlertDialogAction
className={deleteType === 'account' ? 'bg-red-600 hover:bg-red-700' : ''}
onClick={handleDeleteConfirm}
>
{deleteType === 'account' ? 'Delete Account' : 'Move to Trash'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}