Вы можете использовать smtplib
.Ниже приведена реализация простой системы уведомлений, использующей класс для использования чистого поведения менеджера контекста:
import datetime
import smtplib, csv
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email import Encoders
class SendEmail:
def __init__(self, _to, _from = 'youremail@domaim.com', subject = 'Happy Birthday!', attachment = 'birthday.jpg'):
self._to = _to
self._from = _from
self._subject = subject
self.attachment = attachment
def __enter__(self):
msg = MIMEMultipart()
for part in ['Subject', 'From', 'To']:
msg[part] = getattr(self, f'_{i.lower()}')
part = MIMEBase('application', "octet-stream")
part.set_payload(open(self.attachment, "rb").read())
Encoders.encode_base64(part)
part.add_header('Content-Disposition', f'attachment; filename="{self.attachment}"')
msg.attach(part)
server = smtplib.SMTP(self.EMAIL_SERVER)
server.sendmail(self.EMAIL_FROM, self.EMAIL_TO, msg.as_string())
return self
def __exit__(self, *args):
pass
@classmethod
def send_bulk(cls, users:list):
for date, name, email in users:
_d = datetime.datetime.now()
if _d.month in date and _d.day in date:
with cls(email, subject = f'Happy Birthday, {name}!') as f:
pass
with open('filename.csv') as f:
SendEmail.send_bulk(csv.reader(f))