// guides

Hacker News daily digest by email, filtered by your keywords (free script, tested)

A morning email with yesterday's Hacker News stories that match your keywords, plus anything big. One free Python file, standard library only, no API key, works with Gmail or any SMTP. Tested on live data.

Updated 2026-10-22 · about 10 minutes

Rather not set it up yourself? Describe your task in one sentence and we'll build and test it for you, free →

Steps

  1. Pick your keywords and a points bar

    Write down 3 to 8 words you actually care about, for example n8n, self-hosted, postgres, rust. The script includes a story when its title or link contains one of them as a whole word and it has at least 5 points, plus any story with 100 points or more. Avoid very broad words: in our test, adding ai made all 30 slots fill with AI stories and pushed everything else out.

  2. Save the script

    Save the code below as hn_digest.py (or download hn_digest.py). It uses only the Python standard library, so there is nothing to pip install. It reads stories from the free public Hacker News search API at hn.algolia.com, which needs no key.

  3. Try it without sending anything

    Run it in dry-run mode. It prints the email instead of sending it and doesn't remember anything, so you can tune your keywords freely:

    HN_KEYWORDS="n8n,python,self-hosted,llm" python3 hn_digest.py --dry-run

    The first line is the subject, for example Hacker News digest: 30 stories (7 match your keywords). Keyword matches come first, then the biggest stories by points.

  4. Add your email login

    Set the SMTP settings for the account that sends the digest. For Gmail, create an app password (Google Account → Security → 2-Step Verification → App passwords) and use it instead of your normal password:

    export SMTP_HOST=smtp.gmail.com SMTP_PORT=465
    export SMTP_USER=you@gmail.com SMTP_PASSWORD='your app password'
    export SMTP_FROM=you@gmail.com SMTP_TO=you@gmail.com
    export HN_KEYWORDS="n8n,python,self-hosted,llm"
    python3 hn_digest.py

    Port 465 uses SSL from the start. For port 587 the script switches to STARTTLS. It prints Sent: ... when the mail went out.

  5. Run it every morning

    Put the exports in a small shell file, then add one cron line (crontab -e) so it runs at 7:00:

    0 7 * * * . $HOME/hn.env && /usr/bin/python3 $HOME/hn_digest.py >> $HOME/hn_digest.log 2>&1

    No always-on computer? Any small VPS or a Raspberry Pi works, and our guide to running a Python script on a schedule covers the other options.

The script

#!/usr/bin/env python3
"""Hacker News daily digest by email. Standard library only. MIT licence.
Emails you yesterday's Hacker News stories that match your keywords or pass a points threshold.
Settings come from environment variables (see the guide at tasktoagent.com/guides/hacker-news-daily-digest-email/)."""
import os, re, sys, json, time, html, smtplib, ssl, urllib.parse, urllib.request
from email.message import EmailMessage

KEYWORDS = [k.strip().lower() for k in os.getenv("HN_KEYWORDS", "").split(",") if k.strip()]
MIN_POINTS = int(os.getenv("HN_MIN_POINTS", "100"))       # stories with this many points are always included
KW_MIN_POINTS = int(os.getenv("HN_KW_MIN_POINTS", "5"))   # keyword matches need at least this many points
HOURS = int(os.getenv("HN_HOURS", "24"))
MAX_ITEMS = int(os.getenv("HN_MAX_ITEMS", "30"))
SEEN_FILE = os.getenv("HN_SEEN_FILE", os.path.expanduser("~/.hn_digest_seen.json"))
API = os.getenv("HN_API", "https://hn.algolia.com/api/v1/search_by_date")

def fetch(since):
    hits, page = [], 0
    while page < 10:
        q = urllib.parse.urlencode({"tags": "story", "numericFilters": f"created_at_i>{since},points>={min(MIN_POINTS, KW_MIN_POINTS)}",
                                    "hitsPerPage": 1000, "page": page})
        req = urllib.request.Request(f"{API}?{q}", headers={"User-Agent": "hn-digest/1.0 (+tasktoagent.com)"})
        for attempt in range(3):
            try:
                with urllib.request.urlopen(req, timeout=20) as r:
                    data = json.load(r); break
            except Exception as e:
                if attempt == 2: raise SystemExit(f"Hacker News API failed: {e}")
                time.sleep(5 * (attempt + 1))
        hits += data.get("hits", [])
        page += 1
        if page >= data.get("nbPages", 0): break
    return hits

def matches(h):
    text = (h.get("title") or "").lower() + " " + (h.get("url") or "").lower()
    # whole words only, so "ai" doesn't match "email" and "go" doesn't match "google"
    return [k for k in KEYWORDS if re.search(r"(?<![a-z0-9])" + re.escape(k) + r"(?![a-z0-9])", text)]

def pick(hits, seen):
    out = []
    for h in hits:
        if h["objectID"] in seen: continue
        kw = matches(h); pts = h.get("points") or 0
        if pts >= MIN_POINTS or (kw and pts >= KW_MIN_POINTS):
            h["_kw"] = kw; out.append(h)
    out.sort(key=lambda h: (not h["_kw"], -(h.get("points") or 0)))
    return out[:MAX_ITEMS]

def render(items):
    txt, rows = [], []
    for h in items:
        link = h.get("url") or f"https://news.ycombinator.com/item?id={h['objectID']}"
        disc = f"https://news.ycombinator.com/item?id={h['objectID']}"
        tag = f" [{', '.join(h['_kw'])}]" if h["_kw"] else ""
        meta = f"{h.get('points',0)} points, {h.get('num_comments') or 0} comments"
        txt.append(f"- {h['title']}{tag}\n  {link}\n  {meta}: {disc}")
        rows.append(f'<li><a href="{html.escape(link)}">{html.escape(h["title"])}</a>{html.escape(tag)}<br>'
                    f'<small>{meta} · <a href="{disc}">discussion</a></small></li>')
    return "\n".join(txt), "<ol>" + "".join(rows) + "</ol>"

def send(subject, txt, htm):
    msg = EmailMessage()
    msg["Subject"], msg["From"], msg["To"] = subject, os.environ["SMTP_FROM"], os.environ["SMTP_TO"]
    msg.set_content(txt); msg.add_alternative(f"<html><body>{htm}</body></html>", subtype="html")
    host, port = os.environ["SMTP_HOST"], int(os.getenv("SMTP_PORT", "465"))
    user, pw = os.getenv("SMTP_USER"), os.getenv("SMTP_PASSWORD")
    if port == 465:
        s = smtplib.SMTP_SSL(host, port, context=ssl.create_default_context(), timeout=30)
    else:
        s = smtplib.SMTP(host, port, timeout=30)
        if os.getenv("SMTP_STARTTLS", "1") == "1": s.starttls(context=ssl.create_default_context())
    with s:
        if user: s.login(user, pw)
        s.send_message(msg)

def main():
    dry = "--dry-run" in sys.argv
    seen = {}
    if os.path.exists(SEEN_FILE):
        seen = json.load(open(SEEN_FILE))
    cutoff = time.time() - 7 * 86400
    seen = {k: v for k, v in seen.items() if v > cutoff}
    items = pick(fetch(int(time.time()) - HOURS * 3600), seen)
    if not items:
        print("Nothing new today; no email sent."); return
    txt, htm = render(items)
    subject = f"Hacker News digest: {len(items)} stories" + (f" ({sum(1 for h in items if h['_kw'])} match your keywords)" if KEYWORDS else "")
    if dry:
        print(subject + "\n\n" + txt)
    else:
        send(subject, txt, htm); print("Sent:", subject)
    for h in items: seen[h["objectID"]] = time.time()
    if not dry:
        json.dump(seen, open(SEEN_FILE, "w"))

if __name__ == "__main__":
    main()

Settings

VariableWhat it doesDefault
HN_KEYWORDScomma-separated words, matched as whole words in the title and linkempty
HN_MIN_POINTSstories with this many points are always included100
HN_KW_MIN_POINTSminimum points for a keyword match5
HN_HOURShow far back to look24
HN_MAX_ITEMSmaximum stories per email30
HN_SEEN_FILEwhere sent story ids are kept for 7 days~/.hn_digest_seen.json
SMTP_HOST, SMTP_PORTyour provider's SMTP server; 465 = SSL, other ports use STARTTLSport 465
SMTP_USER, SMTP_PASSWORDyour login (an app password for Gmail)
SMTP_FROM, SMTP_TOsender and recipient

What we tested

On 22 October 2026 we ran the script 9 times with Python 3.13 against the live Hacker News search API, sending to a local test SMTP server (aiosmtpd) instead of a real inbox. Here is what happened:

TestResult
Dry run with keywords n8n, python, self-hosted, llm30 stories, 7 keyword matches listed first (LLM agents, LiteLLM, Python items), then the biggest stories by points. Nothing written to disk.
Same with ai added30 of 30 matched a keyword. A broad word fills the whole digest, so keep keywords specific.
Whole-word matchOf 185 stories from the last 24 hours, 29 contain the letters "ai" inside another word (Ukraine, Restrain, Braille, Railway). With the whole-word check none of those 29 matched the keyword ai.
Send to a local SMTP serverOne email arrived with a plain-text and an HTML part; 30 story ids saved to the seen file.
Second run the same dayIt did not repeat the 30 stories. It sent the next 30 matching stories instead, so run it once a day.
Wrong API addressAfter 3 tries: Hacker News API failed: HTTP Error 404: Not Found, exit code 1, no email.
Wrong SMTP portConnectionRefusedError: [Errno 111] Connection refused
STARTTLS against a server without TLSsmtplib.SMTPNotSupportedError: STARTTLS extension not supported by server. Use the provider's real SMTP host and port 465 or 587.
No keywords, HN_MIN_POINTS=30012 stories: only the day's biggest.

Why not just use the front page?

The front page shows the 30 stories most people are reading right now. A keyword digest catches the 8-point post about the one tool you use, which drops off /newest within an hour and never reaches the front page. Keeping the 100-point rule means you still see the big story of the day.

Want AI news from blogs and newsletters instead of Hacker News? See the daily AI news digest. Want it in a chat instead of email? The RSS to Discord workflow works with Hacker News RSS feeds such as hnrss.org/newest?q=n8n.

FAQ

Do I need a Hacker News account or API key?

No. The script reads the public Hacker News search API run by Algolia, which needs no key and no account.

How do I get Hacker News stories by keyword by email?

Set HN_KEYWORDS to your words, add your SMTP login, and schedule the script once a day. Each email lists stories whose title or link contains one of your words, with points, comment count and a link to the discussion.

Will it send me the same story twice?

No. Every sent story id is kept for 7 days in the seen file, so a story that stays popular for two days appears once. Dry runs don't update that file.

Can I get it weekly instead of daily?

Yes. Set HN_HOURS=168, raise HN_MAX_ITEMS if you like, and change the cron line to 0 7 * * 1 for Monday mornings.

Does it work with Outlook or other email providers?

Yes, with any provider that allows SMTP: set SMTP_HOST and SMTP_PORT to the values your provider publishes. Gmail needs an app password, not your normal password.

Is it really free?

Yes. The script is MIT-licensed, the Hacker News API is free, and sending one email a day through your own account costs nothing.

Related guides

New guides

Want one built for your task?

Describe it in one sentence. We build it, test it and email it to you, usually within 24h. Free while we're in beta.

We'll only email you about your agent and TaskToAgent.