Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (16.4k points)

I'm having issues seeing how to email an attachment utilizing Python. I have effectively messaged straightforward messages with the smtplib. Could somebody kindly disclose how to send a connection (attachment) in an email? I know there are different posts on the web however as a Python amateur I discover them difficult to comprehend.

1 Answer

0 votes
by (26.4k points)

Have a look at the below code:

import smtplib

from os.path import basename

from email.mime.application import MIMEApplication

from email.mime.multipart import MIMEMultipart

from email.mime.text import MIMEText

from email.utils import COMMASPACE, formatdate

def send_mail(send_from, send_to, subject, text, files=None,


    assert isinstance(send_to, list)

    msg = MIMEMultipart()

    msg['From'] = send_from

    msg['To'] = COMMASPACE.join(send_to)

    msg['Date'] = formatdate(localtime=True)

    msg['Subject'] = subject


    for f in files or []:

        with open(f, "rb") as fil:

            part = MIMEApplication(




        # After the file is closed

        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)


    smtp = smtplib.SMTP(server)

    smtp.sendmail(send_from, send_to, msg.as_string())


Want to learn python to get expertise in the concepts of python? Join python certification course and get certified

Related questions

0 votes
1 answer
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 22, 2020 in Azure by dante07 (13.1k points)

Browse Categories