Initial commit

This commit is contained in:
Augusto Gunsch 2022-04-19 14:43:17 -03:00
commit df6a09b81e
6 changed files with 92 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
config.py
__pycache__/

1
README.md Normal file
View File

@ -0,0 +1 @@
Lazy scripts I made for scheduling emails to be sent at specific times

0
__init__.py Normal file
View File

5
config.py Normal file
View File

@ -0,0 +1,5 @@
HOSTNAME = 'localhost'
PORT = 587
EMAIL = 'example@hostname.com'
LOGIN = 'example'
PASSWORD = 'strong_password'

45
mailman.py Executable file
View File

@ -0,0 +1,45 @@
#!/bin/python3.9
import config, re, smtplib, os
from datetime import datetime
from email.message import EmailMessage
from pathlib import Path
os.chdir(os.path.dirname(__file__))
smtp = smtplib.SMTP(config.HOSTNAME, port=config.PORT)
smtp.ehlo()
smtp.starttls()
smtp.ehlo()
smtp.login(config.LOGIN, config.PASSWORD)
for mail in Path('scheduled').glob('*.mail'):
with mail.open('r') as file:
msg = file.read()
scheduled = re.findall(r'Scheduled to \(UTC\): (.*)\n', msg)[0]
scheduled = datetime.fromisoformat(scheduled)
if scheduled <= datetime.now():
to_address = re.findall(r'To: (.*)\n', msg)[0]
subject = re.findall(r'Subject: (.*)\n', msg)[0]
body = ''
reading_body = False
for line in msg.splitlines():
if reading_body:
body += f'{line}\n'
elif line == '---- Body ----':
reading_body = True
msg = EmailMessage()
msg.set_content(body)
msg['Subject'] = subject
msg['From'] = config.EMAIL
msg['To'] = to_address
smtp.send_message(msg)
mail.unlink()
smtp.quit()

39
schedule.py Executable file
View File

@ -0,0 +1,39 @@
#!/bin/python3.9
import os, tempfile, subprocess, re, sys
from datetime import datetime, timedelta
os.chdir(os.path.dirname(__file__))
EDITOR = os.environ.get('EDITOR', 'vim')
os.makedirs('scheduled', exist_ok=True)
tomorrow = datetime.utcnow() + timedelta(days=1)
tomorrow = tomorrow.replace(microsecond=0, second=0, minute=int(tomorrow.minute/15))
initial_msg = f'To: \nSubject: \nScheduled to (UTC): {tomorrow.isoformat()}\n---- Body ----'
with tempfile.NamedTemporaryFile() as file:
file.write(bytes(initial_msg, encoding='utf-8'))
file.flush()
subprocess.call([EDITOR, file.name])
file.seek(0)
msg = file.read().decode()
to = re.findall(r'To: (.*)\n', msg)[0]
subject = re.findall(r'Subject: (.*)\n', msg)[0]
if not to or not subject:
print('ERROR: recipient or subject empty')
exit(1)
filename = f'scheduled/{to}:{subject}.mail'
if os.path.exists(filename):
print('ERROR: an email for this recipient with the same subject is already scheduled')
exit(1)
with open(filename, 'w') as file:
file.write(msg)