0

I am not able to send any text or html body with an email if any attachements are there using smtplib. Body is visible/not empty if no attachment is passed.

I have tried using MIMEMultipart('alternative'), sending text as msg.attach(MIMEText(kwargs.get('text'), 'plain')) sending body as msg.attach(MIMEText(body)) and attachements as msg.attach(MIMEApplication(fil.read(),Content_Disposition='attachment; filename="%s"' % basename(f),Name=basename(f)))

The Code is as follows -

    msg = MIMEMultipart('alternative')
    author = formataddr((str(Header(header)), sender))
    msg['From'] = author
    msg['To'] = ','.join(receiver)
    msg['Subject'] = subject

    if "reply_to" in kwargs and kwargs["reply_to"]:
        msg['Reply-to'] = kwargs["reply_to"]

    if 'Bcc' in kwargs:
        if not isinstance(kwargs['Bcc'], list):
            kwargs['Bcc'] = [kwargs['Bcc']]
        receiver = receiver + kwargs['Bcc']
        msg['Bcc'] = ','.join(kwargs['Bcc'])

    if 'Cc' in kwargs:
        if not isinstance(kwargs['Cc'], list):
            kwargs['Cc'] = [kwargs['Cc']]
        receiver = receiver + kwargs['Cc']
        msg['Cc'] = ','.join(kwargs['Cc'])

    if 'text' in kwargs:
        msg.attach(MIMEText(kwargs.get('text'), 'plain'))

    if body != []:
        if 'mime_only' in kwargs and kwargs['mime_only']:
            msg.attach(MIMEText(body))
        else:
            msg.attach(MIMEText(body, 'html'))

    if 'files' in kwargs:
        files = kwargs['files']
        for f in files:
            with open(f, "rb") as fil:
                msg.attach(MIMEApplication(
                    fil.read(),
                    Content_Disposition='attachment; filename="%s"' % basename(f),
                    Name=basename(f)
                ))

All the parts are working indivisually, ie - I am able to send text emails, html emails and attachements, but not HTML or text with attachements.

One thing I noticed is when I receive the mail on gmail it does show the body content before I click on the mail(in the notification/summary) but body is not there when I click on it or open it.

  • 1
    Possible duplicate of [Sending HTML email using Python](https://stackoverflow.com/questions/882712/sending-html-email-using-python) – The Pjot Apr 24 '19 at 12:39
  • I can't reproduce this, but there is so much branching in your code it's difficult to be sure what set of conditions might trigger this behaviour. Please provide an [mcve], including a minimal html body, that reproduces the problem. – snakecharmerb Apr 27 '19 at 10:32
  • @ThePjot Checked that, still the issue is coming, not able to solve it still. – user7104253 May 07 '19 at 09:43

0 Answers0