Python Payment Reminder Script: Email Unpaid Invoices on a Schedule
A Python payment reminder script reads your invoice list, picks every unpaid invoice whose reminder date has arrived, and emails each customer one reminder through Gmail. The script below does that from an Excel file, a CSV or a Google Sheet. It has a dry run, a date simulation, a log, and runs daily with Task Scheduler, cron or GitHub Actions.
Table of contents
What the script does
Each run sends a customer at most one email, even when they have two open invoices, and every email goes into a log file. The first version I built for the video used two files and a Google Sheet. This one is a single tested file and adds what I missed after using the first one for a while:
- It reads an Excel workbook, a CSV file or a Google Sheet’s CSV link, so your list can stay where it is.
- It starts in dry-run mode. Nothing is sent until you say so.
- It can pretend that today is another date, so you can see who gets a reminder next week.
- It never emails the same customer twice on one day, and it stops when the list suddenly asks for more emails than you expect.
- It sends through Gmail with an app password, and through any other SMTP server if you change two settings.
If you need the invoices themselves first, my tutorial on how to create PDF invoices from Excel in bulk with Python builds them from the same kind of list.
The invoice list
One row per invoice and seven columns with fixed headings: invoice_no, name, email, amount, due_date, reminder_date and has_paid. Dates must be real dates, and has_paid is yes or no. The headings matter because the script finds the columns by name.
| Column | What it holds | Example |
|---|---|---|
| invoice_no | Your invoice number | INV-1002 |
| name | The name used in the greeting | Ben Carter |
| Where the reminder goes | ben@example.com | |
| amount | The open amount, as a number | 1250.00 |
| due_date | When the invoice is due | 2026-12-05 |
| reminder_date | The first day a reminder may go out | 2026-12-08 |
| has_paid | yes or no | no |
The reminder_date is the day the first reminder should go out. I usually set it a few days after the due date, which gives a customer time to pay before they hear from me. If you prefer a friendly heads-up before the due date, set it a few days earlier instead. The script does not care which you choose.
Your list can live in three places. An Excel file next to the script is the simplest. A CSV file works the same way. A Google Sheet works too, as long as the script can download it as CSV, which I explain in the GitHub Actions section. If you keep the list in Excel but want a copy in Google Sheets, see how to sync Excel to Google Sheets.
Payment reminder sample invoices
Ten fictional invoices in the exact layout the script reads, formatted as an Excel table with a yes/no list for has_paid, plus a short How to use sheet.
When a reminder goes out
A customer gets a reminder when has_paid is no and the reminder date is today or earlier. Because the check is “today or earlier”, a daily run keeps reminding them every day until you set has_paid to yes. A missed run is caught up the next day.
Take the sample list and pretend it is December 15, 2026:
- INV-1001 (Anna) is paid. No email.
- INV-1002 and INV-1006 (Ben) are unpaid and both reminder dates have passed. Ben gets one email that lists both invoices.
- INV-1004 (David) has its reminder date today. David gets an email.
- INV-1005 (Erin) has its reminder date on December 18. No email yet.
The email says “was due on … and is still open” for an invoice past its due date, and “is due on …” for one that is not due yet. Here is the plain-text part of Ben’s email from my test run:
Hi Ben Carter,
This is a quick reminder about your open payment:
Invoice INV-1002 for 1,250.00 USD was due on 05 Dec 2026 and is still open.
Invoice INV-1006 for 640.00 USD was due on 08 Dec 2026 and is still open.
If you have already paid, please ignore this email.
Best regards
Example Studio
A daily reminder can feel pushy for a slow payer. If you want one reminder a week instead, schedule the script once a week, or move the reminder_date forward by seven days after each reminder.
The script
It is one file, payment_reminder.py, with under 200 lines. It needs Python 3.10 or newer and three packages: pandas to read the list, openpyxl for Excel files, and python-dotenv for the settings file. Sending uses smtplib, which comes with Python.
Create a folder, put the script and your invoice list in it, and install the packages. A virtual environment keeps them apart from other projects:
python -m venv .venv
.venv\Scripts\activate
# on Mac or Linux instead: source .venv/bin/activate
pip install pandas openpyxl python-dotenv
Then create a file called .env in the same folder. The script reads its settings from there, so your password never sits in the code:
SENDER_EMAIL=you@gmail.com
SENDER_NAME=Example Studio
APP_PASSWORD=your-16-letter-app-password
INVOICES=payment-reminder-sample-invoices.xlsx
DRY_RUN=1
If the folder is a Git repository, add .env to your .gitignore so the password never ends up on GitHub. Here is the script:
"""Email a payment reminder for every unpaid invoice whose reminder date has come.
Reads the invoice list from a Google Sheet (CSV link), a CSV file or an Excel file.
Settings come from environment variables or a .env file next to this script.
"""
import csv
import html
import os
import smtplib
import ssl
import sys
import time
from datetime import date
from email.message import EmailMessage
from email.utils import formataddr
from pathlib import Path
import pandas as pd # pip install pandas openpyxl
from dotenv import load_dotenv # pip install python-dotenv
HERE = Path(__file__).resolve().parent
load_dotenv(HERE / ".env")
SENDER_EMAIL = os.getenv("SENDER_EMAIL", "")
SENDER_NAME = os.getenv("SENDER_NAME") or "Accounts"
APP_PASSWORD = os.getenv("APP_PASSWORD", "")
INVOICES = os.getenv("INVOICES") or "payment-reminder-sample-invoices.xlsx"
SMTP_HOST = os.getenv("SMTP_HOST") or "smtp.gmail.com"
SMTP_PORT = int(os.getenv("SMTP_PORT") or "587")
DRY_RUN = os.getenv("DRY_RUN", "1") != "0" # 1 = only print, 0 = really send
MAX_EMAILS = int(os.getenv("MAX_EMAILS") or "50") # stop if the list looks wrong
PAUSE_SECONDS = float(os.getenv("PAUSE_SECONDS") or "3")
LOG_FILE = HERE / "reminder_log.csv"
# Simulate another day: TODAY=2026-12-15 shows who would get a reminder then.
TODAY = date.fromisoformat(os.getenv("TODAY") or date.today().isoformat())
def load_invoices(source):
"""Return the invoice list as a DataFrame with real dates."""
if not source.startswith(("http://", "https://")):
source = str(HERE / source) # relative paths start at this script's folder
if source.lower().endswith((".xlsx", ".xlsm")):
df = pd.read_excel(source, sheet_name="Invoices")
else: # a local .csv file or a Google Sheets CSV link
df = pd.read_csv(source)
df.columns = [str(c).strip().lower() for c in df.columns]
for col in ("due_date", "reminder_date"):
df[col] = pd.to_datetime(df[col], errors="coerce").dt.date
df["has_paid"] = df["has_paid"].fillna("no").astype(str).str.strip().str.lower()
df["email"] = df["email"].fillna("").astype(str).str.strip()
return df
def invoices_due(df, today):
"""Unpaid invoices whose reminder date is today or earlier."""
unpaid = df["has_paid"].isin(["no", "n", "false", "0"])
reminder_reached = df["reminder_date"].notna() & (df["reminder_date"] <= today)
has_email = df["email"].str.contains("@")
return df[unpaid & reminder_reached & has_email]
def already_emailed_today(today):
"""Addresses that already got a reminder today, read from the log file."""
if not LOG_FILE.exists():
return set()
with LOG_FILE.open(newline="", encoding="utf-8") as f:
return {
r["email"].lower()
for r in csv.DictReader(f)
if r["date"] == today.isoformat() and r["status"] == "sent"
}
def write_log(today, invoices, status):
new_file = not LOG_FILE.exists()
with LOG_FILE.open("a", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
if new_file:
writer.writerow(["date", "invoice_no", "email", "status"])
for _, row in invoices.iterrows():
writer.writerow([today.isoformat(), row["invoice_no"], row["email"], status])
def invoice_line(row):
amount = f"{float(row['amount']):,.2f} USD"
if pd.isna(row["due_date"]):
return f"Invoice {row['invoice_no']} for {amount} is open."
due = row["due_date"].strftime("%d %b %Y")
if row["due_date"] < TODAY:
return f"Invoice {row['invoice_no']} for {amount} was due on {due} and is still open."
return f"Invoice {row['invoice_no']} for {amount} is due on {due}."
def build_message(invoices):
"""One email per customer, listing every invoice that needs a reminder."""
first = invoices.iloc[0]
lines = [invoice_line(row) for _, row in invoices.iterrows()]
numbers = ", ".join(str(n) for n in invoices["invoice_no"])
label = "invoice" if len(invoices) == 1 else "invoices"
msg = EmailMessage()
msg["Subject"] = f"Payment reminder: {label} {numbers}"
msg["From"] = formataddr((SENDER_NAME, SENDER_EMAIL))
msg["To"] = first["email"]
msg["Bcc"] = SENDER_EMAIL # a copy for your records
text = [f"Hi {first['name']},", "", "This is a quick reminder about your open payment:", ""]
text += lines
text += ["", "If you have already paid, please ignore this email.", ""]
text += ["Best regards", SENDER_NAME]
msg.set_content("\n".join(text))
items = "".join(f"<li>{html.escape(line)}</li>" for line in lines)
msg.add_alternative(
f"<p>Hi {html.escape(str(first['name']))},</p>"
f"<p>This is a quick reminder about your open payment:</p><ul>{items}</ul>"
"<p>If you have already paid, please ignore this email.</p>"
f"<p>Best regards<br>{html.escape(SENDER_NAME)}</p>",
subtype="html",
)
return msg
def send_all(batches):
"""Send (invoices, message) pairs over one SMTP connection."""
sent = 0
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=30) as server:
if SMTP_HOST != "localhost": # localhost = a test server, no login
server.starttls(context=ssl.create_default_context())
server.login(SENDER_EMAIL, APP_PASSWORD)
for invoices, msg in batches:
try:
server.send_message(msg) # also delivers the Bcc copy
write_log(TODAY, invoices, "sent")
sent += 1
print(f"Sent {msg['Subject']} to {msg['To']}")
except smtplib.SMTPException as err:
write_log(TODAY, invoices, f"failed: {err}")
print(f"FAILED {msg['Subject']} to {msg['To']}: {err}")
time.sleep(PAUSE_SECONDS)
return sent
def main():
df = load_invoices(INVOICES)
due = invoices_due(df, TODAY)
emailed = already_emailed_today(TODAY)
skipped = due["email"].str.lower().isin(emailed)
due = due[~skipped]
batches = [
(invoices, build_message(invoices))
for _, invoices in due.groupby(due["email"].str.lower(), sort=False)
]
print(f"{TODAY}: {len(df)} invoices, {len(due)} need a reminder, {len(batches)} emails.")
if skipped.any():
print(f"Skipped {skipped.sum()} invoices: that customer already got a reminder today.")
if len(batches) > MAX_EMAILS:
sys.exit(f"Stopped: {len(batches)} emails is more than MAX_EMAILS={MAX_EMAILS}.")
if DRY_RUN:
for invoices, msg in batches:
print(f"Would send {msg['Subject']} to {msg['To']}")
print("Dry run: nothing was sent. Set DRY_RUN=0 to send.")
return
if not batches:
return
if SMTP_HOST != "localhost" and not (SENDER_EMAIL and APP_PASSWORD):
sys.exit("Set SENDER_EMAIL and APP_PASSWORD first.")
sent = send_all(batches)
print(f"Total reminders sent: {sent}")
if __name__ == "__main__":
main()
The settings at the top all come from the .env file or from environment variables:
| Setting | Default | What it does |
|---|---|---|
| INVOICES | payment-reminder-sample-invoices.xlsx | Excel file, CSV file or CSV link. Relative paths start at the script’s folder. |
| DRY_RUN | 1 | 1 prints who would get an email. 0 really sends. |
| TODAY | the real date | Pretend it is another day, for example 2026-12-15. |
| MAX_EMAILS | 50 | Stops the run when more emails would go out. |
| PAUSE_SECONDS | 3 | Pause between two emails. |
| SMTP_HOST, SMTP_PORT | smtp.gmail.com, 587 | The mail server. localhost means a test server without login. |
For an Excel file the script reads the sheet named Invoices. For a CSV it reads the whole file. Column headings are matched without regard to capital letters or extra spaces, but the names must be the seven listed above.
Set up Gmail
Gmail does not accept your normal password from a script. Turn on 2-Step Verification in your Google account, create an app password, and put that 16-letter password into the .env file as APP_PASSWORD. The script then signs in to smtp.gmail.com on port 587.
-
Turn on 2-Step Verification. Open your Google account, go to Security and turn on 2-Step Verification. Google only offers app passwords when it is on.
-
Create an app password. Open myaccount.google.com/apppasswords, type a name such as Payment reminders and click Create. Google shows a 16-letter password once. Copy it.
-
Paste it into .env. Set APP_PASSWORD to the 16 letters and SENDER_EMAIL to the Gmail address the password belongs to.
If your Google password changes, Google deletes your app passwords and you need a new one. A Google Workspace admin can also turn app passwords off for a company account. My post on sending Gmail from Excel with Python covers the app password and Gmail’s sending errors in more detail.
If you use Outlook.com: Microsoft no longer lets scripts sign in to Outlook.com or Hotmail with a password, so the Outlook server from the original version stops at the login. Gmail, a Google Workspace address, or the SMTP server of your own domain or email host all work: set SMTP_HOST and SMTP_PORT to the values your provider gives you.
Test without emailing customers
Run the script in dry-run mode, which is the default, and it prints who would get a reminder without sending anything. Add TODAY to simulate another date. To see the real emails, point the script at a local test mail server that prints every message instead of delivering it.
A dry run for December 15 with the sample workbook, in PowerShell:
$env:TODAY = "2026-12-15"
python payment_reminder.py
2026-12-15: 10 invoices, 5 need a reminder, 4 emails.
Would send Payment reminder: invoices INV-1002, INV-1006 to ben@example.com
Would send Payment reminder: invoice INV-1003 to chloe@example.com
Would send Payment reminder: invoice INV-1004 to david@example.com
Would send Payment reminder: invoice INV-1010 to ivy@example.com
Dry run: nothing was sent. Set DRY_RUN=0 to send.
On Mac or Linux, write the setting in front of the command instead: TODAY=2026-12-15 python payment_reminder.py. Change the date and run it again to walk through your receivables week by week. That is the quickest way to check the reminder dates in your list before anything goes out.
The dry run does not show the emails themselves. For that, start a local test server in a second terminal. The aiosmtpd package has one built in that accepts every email and prints it:
pip install aiosmtpd
python -m aiosmtpd -n -l localhost:8025
Then send for real, but to that server:
$env:SMTP_HOST = "localhost"
$env:SMTP_PORT = "8025"
$env:DRY_RUN = "0"
python payment_reminder.py
2026-12-15: 10 invoices, 5 need a reminder, 4 emails.
Sent Payment reminder: invoices INV-1002, INV-1006 to ben@example.com
Sent Payment reminder: invoice INV-1003 to chloe@example.com
Sent Payment reminder: invoice INV-1004 to david@example.com
Sent Payment reminder: invoice INV-1010 to ivy@example.com
Total reminders sent: 4
The test server window now shows each email with its subject, plain text and HTML part. Run the script a second time on the same day and it sends nothing, because the log already has those customers:
2026-12-15: 10 invoices, 0 need a reminder, 0 emails.
Skipped 5 invoices: that customer already got a reminder today.
Delete reminder_log.csv after testing, then remove SMTP_HOST, SMTP_PORT and TODAY again (or close the terminal). As a last check before going live, put your own address into one row and send a single real reminder through Gmail.
Run it daily on Windows
Create a daily task in Windows Task Scheduler that starts the Python of your virtual environment with the script. The PC must be on at that time. Set DRY_RUN=0 in the .env file first, because a scheduled run uses the settings in that file.
The fastest way is one command in a terminal. Change the folder to yours:
schtasks /Create /SC DAILY /ST 09:00 /TN "Payment reminders" /TR "C:\reminders\.venv\Scripts\python.exe C:\reminders\payment_reminder.py"
If your folder path has spaces, it is easier to create the task in the Task Scheduler window instead: Create Basic Task, a daily trigger, the action Start a program, the python.exe of your .venv as the program and the full path of payment_reminder.py as the argument. On the task’s Settings tab, tick “Run task as soon as possible after a scheduled start is missed” so a day when the PC was off is caught up later.
The script finds its .env, the invoice file and the log next to itself, so it does not matter which folder Task Scheduler starts it in. Right-click the task and choose Run to check it, then look at reminder_log.csv.
Schedule it with cron
Add one line to your crontab with crontab -e. The line below runs the script at 9:00 on weekdays and appends its output to a log file. Cron uses the time zone of the machine, and the machine has to be running at that time.
0 9 * * 1-5 cd /home/me/reminders && .venv/bin/python payment_reminder.py >> cron.log 2>&1
Use full paths, because cron starts with almost no environment. If nothing happens, cron.log usually tells you why. A small always-on server or a Raspberry Pi works well for this. On a laptop that sleeps at night, Task Scheduler with the catch-up setting or GitHub Actions is the safer choice.
Run it on GitHub Actions
Put the script and a requirements.txt into a private GitHub repository, store the Gmail address, app password and invoice link as repository secrets, and add a workflow with a schedule. GitHub then runs the script every weekday on its own servers, with no PC of yours switched on.
requirements.txt:
pandas
openpyxl
python-dotenv
The workflow goes into .github/workflows/payment-reminders.yml:
name: Payment reminders
on:
schedule:
- cron: "0 9 * * 1-5"
timezone: "America/New_York"
workflow_dispatch:
jobs:
remind:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-python@v7
with:
python-version: "3.13"
cache: pip
- run: pip install -r requirements.txt
- run: python payment_reminder.py
env:
INVOICES: ${{ secrets.INVOICES_CSV_URL }}
SENDER_EMAIL: ${{ secrets.SENDER_EMAIL }}
APP_PASSWORD: ${{ secrets.APP_PASSWORD }}
SENDER_NAME: Example Studio
DRY_RUN: "0"
-
Add the secrets. In the repository, open Settings, then Secrets and variables, then Actions, and add SENDER_EMAIL, APP_PASSWORD and INVOICES_CSV_URL as new repository secrets.
-
Run it once by hand. The workflow_dispatch line adds a Run workflow button on the Actions tab. Use it with DRY_RUN set to “1” first and read the log of the run.
-
Switch it on. Set DRY_RUN to “0” and push. From then on it runs at 9:00 New York time on weekdays. Change the timezone line to yours.
For the invoice link, open your Google Sheet, click Share and set General access to “Anyone with the link” as Viewer. The CSV link is then https://docs.google.com/spreadsheets/d/SHEET_ID/gviz/tq?tqx=out:csv&sheet=Invoices, with SHEET_ID taken from the sheet’s address. Anyone who has that link can read your invoices, which is why it belongs in a secret. If that is too open for you, commit the Excel file to the private repository instead and leave INVOICES_CSV_URL empty: the script then reads payment-reminder-sample-invoices.xlsx, or the file you name in INVOICES.
Three things to know about GitHub’s schedule. It runs only on the default branch. A run can start late when GitHub is busy. And in a public repository GitHub switches scheduled workflows off after 60 days without activity, which is one more reason to keep this repository private. Each run also starts with a fresh copy of the repository, so reminder_log.csv does not carry over from one run to the next. The once-a-day guard comes from the schedule there; the log still shows up in the run output.
Safeguards
Keep the dry run as the default, cap the number of emails per run, never email the same customer twice in one day, and log every email. The script does all four. The rest is habit: test with a copy of the list, and update has_paid the moment someone pays.
- Dry run first. DRY_RUN is on unless the setting says 0. A new list, a new column or a new month: run it dry once.
- MAX_EMAILS. When a sorting mistake or an empty has_paid column suddenly makes 400 invoices due, the script stops before sending anything. Set the number a little above your normal day.
- Once per customer per day. The log file stores every address that got a reminder today. A second run, by hand or by a double-booked schedule, skips them.
- A log. reminder_log.csv has the date, invoice number, address and result of every email, including failures. It is your answer when a customer says they never got a reminder.
- A copy for you. Every reminder goes to you as BCC, so your mailbox shows exactly what customers received.
- A calm pace. The script waits a few seconds between emails. Gmail allows about 500 emails a day from a normal account, which is far more than a reminder run needs. I explain Gmail’s limits in how to send bulk email from Gmail using Excel.
Troubleshooting
Most failures are a refused Gmail login, a list the script cannot read, or dates that were not parsed. The printed summary line tells you which: zero invoices means the list, zero reminders means the dates or has_paid, and an error at login means the app password.
| What you see | Why | Fix |
|---|---|---|
| SMTPAuthenticationError 535 | Gmail refused the password | Use an app password, not your Google password, and check SENDER_EMAIL belongs to it. |
| KeyError: ‘reminder_date’ (or another column) | A column heading is missing or spelled differently | Use the seven headings exactly as in the sample. |
| ValueError: Worksheet named ‘Invoices’ not found | The Excel sheet has another name | Rename the sheet to Invoices. |
| “0 need a reminder” although some are overdue | has_paid is empty or says something else, or the dates are text | Use yes or no, and real dates. A dry run with TODAY set shows what changes. |
| Wrong reminders from a Google Sheet | Dates like 03/12/2026 can be read as March 12 | Format the date columns as yyyy-mm-dd in the sheet. |
| HTTPError, or a KeyError with a Google Sheet | The sheet is not shared by link, so Google sends a sign-in page instead of data | Set General access to “Anyone with the link” and check the sheet name in the link. |
| Stopped: … more than MAX_EMAILS | The safeguard did its job | Check the list. Raise MAX_EMAILS only when the number is right. |
| Nothing happens on schedule | The PC was off, or cron has no full paths | Use the catch-up setting in Task Scheduler, full paths in cron, or GitHub Actions. |
Gmail may pause an account for a day when emails go out too fast, and reminders can land in a customer’s spam folder when they look like a campaign. Keep the subject plain, use the customer’s name and invoice number, and avoid links you do not need.
The original Deta version
Deta, the cloud service the first version used to run the script daily, has shut down. That code ran inside a Deta “micro” with a cron decorator. The script in this post replaces it with Task Scheduler, cron or GitHub Actions.
The original two-file version is still on GitHub in my automate-sending-emails-using-python repository. Its send_email.py and the reminder check work like the script above, but it imports Deta, uses the Outlook server and has no dry run, log or limit. The original Google Sheet is no longer online; the download above has the same columns. If you want to see how Python fits into other office routines, my post on automating boring office tasks with ChatGPT and Python has more ideas.
Not everyone wants to maintain a script. If you would rather send the reminders yourself from the Excel list with a few clicks, my guide to mail merge from Excel to Outlook or Gmail shows how, including a different invoice PDF for each customer.
Send payment reminders from an Excel list without code: one personal email per customer through your own Gmail or Outlook, each with their own invoice attached. Try it with 100 free emails.
