| @@ -1,6 +1,7 @@ |
| 1 | # Fetch a random poem from PoetryDB and mail it. |
1 | # Fetch a random poem from PoetryDB and mail it. |
| 2 | import smtplib |
2 | import smtplib |
| 3 | from email.mime.text import MIMEText |
3 | from email.mime.text import MIMEText |
| |
4 | from typing import NamedTuple |
| 4 | |
5 | |
| 5 | import requests |
6 | import requests |
| 6 | |
7 | |
| @@ -12,30 +13,34 @@ SENDER_EMAIL = "" |
| 12 | RECIPIENT_EMAILS = "" |
13 | RECIPIENT_EMAILS = "" |
| 13 | |
14 | |
| 14 | |
15 | |
| |
16 | class Poem(NamedTuple): |
| |
17 | title: str |
| |
18 | author: str |
| |
19 | line_count: str |
| |
20 | lines: str |
| |
21 | |
| |
22 | |
| 15 | def fetch_poem(url=POETRY_URL): |
23 | def fetch_poem(url=POETRY_URL): |
| 16 | """Return (title, author, line_count, body) for a random poem.""" |
24 | """Return a random poem.""" |
| 17 | json_data = requests.get(url, timeout=30).json() |
25 | json_data = requests.get(url, timeout=30).json() |
| 18 | poem = json_data[0] |
26 | poem = json_data[0] |
| 19 | lines = "" |
27 | lines = "" |
| 20 | for line in poem["lines"]: |
28 | for line in poem["lines"]: |
| 21 | lines = lines + line + "\n" |
29 | lines = lines + line + "\n" |
| 22 | return poem["title"], poem["author"], poem["linecount"], lines |
30 | return Poem(poem["title"], poem["author"], poem["linecount"], lines) |
| 23 | |
31 | |
| 24 | |
32 | |
| 25 | def build_message(title, author, line_count, lines, sender, recipient): |
33 | def build_message(poem, sender, recipient): |
| 26 | """Return a plaintext MIMEText message for one poem.""" |
34 | """Return a plaintext MIMEText message for one poem.""" |
| 27 | msg = MIMEText(title + "\n" + author + "\n\n" + lines) |
35 | msg = MIMEText(poem.title + "\n" + poem.author + "\n\n" + poem.lines) |
| 28 | msg["Subject"] = "Your Daily Poem (" + line_count + " lines)" |
36 | msg["Subject"] = "Your Daily Poem (" + poem.line_count + " lines)" |
| 29 | msg["From"] = sender |
37 | msg["From"] = sender |
| 30 | msg["To"] = recipient |
38 | msg["To"] = recipient |
| 31 | return msg |
39 | return msg |
| 32 | |
40 | |
| 33 | |
41 | |
| 34 | def main(): |
42 | def main(): |
| 35 | title, author, line_count, lines = fetch_poem() |
43 | msg = build_message(fetch_poem(), SENDER_EMAIL, RECIPIENT_EMAILS) |
| 36 | msg = build_message( |
| |
| 37 | title, author, line_count, lines, SENDER_EMAIL, RECIPIENT_EMAILS |
| |
| 38 | ) |
| |
| 39 | |
44 | |
| 40 | # Send via the local SMTP server, without the envelope header. |
45 | # Send via the local SMTP server, without the envelope header. |
| 41 | s = smtplib.SMTP(SMTP_SERVER) |
46 | s = smtplib.SMTP(SMTP_SERVER) |