''' This program is the emailing system ''' import ssl import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import settings class Mail: ''' Sets up email and sends it. ''' def __init__(self): self.email = settings.EMAIL self.password = settings.PASSWORD self.message = MIMEMultipart() def set_credentials(self, receiver_email: str, title: str): ''' Sets credentials for emailing the user. ''' self.message['From'] = self.email self.message['To'] = receiver_email self.message['Subject'] = title self.message['Bcc'] = receiver_email def set_body_and_file(self, body: str, filename: str): ''' Sets the body and attaches files to the message. ''' self.message.attach(MIMEText(body, 'plain')) self.message.attach(Mail.encode_file(filename)) self.text = self.message.as_string() @staticmethod def encode_file(filename: str) -> MIMEBase: ''' Reads, encodes and attaches files to have them sent in the email''' with open(filename, 'rb') as attachment: part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header( 'Content-Disposition', f'attachment; filename= {filename}' ) return part def email_person(self, user_email: str): ''' Emails someone with a message ''' port = 465 context = ssl.create_default_context() with smtplib.SMTP_SSL('smtp.gmail.com', port, context=context) as server: server.login(self.email, self.password) server.sendmail( self.email, user_email, self.text )