Skip to content

Commit d1d44ab

Browse files
author
Sam Razavi
committed
Email forwarding: keep only mail about job applications
People forward their whole inbox, so every newsletter, receipt and delivery notice was stored and shown in the Inbox, and a parcel notice from amazon.se was matched to an Amazon application by its sender domain. - relevance.py decides whether an email is about a job application: a confident rejection/interview/offer, job wording, a match to a tracked application, or a recruiting-system sender. Shop and delivery subjects and bulk mail not tied to an application are dropped. - Dropped mail is not stored at all. - Migration 0036 deletes stored noise that nobody acted on. Gmail's forwarding confirmation and anything with a detected decision are kept. - Privacy policy says what is not kept.
1 parent f366826 commit d1d44ab

9 files changed

Lines changed: 350 additions & 0 deletions

File tree

‎CLAUDE.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -534,6 +534,16 @@ Inbound Email Ingestion (August 2026, first slice):
534534
Gmail's confirmation prompt once later mail has arrived (or the user
535535
clicks "I've confirmed it"), and its Outlook steps use "Redirect to",
536536
which keeps the recruiter as `From:`.
537+
- Relevance filter (November 2026): people forward their whole inbox, so
538+
every newsletter and receipt was stored and shown, and a parcel notice from
539+
amazon.se matched an Amazon application by sender domain.
540+
`relevance.py` `is_job_related` (pure) keeps mail with a confident
541+
classification, job wording, a match or an ATS sender, and drops shop and
542+
delivery subjects and bulk mail not tied to an application. Dropped mail is
543+
NOT stored (the task returns `ignored`). The bulk flag is computed in the
544+
webhook (`looks_bulk`: List-Unsubscribe and similar headers, sender, body),
545+
because headers do not cross the queue. Migration `0036` deleted stored
546+
noise nobody had acted on; Alembic chain ends at `0036`.
537547
- Extension sign-in: `/extension-auth` opens in a new tab with no in-memory
538548
token, and a cookie-only POST cannot pass the CSRF check from
539549
applyluma.com (the `csrf_token` cookie belongs to the API's domain), so
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
"""delete stored inbound emails that are not about a job application
2+
3+
Revision ID: 0036
4+
Revises: 0035
5+
6+
Until now every forwarded email was stored, so inboxes filled with newsletters,
7+
receipts and delivery notices. New mail of that kind is no longer stored
8+
(services/inbound_email/relevance.py); this removes what is already there.
9+
10+
Only rows nobody acted on are touched (suggestion_state 'none', no decision
11+
detected). Gmail's forwarding confirmation is kept: Settings reads its code.
12+
The headers of old rows were never stored, so "bulk" is judged from the sender
13+
and the text alone.
14+
"""
15+
from collections.abc import Sequence
16+
17+
import sqlalchemy as sa
18+
19+
from alembic import op
20+
21+
revision: str = "0036"
22+
down_revision: str | None = "0035"
23+
branch_labels: str | Sequence[str] | None = None
24+
depends_on: str | Sequence[str] | None = None
25+
26+
27+
def upgrade() -> None:
28+
from app.services.inbound_email.forwarded import is_gmail_confirmation
29+
from app.services.inbound_email.relevance import is_job_related, looks_bulk
30+
31+
bind = op.get_bind()
32+
rows = bind.execute(
33+
sa.text(
34+
"""
35+
SELECT id, from_address, from_domain, subject, snippet, matched_application_id
36+
FROM inbound_emails
37+
WHERE suggestion_state = 'none' AND classification IS NULL
38+
"""
39+
)
40+
).mappings().all()
41+
42+
doomed = []
43+
for row in rows:
44+
if is_gmail_confirmation(row["from_address"]):
45+
continue
46+
keep, _ = is_job_related(
47+
subject=row["subject"],
48+
snippet=row["snippet"],
49+
from_domain=row["from_domain"],
50+
classification=None,
51+
matched=row["matched_application_id"] is not None,
52+
bulk=looks_bulk(headers={}, from_address=row["from_address"], snippet=row["snippet"]),
53+
)
54+
if not keep:
55+
doomed.append(row["id"])
56+
57+
for row_id in doomed:
58+
bind.execute(sa.text("DELETE FROM inbound_emails WHERE id = :id"), {"id": row_id})
59+
60+
61+
def downgrade() -> None:
62+
# Deleted mail cannot be restored.
63+
pass

‎backend/app/api/v1/endpoints/inbound_email.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@
2929
from app.services.inbound_email.forwarded import unwrap_forward
3030
from app.services.inbound_email.matcher import normalize_domain
3131
from app.services.inbound_email.registry import UnknownVendorError, get_adapter
32+
from app.services.inbound_email.relevance import looks_bulk
3233
from app.tasks.inbound_email import process_inbound_email
3334

3435
logger = logging.getLogger(__name__)
@@ -146,10 +147,13 @@ async def inbound_email_webhook(request: Request) -> Response:
146147
# sender written in the forwarded header block instead. Done here, on the
147148
# full body, because only the truncated snippet crosses the queue.
148149
from_address, subject, body = email.from_address, email.subject, email.text_body
150+
message_headers = email.headers
149151
original = unwrap_forward(email.subject, email.text_body)
150152
if original is not None:
151153
from_address, subject, body = original.from_address, original.subject, original.body
152154
sender_domain = normalize_domain(from_address.rpartition("@")[2])
155+
# The headers are those of the user's own forward, not of the original.
156+
message_headers = {}
153157

154158
payload: dict[str, Any] = {
155159
"user_id": str(user.id),
@@ -163,6 +167,8 @@ async def inbound_email_webhook(request: Request) -> Response:
163167
"snippet": (body or "")[:SNIPPET_CHARS] or None,
164168
"received_at": email.received_at.isoformat() if email.received_at else None,
165169
"vendor": adapter.name,
170+
# Decided here: the headers do not cross the queue.
171+
"bulk": looks_bulk(headers=message_headers, from_address=from_address, snippet=body),
166172
}
167173

168174
try:
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
"""Decide whether a forwarded email is about a job application at all.
2+
3+
People forward their whole inbox, so most of what arrives is newsletters,
4+
receipts and delivery notices. Keeping those would show noise in the inbox,
5+
store private mail that has nothing to do with the product, and let a parcel
6+
notice from a company the user applied to pass as mail about the application.
7+
8+
Pure function, no database: the task calls it after matching and classifying,
9+
and stores nothing for mail it rejects.
10+
"""
11+
12+
from __future__ import annotations
13+
14+
import re
15+
from collections.abc import Mapping
16+
17+
from app.services.inbound_email.classifier import SUGGEST_THRESHOLD, Classification
18+
from app.services.inbound_email.matcher import ATS_DOMAINS, domain_matches
19+
20+
_FOLD = str.maketrans("àáâãäåèéêëìíîïòóôõöøùúûüýÿçñ", "aaaaaaeeeeiiiioooooouuuuyycn")
21+
22+
23+
def _fold(text: str | None) -> str:
24+
return (text or "").lower().translate(_FOLD)
25+
26+
27+
# Words that mark mail about applying for a job, in English and Swedish
28+
# (diacritics folded). Matched on word starts, so "applic" covers application,
29+
# applications and applicant.
30+
_JOB_WORDS = re.compile(
31+
r"\b("
32+
r"applic|applied|applying|candidate|candidacy|interview|recruit|hiring manager|"
33+
r"talent acquisition|job offer|offer of employment|your cv|your resume|vacancy|"
34+
r"the position|the role|this position|this role|"
35+
r"ansokan|ansokning|ansokt|sokt tjansten|kandidat|intervju|rekryter|"
36+
r"tjansten|rollen som|anstallning|urvalsprocess|ditt cv"
37+
r")"
38+
)
39+
40+
# Words that mark shop and delivery mail. Checked in the subject only: a job ad
41+
# may well mention "delivery" in its text.
42+
_COMMERCE_WORDS = re.compile(
43+
r"\b("
44+
r"order|shipped|shipment|delivery|delivered|tracking|invoice|receipt|refund|payment|"
45+
r"subscription|"
46+
r"skickad|skickade|leverans|levererad|bestallning|faktura|kvitto|betalning|paket|"
47+
r"prenumeration"
48+
r")"
49+
)
50+
51+
# Senders that only ever send bulk or automated mail.
52+
_BULK_SENDER = re.compile(
53+
r"(newsletter|news@|digest|marketing|promo|deals|offers@|shipment|order-|orders@|billing|receipts?@)"
54+
)
55+
56+
_BULK_BODY = re.compile(
57+
r"(unsubscribe|view (this email )?in (your )?browser|manage (your )?preferences|"
58+
r"avregistrera|avprenumerera|avsluta prenumeration|visa i webblasare)"
59+
)
60+
61+
_BULK_HEADERS = ("list-unsubscribe", "list-id", "x-campaign", "x-mailgun-tag", "feedback-id")
62+
63+
64+
def looks_bulk(
65+
*, headers: Mapping[str, str], from_address: str | None, snippet: str | None
66+
) -> bool:
67+
"""Whether the mail is a mailing-list or automated send, not a person's message."""
68+
lowered = {key.lower(): value for key, value in headers.items()}
69+
if any(name in lowered for name in _BULK_HEADERS):
70+
return True
71+
if lowered.get("precedence", "").strip().lower() in {"bulk", "list", "junk"}:
72+
return True
73+
if _BULK_SENDER.search((from_address or "").lower()):
74+
return True
75+
return bool(_BULK_BODY.search(_fold(snippet)))
76+
77+
78+
def is_job_related(
79+
*,
80+
subject: str | None,
81+
snippet: str | None,
82+
from_domain: str | None,
83+
classification: Classification | None,
84+
matched: bool,
85+
bulk: bool,
86+
) -> tuple[bool, str]:
87+
"""Return ``(keep, reason)`` for one email."""
88+
folded_subject = _fold(subject)
89+
has_job_words = bool(_JOB_WORDS.search(folded_subject) or _JOB_WORDS.search(_fold(snippet)))
90+
from_ats = any(domain_matches(from_domain or "", ats) for ats in ATS_DOMAINS)
91+
92+
if classification is not None and classification.confidence >= SUGGEST_THRESHOLD:
93+
return True, "It reads like a decision on an application."
94+
95+
if _COMMERCE_WORDS.search(folded_subject) and not _JOB_WORDS.search(folded_subject):
96+
return False, "The subject is about an order, delivery or payment."
97+
98+
if bulk:
99+
# A mailing-list send is kept only when it is tied to something the
100+
# user applied for: job-alert digests and newsletters mention jobs too.
101+
if has_job_words and (matched or from_ats):
102+
return True, "Bulk mail about an application the user tracks."
103+
return False, "Newsletter or automated bulk mail."
104+
105+
if has_job_words:
106+
return True, "It uses the wording of a job application."
107+
if matched:
108+
return True, "A personal message from a company the user applied to."
109+
if from_ats:
110+
return True, "Sent through a recruiting system."
111+
return False, "Nothing in it is about a job application."

‎backend/app/tasks/inbound_email.py‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from app.services.inbound_email.classifier import Classification, classify
2424
from app.services.inbound_email.forwarded import is_gmail_confirmation
2525
from app.services.inbound_email.matcher import MatchResult, score_email
26+
from app.services.inbound_email.relevance import is_job_related
2627
from app.tasks.celery_app import celery_app
2728

2829
logger = logging.getLogger(__name__)
@@ -109,6 +110,20 @@ def process_inbound_email(payload: dict[str, Any]) -> dict[str, str]:
109110
)
110111
classification = classify(subject, snippet)
111112

113+
keep, why = is_job_related(
114+
subject=subject,
115+
snippet=snippet,
116+
from_domain=from_domain,
117+
classification=classification,
118+
matched=match.application_id is not None,
119+
bulk=bool(payload.get("bulk")),
120+
)
121+
if not keep:
122+
# Not stored at all: a newsletter or a receipt is none of the
123+
# product's business. The log line carries no content.
124+
logger.info("inbound_email_ignored", extra={"reason": why, "from_domain": from_domain})
125+
return {"status": "ignored", "reason": why}
126+
112127
try:
113128
row = crud_inbound_email.create(
114129
db,

‎backend/tests/test_inbound_email_endpoint.py‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -278,3 +278,16 @@ async def test_manual_forward_is_matched_on_the_original_sender(
278278
assert enqueued[0]["from_domain"] == "spotify.com"
279279
assert enqueued[0]["subject"] == "Your application to Spotify"
280280
assert enqueued[0]["snippet"] == "Unfortunately we will not move forward."
281+
282+
283+
@pytest.mark.asyncio
284+
async def test_bulk_mail_is_flagged_before_the_queue(
285+
monkeypatch: pytest.MonkeyPatch, enqueued: list[dict[str, Any]]
286+
) -> None:
287+
"""The headers never cross the queue, so the flag is decided here."""
288+
known_user(monkeypatch)
289+
290+
await post(body())
291+
await post(body(**{"from": "Dan <dan@tldrnewsletter.com>", "message_id": "<n-1@tldr>"}))
292+
293+
assert [p["bulk"] for p in enqueued] == [False, True]
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
"""Which forwarded emails are about a job application (pure, no database).
2+
3+
The first block is the mail that actually filled a user's inbox in production.
4+
"""
5+
6+
from __future__ import annotations
7+
8+
from typing import Any
9+
10+
import pytest
11+
12+
from app.services.inbound_email.classifier import classify
13+
from app.services.inbound_email.relevance import is_job_related, looks_bulk
14+
15+
16+
def judge(
17+
*, sender: str, subject: str, body: str = "", headers: dict[str, str] | None = None, matched: bool = False
18+
) -> bool:
19+
keep, _ = is_job_related(
20+
subject=subject,
21+
snippet=body,
22+
from_domain=sender.rpartition("@")[2],
23+
classification=classify(subject, body),
24+
matched=matched,
25+
bulk=looks_bulk(headers=headers or {}, from_address=sender, snippet=body),
26+
)
27+
return keep
28+
29+
30+
UNSUB = {"List-Unsubscribe": "<https://example.com/u>"}
31+
32+
33+
@pytest.mark.parametrize(
34+
"mail",
35+
[
36+
dict(sender="noreply@glassdoor.com", subject="At 30 years old, with $600,000 in saving an annual...", headers=UNSUB),
37+
dict(sender="dan@tldrnewsletter.com", subject="Gemini Hydrogen arrives, Resend moves to ...", body="Sponsor: we are hiring engineers."),
38+
dict(sender="team@cs.resumeworded.com", subject="CS#376: Terrible cooks, the two-skip rule, and how to interview", headers=UNSUB),
39+
dict(sender="dan@tldrnewsletter.com", subject="Nvidia's CEO search, AWS emulator", headers=UNSUB),
40+
dict(sender="info@lagenhetsbyte.se", subject="Du har nya bytesförslag att ta ställning till"),
41+
# A parcel notice from a company the user applied to must not pass as
42+
# mail about that application.
43+
dict(sender="shipment-tracking@amazon.se", subject='Skickade: "Amazon Basics HDMI Splitter..." och 1 till', matched=True),
44+
dict(sender="orders@spotify.com", subject="Your receipt from Spotify", matched=True),
45+
dict(sender="jobs-noreply@linkedin.com", subject="30 new jobs for Backend Developer", body="Apply now. Unsubscribe"),
46+
dict(sender="friend@example.com", subject="Dinner on Friday?", body="Are you free?"),
47+
],
48+
)
49+
def test_noise_is_not_kept(mail: dict[str, Any]) -> None:
50+
assert judge(**mail) is False
51+
52+
53+
@pytest.mark.parametrize(
54+
"mail",
55+
[
56+
dict(sender="no-reply@teamtailor.com", subject="Thank you for your application to Klarna", body="We have received your application."),
57+
dict(sender="rekrytering@kommun.se", subject="Tack för din ansökan", body="Vi har tagit emot din ansökan till tjänsten."),
58+
dict(sender="anna@klarna.com", subject="Quick question", body="Hi Sam, are you free on Tuesday at 10?", matched=True),
59+
dict(sender="hr@company.se", subject="Regarding the position", body="Unfortunately we have decided to move forward with other candidates."),
60+
dict(sender="talent@startup.io", subject="Interview invitation", body="We would like to invite you to an interview."),
61+
dict(sender="no-reply@greenhouse.io", subject="An update from Acme", body="Please see the message below."),
62+
# A status mail sent through a mailing system is still kept when it is
63+
# tied to something the user applied for.
64+
dict(sender="careers@klarna.com", subject="Your application at Klarna", body="Thanks for applying.", headers=UNSUB, matched=True),
65+
dict(sender="noreply@varbi.com", subject="Bekräftelse på din ansökan", body="Din ansökan är mottagen.", headers=UNSUB),
66+
],
67+
)
68+
def test_job_mail_is_kept(mail: dict[str, Any]) -> None:
69+
assert judge(**mail) is True
70+
71+
72+
def test_a_clear_decision_is_kept_even_from_a_bulk_sender() -> None:
73+
assert judge(
74+
sender="newsletter@bigcorp.com",
75+
subject="Your application",
76+
body="Unfortunately we will not be moving forward with your application.",
77+
headers=UNSUB,
78+
)
79+
80+
81+
@pytest.mark.parametrize(
82+
("headers", "sender", "body", "expected"),
83+
[
84+
({"List-Unsubscribe": "<mailto:x>"}, "a@b.com", "", True),
85+
({"Precedence": "bulk"}, "a@b.com", "", True),
86+
({}, "dan@tldrnewsletter.com", "", True),
87+
({}, "a@b.com", "Click here to unsubscribe.", True),
88+
({}, "a@b.com", "Klicka här för att avregistrera dig.", True),
89+
({}, "anna@klarna.com", "Hi Sam, are you free on Tuesday?", False),
90+
],
91+
)
92+
def test_bulk_detection(headers: dict[str, str], sender: str, body: str, expected: bool) -> None:
93+
assert looks_bulk(headers=headers, from_address=sender, snippet=body) is expected

0 commit comments

Comments
 (0)