First commit

This commit is contained in:
Cyril Novel 2020-06-11 20:10:49 +02:00
commit 16a203292d
7 changed files with 920 additions and 0 deletions

195
src/email_sender.py Normal file
View file

@ -0,0 +1,195 @@
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from smtplib import SMTP_SSL
from argparse import ArgumentParser
from datetime import date, timedelta
import wikiquote
from src.event import create_events_from_span
week_days = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche']
months = ['janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
'octobre', 'novembre', 'décembre']
class EmailSender:
def __init__(self, smtp_server, user, password):
self._smtp_server = smtp_server
self._user = user
self._pwd = password
print("Setup OK")
def send_paturlettre(self, recipients):
msg = MIMEMultipart('alternative')
msg['Subject'] = f'[Paturlettre] Semaine {get_week_number_and_span()[0]}'
msg['From'] = 'Paturlettre <paturlettre@kosmon.fr>'
msg['To'] = 'Diffusion Paturlettre <no_reply_paturlettre@kosmon.fr>'
msg.preamble = f'La Paturlettre de la semaine {get_week_number_and_span()[0]} !'
msg.attach(MIMEText(create_plain_email(), 'plain'))
msg.attach(MIMEText(create_email_from_template(), 'html'))
print("Msg OK")
conn = SMTP_SSL(self._smtp_server, port=465)
print("Conn OK")
conn.login(self._user, self._pwd)
print("Login OK")
try:
conn.sendmail(msg['From'], 'diffusion_paturlettre@kosmon.fr', msg.as_string())
print("Send OK")
finally:
conn.quit()
def create_email_from_template():
events_previous, events_current, events_next = get_events()
with open('../html_template/mail.html', 'r', encoding='utf-8') as tmp:
mail = tmp.read()
mail = mail.replace('{LogoAddress}',
'https://tof.cx/images/2020/05/27/448fd7d507778064b39ba95c381cd3e8.png')
wk_and_span = get_week_number_and_span()
mail = mail.replace('{Main_Title}', f'Semaine {wk_and_span[0]}')
mail = mail.replace('{Sub_Title}',
f'du {wk_and_span[1].day} {months[wk_and_span[1].month - 1]}'
f' au {wk_and_span[2].day} {months[wk_and_span[2].month - 1]}')
mail = mail.replace('{EVENTS_PREVIOUS}', create_html_string_for_week(events_previous))
mail = mail.replace('{EVENTS_CURRENT}', create_html_string_for_week(events_current))
mail = mail.replace('{EVENTS_NEXT}', create_html_string_for_week(events_next))
quote = wikiquote.qotd(lang='fr')
mail = mail.replace('{Quote_Text}', quote[0])
mail = mail.replace('{Quote_Author}', quote[1])
return mail
def create_plain_email():
events_previous, events_current, events_next = get_events()
wk_and_span = get_week_number_and_span()
mail_plain = f'Paturlettre - Semaine {wk_and_span[0]}\n'
mail_plain += f'du {wk_and_span[1].day} {months[wk_and_span[1].month - 1]}' \
f' au {wk_and_span[2].day} {months[wk_and_span[2].month - 1]}\n'
mail_plain += '\n\n'
mail_plain += 'Semaine précédente :\n'
mail_plain += create_plain_string_for_week(events_previous)
mail_plain += '\n'
mail_plain += 'Cette semaine :\n'
mail_plain += create_plain_string_for_week(events_current)
mail_plain += '\n'
mail_plain += 'Semaine suivante :\n'
mail_plain += create_plain_string_for_week(events_next)
mail_plain += '\n\n'
quote = wikiquote.qotd(lang='fr')
mail_plain += 'Citation de la semaine :\n'
mail_plain += quote[0] + '\n'
mail_plain += f'{quote[1]}\n\n'
mail_plain += 'Cet email vous est envoyé par Cyril NOVEL parce que vous êtes inscrit sur la ' \
'liste de diffusion de la Paturlettre.\n'
mail_plain += 'Des questions ou des commentaires ? Envoyez un email à paturlettre@kosmon.fr\n'
return mail_plain
def create_html_string_for_day(day_name: str, events: list, last_day: bool) -> str:
html_str = ' <tr style="width: 100%;">\n'
html_str += f' <td class="day_row">{day_name}</td>\n'
html_str += ' </tr>\n'
for i in range(0, len(events)):
e = events[i]
style = "width: 100%;"
if not last_day and i == len(events) - 1:
style = "width: 100%; border-bottom: 1px dashed #9ba5ae;"
html_str += f' <tr style="{style}">\n'
html_str += f' <td class="genea_row"><span class="min_info"><b>{e.type_str()}</b> · {e.event_date_as_str()} </span><br />{e.event_description()}</td>\n'
html_str += ' </tr>'
return html_str
def create_html_string_for_no_event() -> str:
html_str = ' <tr style="width: 100%;">\n'
html_str += f' <td class="day_row">Pas d\'événements</td>\n'
html_str += ' </tr>\n'
return html_str
def create_plain_string_for_no_event() -> str:
return 'Pas d\'événements\n'
def create_html_string_for_week(events: list):
if not events:
return create_html_string_for_no_event()
d = {}
last_day = -1
for i in range(0, 7):
d[i] = [e for e in events if e.get_actual_weekday() == i]
if d[i]:
last_day = i
html_str = ''
for i in range(0, 7):
if d[i]:
html_str += create_html_string_for_day(week_days[i], d[i], i == last_day)
return html_str
def create_plain_string_for_week(events: list):
if not events:
return create_plain_string_for_no_event()
plain_str = ''
d = {}
for i in range(0, 7):
d[i] = [e for e in events if e.get_actual_weekday() == i]
for i in range(0, 7):
if d[i]:
plain_str += f' - {week_days[i]} :\n'
for e in d[i]:
plain_str += f' * {e.type_str()} · {e.event_date_as_str()} · ' \
f'{e.event_description()}\n'
return plain_str
def get_events():
today = date.today()
monday = today - timedelta(days=today.weekday())
previous_monday = monday - timedelta(days=7)
next_monday = monday + timedelta(days=7)
previous_week_events = create_events_from_span(previous_monday,
previous_monday + timedelta(days=6))
this_week_events = create_events_from_span(monday,
monday + timedelta(days=6))
next_week_events = create_events_from_span(next_monday,
next_monday + timedelta(days=6))
return previous_week_events, this_week_events, next_week_events
def get_week_number_and_span():
today = date.today()
monday = today - timedelta(days=today.weekday())
return today.isocalendar()[1], monday, monday + timedelta(days=6)
def main():
parser = ArgumentParser(description='Send mail')
parser.add_argument('-s', '--smtp', dest='smtp_server',
help='Json files to process, multiple values accepted')
parser.add_argument('-u', '--user', dest='user',
help='Json files to process, multiple values accepted')
parser.add_argument('-p', '--password', dest='password',
help='Json files to process, multiple values accepted')
args = parser.parse_args()
email_sender = EmailSender(args.smtp_server, args.user, args.password)
email_sender.send_paturlettre(None)
print("Done")
if __name__ == '__main__':
main()