Answer the question
In order to leave comments, you need to log in
How to send email with attachments using Python 3.5?
#!/usr/bin/env python
# coding: utf8
from smtplib import SMTP_SSL
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os
filepath = 'file.png'
address = "[email protected]"
password = 'secret'
mail_adr = 'mail.test.ru'
mail_port = 465
# Compose attachment
part = MIMEBase('application', "octet-stream")
part.set_payload(open(filepath, "rb").read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % os.path.basename(filepath))
# Compose message
msg = MIMEMultipart()
msg['From'] = address
msg['To'] = address
msg.attach(part)
# Send mail
smtp = SMTP_SSL()
smtp.set_debuglevel(1)
smtp.connect(mail_adr, mail_port)
smtp.login(address, password)
smtp.sendmail(address, address, msg.as_string())
smtp.quit()
\n'
Traceback (most recent call last):
File "/usr/lib/python3.5/smtplib.py", line 353, in send
self.sock.sendall(s)
File "/usr/lib/python3.5/ssl.py", line 891, in sendall
v = self.send(data[count:])
File "/usr/lib/python3.5/ssl.py", line 861, in send
return self._sslobj.write(data)
File "/usr/lib/python3.5/ssl.py", line 586, in write
return self._sslobj.write(data)
ConnectionResetError: [Errno 104] Connection reset by peer
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "./mail.py", line 41, in <module>
smtp.sendmail(address, address, msg.as_string())
File "/usr/lib/python3.5/smtplib.py", line 877, in sendmail
(code, resp) = self.data(msg)
File "/usr/lib/python3.5/smtplib.py", line 567, in data
self.send(q)
File "/usr/lib/python3.5/smtplib.py", line 356, in send
raise SMTPServerDisconnected('Server not connected')
smtplib.SMTPServerDisconnected: Server not connected
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question