Home > OS >  Sending message with attachment in email BytesIO doesn't work - No errors shown - Python/Smtp/E
Sending message with attachment in email BytesIO doesn't work - No errors shown - Python/Smtp/E

Time:05-13

I am trying to add attachment to the object created below and stored as email. It's all done within a class and this is how the class is initialised:

class <name>:
    def __init__(self, **kwargs):
        self.msg = kwargs.get("msg", MIMEMultipart())
        self.subject = kwargs.get("subject", None)
        self.body = kwargs.get("body", None)
        self.attachment = kwargs.get("attachment", None)

Attachment is not being sent

The attachments works fine as long as the attachment is of the type str. Add other functionalities of adding body, subject, etc. works fine. When I pass a BytesIO() type object, the mail gets sent without any errors or warnings, but the attachment is not being sent.

for i ,attachment in enumerate(self.attachment,start=1):
            p = MIMEBase('application', 'octet-stream')
            if isinstance(attachment, str):
                p.set_payload(open(attachment,"rb").read())
            else:
                p.set_payload((attachment).read())
            encoders.encode_base64(p)
            p.add_header('Content-Disposition', "attachment", filename= f'attachment{i}.jpg')
            self.msg.attach(p)

Why am I using BytesIO() in the first place?

Well, I am trying to send a QR Image, which is saved using

qr_img.save(BytesIO(),format="png")

I am trying to send the image generated from qrcode module without saving it locally.

Message is sent like this:

self.server.send_message(msg)

Where self.server is the smtplib.SMTP_SSL() object.

Any help is appreciated, thanks!

CodePudding user response:

The issue was that the buffer values were not read using .read() method. Using the .getvalue() method instead worked for me.

Note: No errors are thrown when using .read().

  • Related