Skip to content

feat: add mailto protocol handler support#574

Merged
MrgSub merged 2 commits intoMail-0:stagingfrom
jlokos:feature/mailto-protocol-handler
Apr 4, 2025
Merged

feat: add mailto protocol handler support#574
MrgSub merged 2 commits intoMail-0:stagingfrom
jlokos:feature/mailto-protocol-handler

Conversation

@jlokos
Copy link
Contributor

@jlokos jlokos commented Apr 4, 2025

feat: add mailto protocol handler support

Description

This PR adds support for handling mailto protocol links in the 0.email application. When users click on mailto links in their browser, they can now choose to open them in 0.email. This implementation follows web standards for protocol handlers and provides a seamless experience when creating emails from external applications or websites.

Key features implemented:

  • Protocol handler registration for mailto: links
  • Parsing of mailto URLs to extract recipient email, subject, and body
  • Automatic creation of draft emails from mailto data
  • Updated compose page to accept initial values for new emails
  • Code refactoring to improve maintainability and reusability

Type of Change

  • ✨ New feature (non-breaking change which adds functionality)
  • 🎨 UI/UX improvement

Areas Affected

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience
  • API Endpoints

Testing Done

  • Manual testing performed
  • Cross-browser testing (if UI changes)

I've tested this implementation across multiple browsers and confirmed the protocol handler registration works correctly. The feature has been tested with various mailto link formats including:

Security Considerations

  • No sensitive data is exposed
  • Input validation is implemented

The implementation includes robust validation and sanitization of inputs from mailto URLs to prevent security issues. Email addresses are validated using regex patterns, and all mailto parameters are properly decoded and sanitized before use.

Checklist

  • I have read the CONTRIBUTING document
  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in complex areas
  • My changes generate no new warnings

Additional Notes

The implementation follows best practices for handling web protocols and maintains the existing UX patterns of the application. Code has been refactored to improve maintainability and reuse common functions across components.

Changes include:

  1. Extracting common utility functions (isValidEmail, createEmptyDocContent)
  2. Adding props to the CreateEmail component to support initial values
  3. Creating a dedicated handler for mailto links
  4. Registering the protocol handler in the mail layout component

By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.

Summary by CodeRabbit

  • New Features
    • Added enhanced mailto link handling that parses email details to automatically create draft emails.
    • Updated the compose interface to pre-fill fields with relevant data from URL parameters.
    • Improved email validation and default content setup in the email composition process.
    • Integrated browser support for registering a mailto protocol handler for seamless redirection.

@vercel
Copy link

vercel bot commented Apr 4, 2025

@jlokos is attempting to deploy a commit to the Zero Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 4, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces mailto URL handling into the mail application. A new route processes mailto links by parsing URL parameters, creating email drafts, and managing user authentication with appropriate redirection. A new React compose page component handles mailto parameters by either redirecting to a dedicated handler or initializing the email creation form with provided values. The CreateEmail component is enhanced with email validation and default content generation utilities. Additionally, a protocol handler is registered in the MailLayout for browser-level mailto redirection.

Changes

File(s) Change Summary
apps/mail/app/.../compose/handle-mailto/route.ts
apps/mail/app/.../compose/page.tsx
Introduced new endpoints for handling mailto URLs: a backend route for parsing URLs, creating drafts, and redirecting users based on authentication and parsing results, and a React compose page that checks search parameters for mailto links and redirects or renders the email creation form.
apps/mail/components/…/create/create-email.tsx Enhanced the CreateEmail component by accepting initial values, adding utility functions for email validation (isValidEmail) and default document content (createEmptyDocContent), and updating state initialization with error handling for draft content.
apps/mail/components/…/mail/mail.tsx Added a useEffect hook to register a mailto protocol handler in the MailLayout. This handler allows browsers to redirect mailto links to the compose page after parsing email parameters, with error logging if registration fails.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MailRoute
    participant AuthService
    participant Parser
    participant DraftService

    User->>MailRoute: Send mailto request
    MailRoute->>AuthService: Check authentication
    alt Not Authenticated
        AuthService-->>MailRoute: Authentication failed
        MailRoute-->>User: Redirect to login page
    else Authenticated
        MailRoute->>Parser: parseMailtoUrl(mailto)
        alt Parsing fails
            Parser-->>MailRoute: null
            MailRoute-->>User: Redirect to empty compose page
        else Parsing succeeds
            MailRoute->>DraftService: createDraftFromMailto(parsedData)
            DraftService-->>MailRoute: Draft ID or error
            alt Draft creation succeeds
                MailRoute-->>User: Redirect to compose page with draftId
            else Draft creation fails
                MailRoute-->>User: Redirect to empty compose page
            end
        end
    end
