krz/daily-poem
clone: git clone https://gitbay.org/krz/daily-poem.git
main: main.py · raw
1# Fetch a random poem from PoetryDB and mail it.
2import smtplib
3from email.mime.text import MIMEText
4
5import requests
6
7POETRY_URL = "https://poetrydb.org/random"
8SMTP_SERVER = "localhost"
9
10# Fill these in before running.
11SENDER_EMAIL = ""
12RECIPIENT_EMAILS = ""
13
14
15def fetch_poem(url=POETRY_URL):
16 """Return (title, author, line_count, body) for a random poem."""
17 json_data = requests.get(url, timeout=30).json()
18 poem = json_data[0]
19 lines = ""
20 for line in poem["lines"]:
21 lines = lines + line + "\n"
22 return poem["title"], poem["author"], poem["linecount"], lines
23
24
25def build_message(title, author, line_count, lines, sender, recipient):
26 """Return a plaintext MIMEText message for one poem."""
27 msg = MIMEText(title + "\n" + author + "\n\n" + lines)
28 msg["Subject"] = "Your Daily Poem (" + line_count + " lines)"
29 msg["From"] = sender
30 msg["To"] = recipient
31 return msg
32
33
34def main():
35 title, author, line_count, lines = fetch_poem()
36 msg = build_message(
37 title, author, line_count, lines, SENDER_EMAIL, RECIPIENT_EMAILS
38 )
39
40 # Send via the local SMTP server, without the envelope header.
41 s = smtplib.SMTP(SMTP_SERVER)
42 s.sendmail(SENDER_EMAIL, [RECIPIENT_EMAILS], msg.as_string())
43 s.quit()
44
45
46if __name__ == "__main__":
47 main()