Building an Automated AI Daily Brief: My Morning Workflow
A code-first guide to an AI daily brief: query a Notion data source with the current API version, ask an OpenAI model for a short plan, send it with smtplib and a Gmail app password, retry the flaky calls with tenacity, and schedule it all with GitHub Actions in your own time zone.

This guide shows you how to build an AI daily brief. A small Python script reads your open tasks from Notion, asks a model to pick what matters today, and emails you a short plan before you start work. It is for developers who want one email in the morning instead of five open tabs, and it runs on GitHub Actions, so there is no server to look after.
Key takeaways
- The brief is a plain pipeline, not an agent: fetch tasks, ask a model to rank them, send an email, on a schedule.
- Retry only the failures that can pass on a second try (rate limits, server errors, dropped connections), and let real bugs fail at once.
- GitHub Actions can run the script in your own time zone, and a failed run sends you a notification. A missing email is your cue to check the Actions tab.
Why I built a morning brief
My mornings used to start with a round of tabs: calendar, Notion, GitHub, chat. By the time I knew what to do, I had spent my best focus just finding the data. I wanted the information pushed to me instead.
So I built it. A single email waits in my inbox at 7:00 AM with a ranked view of my day. It runs on a GitHub Actions cron job, sends the email with Python's smtplib through Gmail, and retries flaky calls with the tenacity library. This post walks through that setup with the code brought up to date.
An AI daily brief is a scheduled email that collects your open tasks and asks a language model to turn them into a short, ranked plan for the day.
If you are unsure whether something like this needs an agent, read LLMs vs AI agents vs workflows first. The brief is a workflow: the same steps run in the same order every day.
How the pipeline fits together
The script runs five steps from top to bottom:
- Ingest: query a Notion data source for tasks that are not done.
- Clean: keep only the name, due date and priority of each task.
- Reason: send that list to a model with a prompt that asks for a ranked plan.
- Deliver: email the plan as plain text over SMTP.
- Schedule: run the whole thing from a GitHub Actions workflow.
There is no database and no state between runs. If a run fails, the next one starts clean.
Set up Notion
Notion's API reads only what you share with it. Before you write code, do three things:
- Create an internal connection in Notion's developer portal and copy its API token. Notion's authorization guide notes that you must be a workspace owner to create one.
- Open your tasks database, click the ••• menu, choose Add connections and pick your connection. Until you do this, API requests for that page return an error.
- Copy the database's data source ID. Since API version
2025-09-03, Notion queries and new pages target a data source, not the database itself. You can copy the ID from the database settings under Manage data sources.
The code below assumes a data source with a Name title, a Status property of type status, a Due Date date and a Priority select.
Step 1: Fetch open tasks with retries
Create a folder with a requirements.txt that pins the packages:
openai==3.41.0
requests==2.34.2
tenacity==9.2.1
Then start brief.py with the imports and the Notion query:
import json
import os
import smtplib
import ssl
from datetime import date
from email.message import EmailMessage
import requests
from openai import OpenAI
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential
NOTION_VERSION = "2026-03-11"
class TransientError(Exception):
"""A failure worth retrying: rate limits and server errors."""
@retry(
stop=stop_after_attempt(4),
wait=wait_exponential(multiplier=2, max=60),
retry=retry_if_exception_type((TransientError, requests.ConnectionError, requests.Timeout)),
reraise=True,
)
def query_tasks_page(cursor=None):
url = f"https://api.notion.com/v1/data_sources/{os.environ['NOTION_DATA_SOURCE_ID']}/query"
headers = {
"Authorization": f"Bearer {os.environ['NOTION_TOKEN']}",
"Notion-Version": NOTION_VERSION,
"Content-Type": "application/json",
}
body = {"filter": {"property": "Status", "status": {"does_not_equal": "Done"}}, "page_size": 100}
if cursor:
body["start_cursor"] = cursor
response = requests.post(url, headers=headers, json=body, timeout=30)
if response.status_code == 429 or response.status_code >= 500:
raise TransientError(f"Notion returned {response.status_code}")
response.raise_for_status() # a 400, 401 or 404 is a bug in your setup, so fail at once
return response.json()
Checked against openai@3.41.0, requests@2.34.2 and tenacity@9.2.1 (Python 3.13), 2026-10-29.
A few details matter here:
- The version header.
2026-03-11is the newest version on Notion's versioning page today. Pin it, so Notion's changes don't reach your script until you choose to upgrade. - The endpoint. Queries go to
/v1/data_sources/{id}/query. The older/v1/databases/{id}/querycall fails for any database that gains a second data source, according to Notion's upgrade guide. - The filter. If your
Statuscolumn is a select property and not a status property, change the key"status"to"select". - The retries.
reraise=Truemakes tenacity raise your original error after the last attempt, not aRetryError, so the traceback ends where the problem is.
Notion's request limits page says a rate-limited response carries a Retry-After header in seconds. For one query a day, the backoff above is plenty. For bulk jobs, read that header and wait that long.
Step 2: Turn pages into a clean task list
Notion returns each page with every property in a nested shape. Pull out only what the model needs, and handle empty fields, because a task with no due date returns null:
def to_task(page):
props = page["properties"]
due = props["Due Date"]["date"]
priority = props["Priority"]["select"]
return {
"task": "".join(part["plain_text"] for part in props["Name"]["title"]) or "(untitled)",
"due": due["start"] if due else None,
"priority": priority["name"] if priority else None,
}
def fetch_active_tasks():
tasks, cursor = [], None
while True:
data = query_tasks_page(cursor)
tasks += [to_task(page) for page in data["results"]]
if not data["has_more"]:
return tasks
cursor = data["next_cursor"]
The loop follows has_more and next_cursor, so a long task list doesn't stop at the first page. Joining every plain_text part keeps titles that contain links or formatting intact.
Step 3: Ask the model for a ranked plan
The model's job is judgment: which task comes first, and which ones clash with a busy day. The prompt asks for plain text and forbids invented tasks, because the brief is only useful if every line traces back to Notion.
SYSTEM_PROMPT = """You are an executive assistant for a software developer.
You get today's date and a JSON list of open tasks. Write a plain-text daily brief:
1. THE ONE THING: the single most important task today, with one line on why.
2. ACTION LIST: the other tasks, grouped into Deep work and Admin.
3. WATCH OUT: tasks that are overdue or due today.
Use only the tasks you are given. Do not invent tasks or dates. No HTML."""
def generate_briefing(tasks):
client = OpenAI() # reads OPENAI_API_KEY; the SDK retries rate limits and server errors itself
response = client.responses.create(
model=os.environ.get("BRIEF_MODEL", "gpt-6-luna"),
instructions=SYSTEM_PROMPT,
input=json.dumps({"date": date.today().strftime("%A, %d %B %Y"), "tasks": tasks}),
)
return response.output_text
On the date above, OpenAI's models page lists gpt-6-luna as its most efficient model for cost-sensitive, high-volume tasks, and gpt-6-astra as the most capable. Ranking a short task list is a small job, so start with the cheaper one. Model ids change often, so check that page and set BRIEF_MODEL to switch without editing code.
The client is created inside the function on purpose. OpenAI() raises an error when no API key is set, so building it at import time would break any test that imports the file.
Step 4: Send the email over SMTP
Email works well as the delivery channel: it is already open in the morning, it is searchable, and it needs no new app.
@retry(
stop=stop_after_attempt(3),
wait=wait_exponential(multiplier=5, max=60),
retry=retry_if_exception_type((smtplib.SMTPConnectError, smtplib.SMTPServerDisconnected, TimeoutError)),
reraise=True,
)
def send_email(brief_text):
msg = EmailMessage()
msg["Subject"] = f"Daily brief: {date.today():%Y-%m-%d}"
msg["From"] = os.environ["EMAIL_USER"]
msg["To"] = os.environ["EMAIL_TARGET"]
msg.set_content(brief_text) # plain text: nothing the model writes is rendered as HTML
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context, timeout=30) as server:
server.login(os.environ["EMAIL_USER"], os.environ["EMAIL_PASS"])
server.send_message(msg)
Google's Workspace help lists smtp.gmail.com on port 465 for SSL, signed in with an app password. For a personal Gmail account, Google's app password page says you need 2-Step Verification turned on first. App passwords aren't available for work or school accounts, accounts with Advanced Protection, or accounts that use only security keys for 2-Step Verification. Store the app password as a secret, never in the file.
One trade-off in the retry list: SMTPServerDisconnected can also happen after Gmail has accepted the message, so a retry may now and then send the brief twice. For a daily note to yourself, a rare duplicate beats a missing brief.
Send plain text, not model-written HTML
The earlier version of this script asked the model for HTML and sent it as is. Task titles come from Notion, and anything in them ends up in the prompt, so the model's output is not fully under your control. msg.set_content(brief_text) sends plain text, which a mail client shows as text and never renders.
Finish the file with an entry point:
def main():
tasks = fetch_active_tasks()
send_email(generate_briefing(tasks))
print(f"Brief sent with {len(tasks)} open tasks.")
if __name__ == "__main__":
main()
Because the work starts only under if __name__ == "__main__":, you can import brief.py in a test without any keys.
Test the parsing without any keys
The part most likely to break is the mapping from Notion's JSON to your task list. Test it with a hand-written page, before you spend an API call:
from brief import to_task
page = {
"properties": {
"Name": {"title": [{"plain_text": "Ship "}, {"plain_text": "invoice export"}]},
"Due Date": {"date": {"start": "2026-10-30"}},
"Priority": {"select": None},
}
}
assert to_task(page) == {"task": "Ship invoice export", "due": "2026-10-30", "priority": None}
print("parsing works")
Save it as test_brief.py next to brief.py and run python test_brief.py. If you rename a column in Notion, update this test and to_task together.
Where the retries live
Each outside call fails in its own way, so each gets its own policy:
| Call | Who retries | What is retried | Why |
|---|---|---|---|
| Notion query | tenacity in query_tasks_page |
429, 5xx, connection errors, timeouts | A 400 or 401 means your setup is wrong, and retrying won't fix it |
| OpenAI request | The openai SDK |
Connection errors, 408, 409, 429 and 5xx, 2 retries by default (per its README) | Built in, so adding tenacity on top would multiply the attempts |
| Gmail SMTP | tenacity in send_email |
Connect errors, dropped connections, timeouts | A wrong app password raises SMTPAuthenticationError and fails at once |
As a rule of thumb, retry a call only when the same request could succeed a minute later.
Step 5: Schedule it with GitHub Actions
GitHub Actions starts a fresh runner, installs your packages, runs the script and shuts down. Save this as .github/workflows/daily-brief.yml:
name: Daily brief
on:
schedule:
- cron: "45 6 * * *"
timezone: "Asia/Kolkata" # replace with your own IANA time zone
workflow_dispatch: # lets you run it by hand from the Actions tab
jobs:
brief:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
- run: pip install -r requirements.txt
- run: python brief.py
env:
NOTION_TOKEN: ${{ secrets.NOTION_TOKEN }}
NOTION_DATA_SOURCE_ID: ${{ secrets.NOTION_DATA_SOURCE_ID }}
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
EMAIL_USER: ${{ secrets.EMAIL_USER }}
EMAIL_PASS: ${{ secrets.EMAIL_PASS }}
EMAIL_TARGET: ${{ secrets.EMAIL_TARGET }}
Add each value under Settings > Secrets and variables > Actions in your repository. Then push, open the Actions tab and use Run workflow to test it once by hand.
GitHub's docs explain the scheduling details that shape this file:
- Time zone. Schedules run in UTC unless you add
timezonewith an IANA name. With it, you don't have to shift the cron by hand when daylight saving time changes. - Delays. The
scheduleevent can be delayed when load is high, and GitHub names the start of every hour as a busy time. Under very high load, GitHub says some queued jobs may be dropped. Starting at 6:45 gives the run a margin before 7:00. - Default branch. Scheduled workflows run only on the default branch. The
workflow_dispatchtrigger behind the Run workflow button also needs the workflow file on the default branch. - Inactivity. In a public repository, scheduled workflows are disabled after 60 days with no repository activity. A private repository for your brief avoids that, and it keeps your workflow file out of public view.
Know when it fails
Scripts fail and APIs time out. Two things keep that visible:
- Retries in code cover the short blips, as described above.
- Run notifications cover the rest. When a run fails, the script exits with an error, and GitHub notifies the user who created the scheduled workflow.
That makes the email itself a simple health check. If the brief isn't in your inbox, open the Actions tab. A failed run has a log to read. If there is no run at all, the schedule was delayed or dropped, and Run workflow sends the brief by hand.
Ideas for the next version
- Add your calendar. Fetch today's events the same way and pass them in the same JSON, so the model can see that four hours of meetings leave little room for deep work.
- Write back. Store the chosen "one thing" in Notion, so you can review your mornings later. The Notion writeback guide shows how to create pages from Python.
- Prefer no code? The same flow works in n8n. The AI planning agent tutorial for n8n builds a planner there.
Frequently asked questions
Do I need a server to run a daily AI email?
No. A GitHub Actions scheduled workflow starts a runner, runs your script and stops. You keep the code and the secrets in one repository, and there is nothing to patch or keep running between briefs.
Why does my scheduled GitHub Action run late?
GitHub's docs say the schedule event can be delayed during high load, and the start of every hour is a busy time. Schedule the run a little before the time you need the email, and avoid minute zero.
Can I use my normal Gmail password with smtplib?
Use an app password instead. Google's help page says app passwords need 2-Step Verification, and they aren't available for work or school accounts. Changing your Google password revokes them, so plan to create a new one when you do.
Which Notion endpoint do I use to read a database today?
Query the data source: POST /v1/data_sources/{data_source_id}/query, with a pinned Notion-Version header. Notion moved queries from databases to data sources in API version 2025-09-03, and the old database query fails once a database has more than one data source.
Why plain text and not HTML in the email?
The model writes the brief from your task titles, so its output is not fully under your control. Plain text shows exactly what the model wrote and never renders markup. If you want formatting later, build the HTML yourself from structured data, and escape every value the model returns.
Sources
Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.
- Notion API: Versioning
- Notion API: Upgrading to version 2025-09-03 (data sources)
- Notion API: Query a data source
- Notion API: Request limits
- Notion API: Authorization (internal connections)
- OpenAI API: Models
- OpenAI API: Developer quickstart (Responses API)
- openai-python on GitHub (retries and timeouts)
- Python docs: smtplib
- Google Account Help: Sign in with app passwords
- Google Workspace Admin Help: Send email from a printer, scanner, or app
- Tenacity documentation
- GitHub Docs: Events that trigger workflows (schedule)
- GitHub Docs: Workflow syntax (on.schedule and timezone)
- GitHub Docs: Using secrets in GitHub Actions
- GitHub Docs: Notifications for workflow runs



Comments
Loading comments...