Loading
sequenceDiagram
    participant User
    participant ComposePage
    participant AuthService
    participant MailtoHandler
    participant CreateEmail

    User->>ComposePage: Access compose page with searchParams
    ComposePage->>AuthService: Verify session
    alt Session invalid
        AuthService-->>ComposePage: Session invalid
        ComposePage-->>User: Redirect to login
    else Session valid
        ComposePage-->>ComposePage: Await searchParams
        alt searchParams.to starts with "mailto:"
            ComposePage-->>MailtoHandler: Redirect to mailto handler with encoded `to`
        else
            ComposePage-->>CreateEmail: Render component with initial values
        end
    end
Loading
sequenceDiagram
    participant MailLayout
    participant Browser

    MailLayout->>Browser: Check registerProtocolHandler support
    alt Supported
        Browser-->>MailLayout: Supported
        MailLayout-->>Browser: Register mailto handler (redirect to compose)
    else Not Supported
        MailLayout-->>Browser: Log error / Skip registration
    end
Loading

Possibly related PRs

  • Draft emails #390: The changes in the main PR, which focus on implementing mailto URL handling and creating email drafts, are related to the retrieved PR as both involve functionalities for managing email drafts, specifically through the createDraft function in the retrieved PR that aligns with the draft creation process in the main PR.
  • feat: add mailto protocol handler support #574: The changes in the main PR are directly related to those in the retrieved PR as both implement functionality for handling mailto URLs, including parsing and creating drafts, specifically in the same file route.ts.

Suggested reviewers

  • ahmetskilinc

Poem

Hop along the code, sharp and neat,
Mailto links now take a joyful beat.
Parsing and drafting with a merry spin,
Our email paths are set to begin!
With every hop, our code shines bright 🐇✨
CodeRabbit leaps through day and night.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f2eb74f and cd7d929.

📒 Files selected for processing (1)
  • apps/mail/components/mail/mail.tsx (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (9)
apps/mail/components/mail/mail.tsx (1)

278-299: Consider verifying secure contexts for protocol registration.

The mailto protocol handler registration looks functional. However, navigator.registerProtocolHandler requires a secure context (HTTPS) in most browsers. Consider verifying or documenting that this code path is only invoked over HTTPS to avoid potential registration failures on non-secure environments.

apps/mail/app/(routes)/mail/compose/page.tsx (2)

6-14: Extend interface for additional mailto properties if needed.

If you intend to handle cc, bcc, or multiple recipients in the future, consider extending the interface to capture those fields.


16-46: Sanitize user input for safe rendering.

While the redirect to /mail/compose/handle-mailto filters out mailto URLs, other query fields such as subject and body could contain characters requiring sanitization or encoding. Consider ensuring that the input is sanitized before rendering, especially if eventually displayed in the UI without HTML encoding.

apps/mail/app/(routes)/mail/compose/handle-mailto/route.ts (3)

5-79: Consider more robust email parsing or multiple addressees.

The current parseMailtoUrl function handles a single email with a straightforward regex pattern. For broader mailto use cases (multiple addresses, “cc”/“bcc” fields, subdomains, plus signs, etc.), consider a more robust email parser or additional parameter handling.


81-127: Escape user-supplied content to prevent unexpected HTML injection.

When constructing HTML content, body text is inserted directly without escaping. Although this is for an email draft, untrusted input might contain HTML or scripting elements. Consider escaping <, >, &, etc., to prevent possible code injection in upstream or downstream usage.


129-162: Support additional mailto parameters.

This handler redirects only after extracting basic fields. If future requirements include multiple recipients, cc, or bcc parameters, extend both the parser and the draft-creation logic accordingly.

apps/mail/components/create/create-email.tsx (3)

284-316: Consider consolidating initialization logic.

There's duplication between the useState initializers and this useEffect. The component initializes email/subject/body values in two places: during useState initialization and in this useEffect.

Consider consolidating the initialization logic to avoid potential inconsistencies. Either:

  1. Use null/empty defaults in useState and do all initialization in useEffect, or
  2. Handle all initialization in useState and use the useEffect only for processing that depends on multiple state values
- const [toEmails, setToEmails] = React.useState<string[]>(initialTo ? [initialTo] : []);
- const [subjectInput, setSubjectInput] = React.useState(initialSubject);
- const [messageContent, setMessageContent] = React.useState(initialBody);
+ const [toEmails, setToEmails] = React.useState<string[]>([]);
+ const [subjectInput, setSubjectInput] = React.useState('');
+ const [messageContent, setMessageContent] = React.useState('');

  React.useEffect(() => {
    // Initialize all state from props here
    // ...existing code...
-  }, [initialTo, initialSubject, initialBody, defaultValue]);
+  }, [initialTo, initialSubject, initialBody]);

