V
V
Vlad2016-12-05 11:22:25
Python
Vlad, 2016-12-05 11:22:25

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()

When executing the code, everything goes without problems until the line
smtp.sendmail(address, address, msg.as_string())
and an error pops up
\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

Mail server - corporate on ESMTP Postfix.
I tried different files, not only PNG but also text files, and even the same Python-e script - the error is the same.
Python 3.5 is in virtualenv.
At what messages without attachments leave and come normally.
In what a problem I can not understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2016-12-11
@dimonchik2013

1) check with GMail
2) talk to admin or read RFC and postfix settings

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question