This guide helps you set up the Email Agent with secure Microsoft OAuth authentication, enabling users to access their own emails without administrator access to all email accounts.
- Microsoft 365 account
- Azure account with permissions to register apps
- OpenAI API key
-
Clone the repository:
git clone https://github.com/yourusername/email-agent-workshop.git cd email-agent-workshop
-
Install dependencies:
npm install
-
Create a
.env
file based on.env.example
:# SQLite SQLITE_DB_PATH=./data/email_agent.db # OpenAI OPENAI_API_KEY=your_openai_api_key # Microsoft Graph API (OAuth) AZURE_CLIENT_ID=your_client_id AZURE_TENANT_ID=your_tenant_id AZURE_REDIRECT_URI=http://localhost:3000/api/auth/callback # Webhook WEBHOOK_SECRET=some-random-string
- Go to the Azure Portal
- Navigate to Azure Active Directory > App registrations > New registration
- Enter a name for your application (e.g., "Email Agent")
- Under "Supported account types", select "Accounts in this organizational directory only"
- Under "Redirect URI", select "Web" and enter:
http://localhost:3000/api/auth/callback
- Click "Register"
- On the app overview page, note these values:
- Application (client) ID - copy to AZURE_CLIENT_ID in .env
- Directory (tenant) ID - copy to AZURE_TENANT_ID in .env
- In your app registration, go to "API permissions"
- Click "Add a permission"
- Select "Microsoft Graph" > "Delegated permissions"
- Add the following permissions:
- Mail.Read (under Mail category)
- Mail.ReadBasic (under Mail category)
- User.Read (under User category)
- Click "Add permissions"
- For testing, you can click "Grant admin consent for [your organization]"
- This pre-approves the permissions for all users in your organization
- Without this, each user will need to consent when they first sign in
- In your app registration, go to "Authentication"
- Under "Implicit grant and hybrid flows", enable:
- Access tokens
- ID tokens
- Under "Advanced settings", set "Allow public client flows" to Yes
- Click "Save"
-
Start the development server:
npm run dev
-
Open your browser and navigate to
http://localhost:3000
-
Click "Sign in with Microsoft" to authenticate with your Microsoft 365 account
-
After signing in, click the sync button to fetch emails from your mailbox
- Each user signs in with their own Microsoft 365 account
- Users can only access their own emails (enforced by Microsoft's OAuth)
- Emails are processed with OpenAI and stored only in the local SQLite database
- The app never has access to emails beyond what the logged-in user can access
- If you can't sign in, verify your Azure app registration settings
- If permission errors occur, check that you've added the correct delegated permissions
- For database issues, check that the SQLite database path is correctly set and writable