Last active
January 14, 2022 21:04
-
-
Save ThomasParistech/f055d17609ee78fff38c4ba0e50cf369 to your computer and use it in GitHub Desktop.
Secret Santa: email sender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# /usr/bin/python3 | |
"""Email sender.""" | |
import smtplib | |
from dataclasses import dataclass | |
from email.mime.text import MIMEText | |
from typing import Tuple, List | |
from players_info import ListOfPlayerInfo | |
@dataclass | |
class EmailSender: | |
adress: str | |
password: str | |
mail_object: str | |
mail_body: str | |
def __init__(self, adress: str, password: str, mail_txt_file: str): | |
self.adress = adress | |
self.password = password | |
with open(mail_txt_file, "r", encoding="utf-8") as _f: | |
rows = _f.readlines() | |
self.mail_object = rows[0].strip() | |
self.mail_body = "".join(rows[1:]) | |
def send_mails(self, players: ListOfPlayerInfo, links: List[Tuple[int, int]]): | |
assert len(players) == len(links) | |
for src_id, dst_id in links: | |
try: | |
server = smtplib.SMTP_SSL('smtp.gmail.com', 465) | |
server.ehlo() | |
server.login(self.adress, self.password) | |
text_type = 'plain' | |
src = players[src_id] | |
dst = players[dst_id] | |
text = self.mail_body.format(src=src.name, dst=dst.name) | |
msg = MIMEText(text, text_type, 'utf-8') | |
msg['Subject'] = self.mail_object | |
msg['From'] = self.adress | |
msg['To'] = src.email | |
server.send_message(msg) | |
server.close() | |
print(f'Email sent to {src.email}!') | |
except: | |
print(f'Failed to send email to {src.email}...') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment