0

Hi all I am new to python. I am trying to send an image to my gmail account and getting the below error can someone help me with this. I have searched and searched and can't find an answer I have tried changing the port.

I have turned on the google less secure apps and not sure what else to do.

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import os

gmail_user = "you@gmail.com"
gmail_pwd = "pass"

to = "you@gmail.com"
subject = "Report"
text = "Picture report"
attach = 'web.png'

msg = MIMEMultipart()

msg['From'] = gmail_user
msg['To'] = to
msg['Subject'] = subject

msg.attach(MIMEText(text))

part = MIMEBase('application', 'octet-stream')
part.set_payload(open(attach, 'rb').read())
encoders.encode_base64(part)
part.add_header('Content-Disposition',
   'attachment; filename="%s"' % os.path.basename(attach))
msg.attach(part)

mailServer = smtplib.SMTP("smtp.gmail.com", 465)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmail_user, gmail_pwd)
mailServer.sendmail(gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()  

  Traceback (most recent call last):
  File "C:\Users\scott\Desktop\PYTHON NEW\newemail.py", line 31, in <module>
    mailServer = smtplib.SMTP("smtp.gmail.com", 465)
  File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 251, in __init__
    (code, msg) = self.connect(host, port)
  File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 337, in connect
    (code, msg) = self.getreply()
  File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 393, in getreply
    raise SMTPServerDisconnected("Connection unexpectedly closed")
smtplib.SMTPServerDisconnected: Connection unexpectedly closed

i have changed the port to 587 and got a different error

Traceback (most recent call last):
  File "C:\Users\scott\Desktop\PYTHON NEW\newemail.py", line 35, in <module>
    mailServer.login(gmail_user, gmail_pwd)
  File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 729, in login
    raise last_exception
  File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 720, in login
    initial_response_ok=initial_response_ok)
  File "C:\Users\scott\AppData\Local\Programs\Python\Python36-32\lib\smtplib.py", line 641, in auth
    raise SMTPAuthenticationError(code, resp)
smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbt4\n5.7.14 ah5smKPNBMdR8EDhHji_lOLermVkofD0XZiYZtx04cUZGJIvjm6scA9FeCEhJhB--aeW58\n5.7.14 O3uS9IVuNfqKe4HYqXgdBMbvtMSOSSMM4oGYwlvDIoXpIK0IJYKSyAfvPyPcjiF8Q_Es4n\n5.7.14 33gUceqr9ZjlNI066kXt-uTq2V39X6YUS2-ixCCKfoozS9zoQ1KJuLSWU1IhB3gTsGtB9m\n5.7.14 N-AEdgucbByvuI7zr2KG-DZwlvrWw> Please log in via your web browser and\n5.7.14 then try again.\n5.7.14  Learn more at\n5.7.14  https://support.google.com/mail/answer/78754 b65sm27550600wrd.26 - gsmtp')
scott.turner
  • 69
  • 1
  • 2
  • 6
  • Possible duplicate of [SMTPAuthenticationError when sending mail using gmail and python](https://stackoverflow.com/questions/26852128/smtpauthenticationerror-when-sending-mail-using-gmail-and-python) – tripleee Feb 15 '18 at 12:54

3 Answers3

2

Your code can be shortened down to just two lines:

import smtplib
mailServer = smtplib.SMTP("smtp.gmail.com", 465)

And if you get smtplib.SMTPServerDisconnected, this means that your question is not about the code. Something is blocking your network connection to port 465.

ababak
  • 1,685
  • 1
  • 11
  • 23
  • P.S. Check this question for more info: https://stackoverflow.com/questions/10147455/how-to-send-an-email-with-gmail-as-provider-using-python – ababak Feb 15 '18 at 11:57
0

A SMTP server on port 465 is listening for encrypted TLS connections. The client is not supposed to start the encryption with STARTTLS, because TLS is active from the beginning. That SMTP command is used on port 587 where SMTP servers are listening for plaintext connections.

VPfB
  • 14,927
  • 6
  • 41
  • 75
  • hi i changed the port and i got a different error i have put it above – scott.turner Feb 15 '18 at 11:57
  • @scott.turner There are instructions from google in the error message. Did you try to follow them? – VPfB Feb 15 '18 at 12:48
  • hi yeah i tried the web page in the error and says the page is not found – scott.turner Feb 15 '18 at 13:05
  • I can reach that page: https://support.google.com/mail/answer/78754 Anyway, after solving the issue with wrong port you are now having another problem that I don't know how to solve. The DSN code 5.7.14 means _Undelivered: 'trust relationship' required_, so your code might be OK. – VPfB Feb 15 '18 at 13:45
  • thank you i have sorted it, it was somethink to do with the security on my works internet. cheer – scott.turner Feb 15 '18 at 14:16
-3

you can use flask_mail library for sending mail.Here is just quick review.. '

from flask_mail import Mail, Message
app.config['SECRET_KEY'] = 'your secretkey'
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 465
app.config['MAIL_USE_TLS'] = False
app.config['MAIL_USE_SSL'] = True
app.config['MAIL_USERNAME'] = 'your gmail id'
app.config['MAIL_PASSWORD'] = 'and its password'
mail = Mail(app)
msg = Message(subject=subject, sender=(master().user(), 
app.config['MAIL_USERNAME']), recipients=[recipients])
msg.body = "%s %s" % (body, msg.sender)
if html is not None:
    msg.html = str(html)
mail.connect()
mail.send(msg)

'

***Note :- do not forget to turn off 2-step verification and also turn on Allow less secure apps from sign-in & security > device activity & security events

Smit Mehta
  • 91
  • 9
  • An extension to a web app framework is not the right tool. – VPfB Feb 15 '18 at 12:53
  • why???? because i think its good to use already implemented code it saves our time ..@vpfb – Smit Mehta Feb 16 '18 at 07:05
  • 1
    The code above is not complete. Just try to make it work. Normally you need `flask` to create the `app` object. `flask` consists of several libraries (with many thousands lines of code each) fully unrelated to the task of sending an email message. In my understanding that is wasting of resources, not saving time. – VPfB Feb 16 '18 at 07:33
  • but it also work in my project for that i created a controller...and using ajax to send mail data...and what i think is it will better then flask_mail – Smit Mehta Feb 16 '18 at 10:05