Answer the question
In order to leave comments, you need to log in
How to check all recipients of SMTP MIMEMultipart messages?
There is a class implemented based on the MIMEMultipart module:
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
class SendMessage(object):
def __init__(self, host, port, send_from, send_to):
self.host = host
self.port = port
self.send_from = send_from
self.send_to = send_to
def __enter__(self):
self.server = smtplib.SMTP(host=self.host, port=self.port)
self.server.starttls()
return self
def send(self, task, message, filelist=None, Subject=None, copy_to=None, msg_type=None):
# attach message
msg = MIMEMultipart(border = ';')
msg['From'] = self.send_from
msg['To'] = self.send_to
msg['CC'] = copy_to
if Subject is None:
msg['Subject'] = "Airflow result, dag: {task}.".format(task=task)
else:
msg['Subject'] = Subject
if msg_type == None:
msg.attach(MIMEText(message, 'plain'))
elif msg_type == 'html':
msg.attach(MIMEText(message, 'html'))
# attach file
if filelist is not None:
for file in filelist:
part = MIMEBase('application', "octet-stream")
part.set_payload(open(file, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=file)
msg.attach(part)
self.server.send_message(msg)
def __exit__(self, type, value, traceback):
self.server.quit()
send_args = {
"host": 'exch.mail.local',
"port": 25,
"send_from": '[email protected]',
"send_to": '[email protected]; [email protected]'
}
try:
with SendMessage(**send_args) as email_host:
email_host.send(task=None, message='lol', Subject='lol', msg_type=msg_type)
print('Message Send')
except Exception as err:
print(f"Ошибка отправки сообщения: {err}")
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question