Send email with attachment using python 3.7.3

Viewed 75

I am running a python script using python 3.7.3. Below is the code. This is not doing anything. It just displays message "Email Sent" and does not actually sends an email.

This code used to work with Python 2.7 previously with only change of "multipart" to "Multipart". I had to change the M to m as it was throwing an error. Now, it does not throw that error.

I have checked telnet on machine is up.

telnet localhost 11
Trying 111.1.1.1.......
Connected to localhost.
Escape character is '^]'.
220 abcdef.com ESMTP Exim 4.92 Tue, 09 Nov 2021 11:19:10 -0500
quit

 telnet
telnet> quit

Please Help. Thank you in advance.

#Send email with attachment

sender = 'abc@test.com'
receivers = 'xyz@test.com'



msg = email.mime.multipart.MIMEMultipart()
msg['Subject'] = 'Test script'
msg['From'] = 'abc@test.com'
msg['To'] = 'xyz@test.com'


# The main body is just another attachment
body = email.mime.text.MIMEText("""Please find the updated data in attached csv""")
msg.attach(body)

# CSV attachment
filename='/home/abc/python_scripts/test.csv'
with open(filename, "rb") as fs:
    part = MIMEBase('application', "octet-stream")
    part.set_payload(fs.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment', filename=os.path.basename(filename))
msg.attach(part)

try:

    server = smtplib.SMTP('localhost',11)
    server.sendmail(sender, receivers, msg.as_string())
    server.close()

    print('Email Sent')

except SMTPException:
    print('Something went wrong...')
1 Answers

Above script works just fine. It seems the server wasn't setup properly to send emails from "@test.com". Please feel free to use above code in your script.

Related