M
M
marselabdullin2022-02-07 16:26:39
Python
marselabdullin, 2022-02-07 16:26:39

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()

Interested in the send function that takes a list of recipients and a copy of the list(msg['To'], msg['Cc']). A string is passed, for example: '[email protected]' or '[email protected]; [email protected]' (the same in mine)

Next, we run this function in a try except block:

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}")


Problem : It is necessary to catch cases when the message was not sent or only part of the recipients was sent. I would like to understand how to get the status of sending a message from the module

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2022-02-17
@Sat0shi

Send to each separately)) plus forgot to get recipients from bcc - hidden copy

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question