299-315: Simplify document creation using utility function.

You've created a nice utility function for empty document creation but aren't using it consistently here.

  if (initialBody && !defaultValue) {
-    setDefaultValue({
-      type: 'doc',
-      content: [
-        {
-          type: 'paragraph',
-          content: [
-            {
-              type: 'text',
-              text: initialBody
-            }
-          ]
-        }
-      ]
-    });
+    try {
+      const json = generateJSON(initialBody, [Document, Paragraph, Text, Bold]);
+      setDefaultValue(json);
+    } catch (error) {
+      console.error('Error parsing initial body in useEffect:', error);
+      // Create document with plain text fallback
+      const doc = createEmptyDocContent();
+      if (doc.content && doc.content.length > 0) {
+        doc.content[0].content = [{ type: 'text', text: initialBody }];
+      }
+      setDefaultValue(doc);
+    }
     setMessageContent(initialBody);
  }

285-293: Handle multiple recipient addresses correctly.

The email handling for mailto links works properly but could be improved to handle multiple recipients more elegantly.

  if (initialTo) {
    const emails = initialTo.split(',').map(email => email.trim());
    const validEmails = emails.filter(email => isValidEmail(email));
    if (validEmails.length > 0) {
      setToEmails(validEmails);
-    } else {
+    } 
+    
+    // If we have any invalid emails, put them in the input field for the user to correct
+    const invalidEmails = emails.filter(email => !isValidEmail(email));
+    if (invalidEmails.length > 0) {
-      setToInput(initialTo);
+      setToInput(invalidEmails.join(', '));
    }
  }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cc919e4 and f2eb74f.

📒 Files selected for processing (4)
  • apps/mail/app/(routes)/mail/compose/handle-mailto/route.ts (1 hunks)
  • apps/mail/app/(routes)/mail/compose/page.tsx (1 hunks)
  • apps/mail/components/create/create-email.tsx (4 hunks)
  • apps/mail/components/mail/mail.tsx (1 hunks)
🧰 Additional context used
🧬 Code Definitions (1)
apps/mail/app/(routes)/mail/compose/page.tsx (1)
apps/mail/components/create/create-email.tsx (1)
  • CreateEmail (40-516)
🔇 Additional comments (6)
apps/mail/app/(routes)/mail/compose/page.tsx (1)

1-5: Imports look good.
No concerns here—clean setup and consistent with project structure.

apps/mail/components/create/create-email.tsx (5)

25-28: Good email validation implementation.

The email validation function uses a standard regex pattern that properly checks for basic email format requirements.


30-38: Good refactoring of document creation.

Extracting this repeated document structure into a utility function improves maintainability and reduces duplication across the codebase.


40-48: Nice enhancement to support mailto parameters.

The component signature has been properly updated to support the mailto protocol parameters, with appropriate default values and TypeScript typing.


50-57: Initial state values setup correctly.

State initialization now properly uses the provided props, enabling pre-populated email forms from mailto links.


60-70: Good defensive programming for initialBody parsing.

The code properly attempts to parse the initialBody with appropriate error handling and fallback to an empty document when parsing fails.

@vercel
Copy link

vercel bot commented Apr 4, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
0 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 4, 2025 8:05pm

Copy link
Collaborator

@MrgSub MrgSub left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thank you

@MrgSub MrgSub merged commit b431d2d into Mail-0:staging Apr 4, 2025
0 of 2 checks passed
jlokos added a commit to jlokos/Zero that referenced this pull request Apr 15, 2025
Implements proper handling of CC and BCC fields in mailto links, including:
- Parsing CC and BCC values from mailto URLs
- Adding CC and BCC headers to MIME messages when creating drafts
- Extracting CC and BCC values from draft headers
- Validating and sanitizing email addresses
- Updating UI to display CC and BCC fields when values are present

Enhances the existing mailto protocol handler support from PR Mail-0#574
@coderabbitai coderabbitai bot mentioned this pull request Apr 16, 2025
jlokos added a commit to jlokos/Zero that referenced this pull request Apr 25, 2025
Implements proper handling of CC and BCC fields in mailto links, including:
- Parsing CC and BCC values from mailto URLs
- Adding CC and BCC headers to MIME messages when creating drafts
- Extracting CC and BCC values from draft headers
- Validating and sanitizing email addresses
- Updating UI to display CC and BCC fields when values are present

Enhances the existing mailto protocol handler support from PR Mail-0#574
@coderabbitai coderabbitai bot mentioned this pull request May 1, 2025
30 tasks
@coderabbitai coderabbitai bot mentioned this pull request Aug 10, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants