Google Gmail model

Correspondents monthly

Who the mailbox talks to, per month: messages received from and sent to each address.

Grain
one row per month x correspondent address
Built from
  1. 4
    Raw tables
  2. 4
    Staging
  3. 2
    Core
  4. 1
    Analytics
Reads from Google Gmail
messagemessage_labelmessage_part_headerprofile
Ships as
Weld and dbt SQL, open source on GitHub
core.gmail.correspondents_monthly
1-- core.gmail.correspondents_monthly
2-- Who the mailbox talks to, per month: messages received from and sent to each address.
3--
4-- Grain: one row per month x correspondent address.
5-- Depends on: core.gmail.messages
6--
7-- Received mail is counted against the sender. Sent mail is counted against every To and
8-- Cc address, so one message to three people adds one to each of them; `messages_sent`
9-- therefore sums to more than the number of messages sent. The mailbox's own address is
10-- left out.
11
12WITH received AS (
13    SELECT
14        DATE_TRUNC(date, MONTH)             AS month,
15        from_address                        AS correspondent,
16        1                                   AS is_received
17    FROM {{core.gmail.messages}}
18    WHERE direction = 'received'
19      AND from_address IS NOT NULL
20),
21
22sent AS (
23    SELECT
24        DATE_TRUNC(m.date, MONTH)           AS month,
25        recipient                           AS correspondent,
26        0                                   AS is_received
27    FROM {{core.gmail.messages}} m,
28         UNNEST(ARRAY_CONCAT(m.to_addresses, m.cc_addresses)) AS recipient
29    WHERE m.direction = 'sent'
30      AND recipient IS DISTINCT FROM m.mailbox_address
31)
32
33SELECT
34    month,
35    correspondent,
36    REGEXP_EXTRACT(correspondent, r'@(.+)$')    AS correspondent_domain,
37    COUNTIF(is_received = 1)                    AS messages_received,
38    COUNTIF(is_received = 0)                    AS messages_sent
39FROM (
40    SELECT * FROM received

This model and the 6 it depends on. Deploy them together; refs like {{staging.…}} resolve to the matching folders in Weld, and the dbt view uses source() and ref().

Notes

How it counts. And where it stops.

Received mail is counted against the sender. Sent mail is counted against every To and Cc address, so one message to three people adds one to each of them; `messages_sent` therefore sums to more than the number of messages sent. The mailbox's own address is left out.

Raw tables it reads

  • raw.gmail.message
  • raw.gmail.message_label
  • raw.gmail.message_part_header
  • raw.gmail.profile

Put Google Gmail in front
of your agents.

Connect Google Gmail, deploy the models, and ask questions in Claude, Cursor or ChatGPT. Free for 14 days, no credit card.