简体   繁体   中英

Send email with attachment using python 3.7.3

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 te.net 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...')

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.

I tested above code and I'm posting imports that are needed (at least for attachment)

from email.mime.base import MIMEBase
from email import encoders

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM