I used to use auto discover to retrieve some emails from my inbox using exchangelib. However, last week they updated my email and auto discover is not working anymore. Now I am testing the connection with SMTPLIB using SMTP_SSL
server = smtplib.SMTP_SSL('xxxxxxxx.com',port=25)
but I get
ConnectionRefusedError: [WinError 10061]
c:\python37\lib\smtplib.py in __init__(self, host, port, local_hostname, keyfile, certfile, timeout, source_address, context)
1029 self.context = context
1030 SMTP.__init__(self, host, port, local_hostname, timeout,
-> 1031 source_address)
1032
1033 def _get_socket(self, host, port, timeout):
c:\python37\lib\smtplib.py in __init__(self, host, port, local_hostname, timeout, source_address)
249
250 if host:
--> 251 (code, msg) = self.connect(host, port)
252 if code != 220:
253 self.close()
c:\python37\lib\smtplib.py in connect(self, host, port, source_address)
334 if self.debuglevel > 0:
335 self._print_debug('connect:', (host, port))
--> 336 self.sock = self._get_socket(host, port, self.timeout)
337 self.file = None
338 (code, msg) = self.getreply()
c:\python37\lib\smtplib.py in _get_socket(self, host, port, timeout)
1035 self._print_debug('connect:', (host, port))
1036 new_socket = socket.create_connection((host, port), timeout,
-> 1037 self.source_address)
1038 new_socket = self.context.wrap_socket(new_socket,
1039 server_hostname=self._host)
c:\python37\lib\socket.py in create_connection(address, timeout, source_address)
725
726 if err is not None:
--> 727 raise err
728 else:
729 raise error("getaddrinfo returns an empty list")
c:\python37\lib\socket.py in create_connection(address, timeout, source_address)
714 if source_address:
715 sock.bind(source_address)
--> 716 sock.connect(sa)
717 # Break explicitly a reference cycle
718 err = None
ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it
When I used auto discover on exchangelib I got
AutoDiscoverFailed Traceback (most recent call last)
<ipython-input-48-c03f25ef8bb7> in <module>
5 autodiscover=True,
6 # config=self.config,
----> 7 access_type=DELEGATE
8 )
c:\python37\lib\site-packages\exchangelib\account.py in __init__(self, primary_smtp_address, fullname, access_type, autodiscover, credentials, config, locale, default_timezone)
78 raise AttributeError('config is ignored when autodiscover is active')
79 self.primary_smtp_address, self.protocol = discover(email=self.primary_smtp_address,
---> 80 credentials=credentials)
81 else:
82 if not config:
c:\python37\lib\site-packages\exchangelib\autodiscover.py in discover(email, credentials)
221 # We fell out of the with statement, so either cache was filled by someone else, or autodiscover redirected us to
222 # another email address. Start over after releasing the lock.
--> 223 return discover(email=email, credentials=credentials)
224
225
c:\python37\lib\site-packages\exchangelib\autodiscover.py in discover(email, credentials)
211 try:
212 # This eventually fills the cache in _autodiscover_hostname
--> 213 return _try_autodiscover(hostname=domain, credentials=credentials, email=email)
214 except AutoDiscoverRedirect as e:
215 if email.lower() == e.redirect_email.lower():
c:\python37\lib\site-packages\exchangelib\autodiscover.py in _try_autodiscover(hostname, credentials, email)
259 ), None)
260 log.info('autodiscover.%s redirected us to %s', hostname, e.server)
--> 261 return _try_autodiscover(e.server, credentials, email)
262 except AutoDiscoverFailed as e:
263 log.info('Autodiscover on autodiscover.%s (no TLS) failed (%s). Trying DNS records', hostname, e)
c:\python37\lib\site-packages\exchangelib\autodiscover.py in _try_autodiscover(hostname, credentials, email)
277 return _try_autodiscover(hostname=hostname_from_dns, credentials=credentials, email=email)
278 except AutoDiscoverFailed:
--> 279 raise_from(AutoDiscoverFailed('All steps in the autodiscover protocol failed'), None)
280
281
c:\python37\lib\site-packages\future\utils\__init__.py in raise_from(exc, cause)
398 myglobals['__python_future_raise_from_cause'] = cause
399 execstr = "raise __python_future_raise_from_exc from __python_future_raise_from_cause"
--> 400 exec(execstr, myglobals, mylocals)
401
402 def raise_(tp, value=None, tb=None):
c:\python37\lib\site-packages\exchangelib\autodiscover.py in <module>
AutoDiscoverFailed: All steps in the autodiscover protocol failed
I don't know how to deal with these exceptions
Related
I have read quite a few posts around this but couldn't find a resolution. I am able to read from Postgres but getting a connection time out error when I use create_engine string. I know the credentials are correct because I can read from PostGres.
My aim is to write dataframe (df) to postgres directly from Python and going forward keep appending the rows to that table. I have changed the password and the IP address in the example below. Not sure if this is relevant but I am using Tunnel in Putty to connect to remote server and launch Jupyter notebook and then trying to write to Postgres DB.
My code
from sqlalchemy import create_engine
import psycopg2
import io
password = 'Pas#$tk$#a' #This is just an example. MY password has special characters
engine = create_engine('postgresql+psycopg2://admin:password#1.12.11.1:5432/DEV_Sach_D', connect_args={'sslmode':'require'}, echo=True).connect() # I have changed the IP here for security reasons
conn = engine.connect()
df.to_sql('py_stg_test', con=conn, if_exists='replace',index=False)
Error I get
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _wrap_pool_connect(self, fn, connection)
3211 try:
-> 3212 return fn()
3213 except dialect.dbapi.Error as e:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in connect(self)
306 """
--> 307 return _ConnectionFairy._checkout(self)
308
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in _checkout(cls, pool, threadconns, fairy)
766 if not fairy:
--> 767 fairy = _ConnectionRecord.checkout(pool)
768
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in checkout(cls, pool)
424 def checkout(cls, pool):
--> 425 rec = pool._do_get()
426 try:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/impl.py in _do_get(self)
145 with util.safe_reraise():
--> 146 self._dec_overflow()
147 else:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/langhelpers.py in __exit__(self, type_, value, traceback)
71 exc_value,
---> 72 with_traceback=exc_tb,
73 )
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py in raise_(***failed resolving arguments***)
206 try:
--> 207 raise exception
208 finally:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/impl.py in _do_get(self)
142 try:
--> 143 return self._create_connection()
144 except:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in _create_connection(self)
252
--> 253 return _ConnectionRecord(self)
254
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in __init__(self, pool, connect)
367 if connect:
--> 368 self.__connect()
369 self.finalize_callback = deque()
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in __connect(self)
610 with util.safe_reraise():
--> 611 pool.logger.debug("Error on connect(): %s", e)
612 else:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/langhelpers.py in __exit__(self, type_, value, traceback)
71 exc_value,
---> 72 with_traceback=exc_tb,
73 )
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py in raise_(***failed resolving arguments***)
206 try:
--> 207 raise exception
208 finally:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in __connect(self)
604 self.starttime = time.time()
--> 605 connection = pool._invoke_creator(self)
606 pool.logger.debug("Created new connection %r", connection)
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/create.py in connect(connection_record)
577 return connection
--> 578 return dialect.connect(*cargs, **cparams)
579
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/default.py in connect(self, *cargs, **cparams)
583 # inherits the docstring from interfaces.Dialect.connect
--> 584 return self.dbapi.connect(*cargs, **cparams)
585
/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
121 dsn = _ext.make_dsn(dsn, **kwargs)
--> 122 conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
123 if cursor_factory is not None:
OperationalError: could not connect to server: Connection timed out
Is the server running on host "1.12.11.1" and accepting
TCP/IP connections on port 5432?
The above exception was the direct cause of the following exception:
OperationalError Traceback (most recent call last)
<ipython-input-5-28cdb6a0c387> in <module>()
4 password = Pas#$tk$#a'
5
----> 6 engine = create_engine('postgresql+psycopg2://libertypassageadminuser#libertypassage:password#1.12.11.1:5432/Dev_Sach_D, connect_args={'sslmode':'require'}, echo=True).connect()
7 conn = engine.connect()
8 df.to_sql('py_stg_test', con=conn, if_exists='replace',index=False)
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in connect(self, close_with_result)
3164 """
3165
-> 3166 return self._connection_cls(self, close_with_result=close_with_result)
3167
3168 #util.deprecated(
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in __init__(self, engine, connection, close_with_result, _branch_from, _execution_options, _dispatch, _has_events, _allow_revalidate)
94 connection
95 if connection is not None
---> 96 else engine.raw_connection()
97 )
98
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in raw_connection(self, _connection)
3243
3244 """
-> 3245 return self._wrap_pool_connect(self.pool.connect, _connection)
3246
3247
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _wrap_pool_connect(self, fn, connection)
3214 if connection is None:
3215 Connection._handle_dbapi_exception_noconnection(
-> 3216 e, dialect, self
3217 )
3218 else:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _handle_dbapi_exception_noconnection(cls, e, dialect, engine)
2068 elif should_wrap:
2069 util.raise_(
-> 2070 sqlalchemy_exception, with_traceback=exc_info[2], from_=e
2071 )
2072 else:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py in raise_(***failed resolving arguments***)
205
206 try:
--> 207 raise exception
208 finally:
209 # credit to
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/base.py in _wrap_pool_connect(self, fn, connection)
3210 dialect = self.dialect
3211 try:
-> 3212 return fn()
3213 except dialect.dbapi.Error as e:
3214 if connection is None:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in connect(self)
305
306 """
--> 307 return _ConnectionFairy._checkout(self)
308
309 def _return_conn(self, record):
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in _checkout(cls, pool, threadconns, fairy)
765 def _checkout(cls, pool, threadconns=None, fairy=None):
766 if not fairy:
--> 767 fairy = _ConnectionRecord.checkout(pool)
768
769 fairy._pool = pool
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in checkout(cls, pool)
423 #classmethod
424 def checkout(cls, pool):
--> 425 rec = pool._do_get()
426 try:
427 dbapi_connection = rec.get_connection()
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/impl.py in _do_get(self)
144 except:
145 with util.safe_reraise():
--> 146 self._dec_overflow()
147 else:
148 return self._do_get()
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/langhelpers.py in __exit__(self, type_, value, traceback)
70 compat.raise_(
71 exc_value,
---> 72 with_traceback=exc_tb,
73 )
74 else:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py in raise_(***failed resolving arguments***)
205
206 try:
--> 207 raise exception
208 finally:
209 # credit to
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/impl.py in _do_get(self)
141 if self._inc_overflow():
142 try:
--> 143 return self._create_connection()
144 except:
145 with util.safe_reraise():
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in _create_connection(self)
251 """Called by subclasses to create a new ConnectionRecord."""
252
--> 253 return _ConnectionRecord(self)
254
255 def _invalidate(self, connection, exception=None, _checkin=True):
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in __init__(self, pool, connect)
366 self.__pool = pool
367 if connect:
--> 368 self.__connect()
369 self.finalize_callback = deque()
370
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in __connect(self)
609 except Exception as e:
610 with util.safe_reraise():
--> 611 pool.logger.debug("Error on connect(): %s", e)
612 else:
613 # in SQLAlchemy 1.4 the first_connect event is not used by
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/langhelpers.py in __exit__(self, type_, value, traceback)
70 compat.raise_(
71 exc_value,
---> 72 with_traceback=exc_tb,
73 )
74 else:
/usr/local/lib/python3.6/dist-packages/sqlalchemy/util/compat.py in raise_(***failed resolving arguments***)
205
206 try:
--> 207 raise exception
208 finally:
209 # credit to
/usr/local/lib/python3.6/dist-packages/sqlalchemy/pool/base.py in __connect(self)
603 try:
604 self.starttime = time.time()
--> 605 connection = pool._invoke_creator(self)
606 pool.logger.debug("Created new connection %r", connection)
607 self.connection = connection
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/create.py in connect(connection_record)
576 if connection is not None:
577 return connection
--> 578 return dialect.connect(*cargs, **cparams)
579
580 creator = pop_kwarg("creator", connect)
/usr/local/lib/python3.6/dist-packages/sqlalchemy/engine/default.py in connect(self, *cargs, **cparams)
582 def connect(self, *cargs, **cparams):
583 # inherits the docstring from interfaces.Dialect.connect
--> 584 return self.dbapi.connect(*cargs, **cparams)
585
586 def create_connect_args(self, url):
/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
120
121 dsn = _ext.make_dsn(dsn, **kwargs)
--> 122 conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
123 if cursor_factory is not None:
124 conn.cursor_factory = cursor_factory
OperationalError: (psycopg2.OperationalError) could not connect to server: Connection timed out
Is the server running on host "1.12.11.1" and accepting
TCP/IP connections on port 5432?
(Background on this error at: https://sqlalche.me/e/14/e3q8)
Very silly of me. I was using the wrong IP in the string. Instead of using POSTGRES DB name I was using the IP of the machine itself.
Thanks to all who answered.
On Udemy, the instructor is showing us how to use SMTP. I am using Jupyter Notebook (I know it's just to learn the basics then I am going to switch over to an IDE) and Anaconda (Python). When I run this I get these errors. (This happens with no port numbers, and the 2 port numbers our teacher told us 587,465. I also turned off windows firewall when doing this because that might have been interfering but it still didn't work.
Port Number 465
```smtp_object = smtplib.SMTP('smtp.gamil.com',465)
---------------------------------------------------------------------------
gaierror Traceback (most recent call last)
<ipython-input-10-cf67d6421353> in <module>
----> 1 smtp_object = smtplib.SMTP('smtp.gamil.com',465)
C:\ProgramData\Anaconda3\lib\smtplib.py in __init__(self, host, port, local_hostname, timeout, source_address)
249
250 if host:
--> 251 (code, msg) = self.connect(host, port)
252 if code != 220:
253 self.close()
C:\ProgramData\Anaconda3\lib\smtplib.py in connect(self, host, port, source_address)
334 if self.debuglevel > 0:
335 self._print_debug('connect:', (host, port))
--> 336 self.sock = self._get_socket(host, port, self.timeout)
337 self.file = None
338 (code, msg) = self.getreply()
enter code here
C:\ProgramData\Anaconda3\lib\smtplib.py in _get_socket(self, host, port, timeout)
305 self._print_debug('connect: to', (host, port), self.source_address)
306 return socket.create_connection((host, port), timeout,
--> 307 self.source_address)
308
309 def connect(self, host='localhost', port=0, source_address=None):
C:\ProgramData\Anaconda3\lib\socket.py in create_connection(address, timeout, source_address)
705 host, port = address
706 err = None
--> 707 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
708 af, socktype, proto, canonname, sa = res
709 sock = None
C:\ProgramData\Anaconda3\lib\socket.py in getaddrinfo(host, port, family, type, proto, flags)
750 # and socket type values to enum constants.
751 addrlist = []
--> 752 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
753 af, socktype, proto, canonname, sa = res
754 addrlist.append((_intenum_converter(af, AddressFamily),
gaierror: [Errno 11001] getaddrinfo failed```
Port number 587
```smtp_object = smtplib.SMTP('smtp.gamil.com',587)
---------------------------------------------------------------------------
gaierror Traceback (most recent call last)
<ipython-input-13-40083b789b9c> in <module>
----> 1 smtp_object = smtplib.SMTP('smtp.gamil.com',587)
C:\ProgramData\Anaconda3\lib\smtplib.py in __init__(self, host, port, local_hostname, timeout, source_address)
249
250 if host:
--> 251 (code, msg) = self.connect(host, port)
252 if code != 220:
253 self.close()
C:\ProgramData\Anaconda3\lib\smtplib.py in connect(self, host, port, source_address)
334 if self.debuglevel > 0:
335 self._print_debug('connect:', (host, port))
--> 336 self.sock = self._get_socket(host, port, self.timeout)
337 self.file = None
338 (code, msg) = self.getreply()
C:\ProgramData\Anaconda3\lib\smtplib.py in _get_socket(self, host, port, timeout)
305 self._print_debug('connect: to', (host, port), self.source_address)
306 return socket.create_connection((host, port), timeout,
--> 307 self.source_address)
308
309 def connect(self, host='localhost', port=0, source_address=None):
C:\ProgramData\Anaconda3\lib\socket.py in create_connection(address, timeout, source_address)
705 host, port = address
706 err = None
--> 707 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
708 af, socktype, proto, canonname, sa = res
709 sock = None
C:\ProgramData\Anaconda3\lib\socket.py in getaddrinfo(host, port, family, type, proto, flags)
750 # and socket type values to enum constants.
751 addrlist = []
--> 752 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
753 af, socktype, proto, canonname, sa = res
754 addrlist.append((_intenum_converter(af, AddressFamily),
gaierror: [Errno 11001] getaddrinfo failed```
No Port Number
```smtp_object = smtplib.SMTP('smtp.gamil.com')
---------------------------------------------------------------------------
gaierror Traceback (most recent call last)
<ipython-input-14-1655d3855dcf> in <module>
----> 1 smtp_object = smtplib.SMTP('smtp.gamil.com')
C:\ProgramData\Anaconda3\lib\smtplib.py in __init__(self, host, port, local_hostname, timeout, source_address)
249
250 if host:
--> 251 (code, msg) = self.connect(host, port)
252 if code != 220:
253 self.close()
C:\ProgramData\Anaconda3\lib\smtplib.py in connect(self, host, port, source_address)
334 if self.debuglevel > 0:
335 self._print_debug('connect:', (host, port))
--> 336 self.sock = self._get_socket(host, port, self.timeout)
337 self.file = None
338 (code, msg) = self.getreply()
C:\ProgramData\Anaconda3\lib\smtplib.py in _get_socket(self, host, port, timeout)
305 self._print_debug('connect: to', (host, port), self.source_address)
306 return socket.create_connection((host, port), timeout,
--> 307 self.source_address)
308
309 def connect(self, host='localhost', port=0, source_address=None):
C:\ProgramData\Anaconda3\lib\socket.py in create_connection(address, timeout, source_address)
705 host, port = address
706 err = None
--> 707 for res in getaddrinfo(host, port, 0, SOCK_STREAM):
708 af, socktype, proto, canonname, sa = res
709 sock = None
C:\ProgramData\Anaconda3\lib\socket.py in getaddrinfo(host, port, family, type, proto, flags)
750 # and socket type values to enum constants.
751 addrlist = []
--> 752 for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
753 af, socktype, proto, canonname, sa = res
754 addrlist.append((_intenum_converter(af, AddressFamily),
gaierror: [Errno 11001] getaddrinfo failed```
I am trying to load an excel file into a database for which I have to first connect to my SQL server using python. MYSQL server is already running in the background. Now when I try to run this code:
import xlrd
import pymysql
xl_data = xlrd.open_workbook('C:/Users/xxx/Desktop/xyz.xlsx')
mydb = pymysql.connect( host = 'localhost' , user ="x" , passwd = "x" , db = "")
cursor = mydb.cursor()
I get the following error:
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
<ipython-input-2-d43a74bc83ce> in <module>
3
4 xl_data = xlrd.open_workbook('C:/Users/Sankalp/Desktop/Problem_Sample Linkedin Data.xlsx')
----> 5 mydb = pymysql.connect( host = 'localhost' , user ="x" , passwd = "x" , db = "")
6 cursor = mydb.cursor()
D:\Softwares\Anaconda\lib\site-packages\pymysql\__init__.py in Connect(*args, **kwargs)
92 """
93 from .connections import Connection
---> 94 return Connection(*args, **kwargs)
95
96 from . import connections as _orig_conn
D:\Softwares\Anaconda\lib\site-packages\pymysql\connections.py in __init__(self, host, user, password, database, port, unix_socket, charset, sql_mode, read_default_file, conv, use_unicode, client_flag, cursorclass, init_command, connect_timeout, ssl, read_default_group, compress, named_pipe, autocommit, db, passwd, local_infile, max_allowed_packet, defer_connect, auth_plugin_map, read_timeout, write_timeout, bind_address, binary_prefix, program_name, server_public_key)
323 self._sock = None
324 else:
--> 325 self.connect()
326
327 def _create_ssl_ctx(self, sslp):
D:\Softwares\Anaconda\lib\site-packages\pymysql\connections.py in connect(self, sock)
597
598 self._get_server_information()
--> 599 self._request_authentication()
600
601 if self.sql_mode is not None:
D:\Softwares\Anaconda\lib\site-packages\pymysql\connections.py in _request_authentication(self)
869 plugin_name = auth_packet.read_string()
870 if self.server_capabilities & CLIENT.PLUGIN_AUTH and plugin_name is not None:
--> 871 auth_packet = self._process_auth(plugin_name, auth_packet)
872 else:
873 # send legacy handshake
D:\Softwares\Anaconda\lib\site-packages\pymysql\connections.py in _process_auth(self, plugin_name, auth_packet)
900 return _auth.caching_sha2_password_auth(self, auth_packet)
901 elif plugin_name == b"sha256_password":
--> 902 return _auth.sha256_password_auth(self, auth_packet)
903 elif plugin_name == b"mysql_native_password":
904 data = _auth.scramble_native_password(self.password, auth_packet.read_all())
D:\Softwares\Anaconda\lib\site-packages\pymysql\_auth.py in sha256_password_auth(conn, pkt)
181 data = b''
182
--> 183 return _roundtrip(conn, data)
184
185
D:\Softwares\Anaconda\lib\site-packages\pymysql\_auth.py in _roundtrip(conn, send_data)
120 def _roundtrip(conn, send_data):
121 conn.write_packet(send_data)
--> 122 pkt = conn._read_packet()
123 pkt.check_error()
124 return pkt
D:\Softwares\Anaconda\lib\site-packages\pymysql\connections.py in _read_packet(self, packet_type)
682
683 packet = packet_type(buff, self.encoding)
--> 684 packet.check_error()
685 return packet
686
D:\Softwares\Anaconda\lib\site-packages\pymysql\protocol.py in check_error(self)
218 errno = self.read_uint16()
219 if DEBUG: print("errno =", errno)
--> 220 err.raise_mysql_exception(self._data)
221
222 def dump(self):
D:\Softwares\Anaconda\lib\site-packages\pymysql\err.py in raise_mysql_exception(data)
107 errval = data[3:].decode('utf-8', 'replace')
108 errorclass = error_map.get(errno, InternalError)
--> 109 raise errorclass(errno, errval)
**OperationalError: (1045, "Access denied for user 'x'#'localhost' (using password: YES)")**
How to rectify this error? Can anyone help?
Is it the permissions problem? Or incorrect details?
I need a heads up.
Thanks!
I am trying to use 'mailgun' and gmail mail to send emails from my Django application, but each time I receive an error.
In my application I have the following code:
settings.py
EMAIL_HOST = 'smtp.mailgun.org'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'aaa#mg.xxx.com'
EMAIL_HOST_PASSWORD = '#########'
EMAIL_USE_TLS = True
then I run the command from the command line:
manage.py shell
[1] from django.core.mail import send_mail
[2] send_mail('subject', 'body of the message', 'aaa#mg.xxx.com', ['
recipient#aaa.com'])
Do I use gmail, or with 'mailguna' always get the same error
Error:
TimeoutError Traceback (most recent call last)
<ipython-input-27-4c559962ca7f> in <module>()
----> 1 send_mail('subject', 'body of the message', '####mg.###.com', ['#######.com'])
~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\__init__.py in send_mail(subject, message, from_email, recipient_list, fail_silently, auth_user, auth_password, connection, html_message)
58 mail.attach_alternative(html_message, 'text/html')
59
---> 60 return mail.send()
61
62
~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\message.py in send(self, fail_silently)
289 # send to.
290 return 0
--> 291 return self.get_connection(fail_silently).send_messages([self])
292
293 def attach(self, filename=None, content=None, mimetype=None):
~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\backends\smtp.py in send_messages(self, email_messages)
101 return
102 with self._lock:
--> 103 new_conn_created = self.open()
104 if not self.connection or new_conn_created is None:
105 # We failed silently on open().
~\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\mail\backends\smtp.py in open(self)
61 })
62 try:
---> 63 self.connection = self.connection_class(self.host, self.port, **connection_params)
64
65 # TLS/SSL are mutually exclusive, so only attempt TLS over
~\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py in __init__(self, host, port, local_hostname, timeout, source_address)
249
250 if host:
--> 251 (code, msg) = self.connect(host, port)
252 if code != 220:
253 self.close()
~\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py in connect(self, host, port, source_address)
334 if self.debuglevel > 0:
335 self._print_debug('connect:', (host, port))
--> 336 self.sock = self._get_socket(host, port, self.timeout)
337 self.file = None
338 (code, msg) = self.getreply()
~\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py in _get_socket(self, host, port, timeout)
305 self._print_debug('connect: to', (host, port), self.source_address)
306 return socket.create_connection((host, port), timeout,
--> 307 self.source_address)
308
309 def connect(self, host='localhost', port=0, source_address=None):
~\AppData\Local\Programs\Python\Python37-32\lib\socket.py in create_connection(address, timeout, source_address)
725
726 if err is not None:
--> 727 raise err
728 else:
729 raise error("getaddrinfo returns an empty list")
~\AppData\Local\Programs\Python\Python37-32\lib\socket.py in create_connection(address, timeout, source_address)
714 if source_address:
715 sock.bind(source_address)
--> 716 sock.connect(sa)
717 # Break explicitly a reference cycle
718 err = None
TimeoutError: [WinError 10060]
I tried to change the settings 'TLS', 'mail port' and 'SSL' but they always ended with the same error.
When the code runs outside the application everything works fine:
file_works_properly.py
import smtplib
from email.mime.text import MIMEText
msg = MIMEText('Title') #Tresc wiadomosci
msg['Subject'] = "Hello world"
msg['From'] = "XXX#mg.bbb.com"
msg['To'] = "ccc#ccc.com"
s = smtplib.SMTP('smtp.mailgun.org', 587)
s.login('####mg.bbb.com', '3###baa5e1f3###-26fa###0987')
s.sendmail(msg['From'], msg['To'], msg.as_string())
s.quit()
Every help will be appreciated.
The addition of three imports solved my problem (for 'python manage.py shell' or to the views.py file):
imports (in views.py/shell):
from django.contrib import messages
from django.core.mail import send_mail
from django.conf import settings
The rest of the activities are unchanged:
settings.py
[...]
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'myemail#gmail.com'
EMAIL_HOST_PASSWORD = 'mypassowrd'
EMAIL_PORT = 587
To send e-mail (in views.py/shell)
send_mail(subject, message, from_email, [to_list_email])
(*Important for gmail.com) - and often this option must be enabled.
This code used to run flawlessly. I haven't changed anything but tried using it from a different location, behind a proxy, and I get this error:
IOError: [Errno socket error] [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:590)
Here's where it fails:
gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
data = urllib.urlopen("https://itunes.apple.com/us/rss/topfreeapplications/limit=50/genre=" + str(category) + "/json", "download.txt", context = gcontext).read()
I immediately thought that the problem might come from the proxy I'm using, but don't know how to tell python to use that proxy as well. The solutions in this thread did not help me (same error).
And here's the full traceback:
IOError Traceback (most recent call last)
C:\Users\Nathan\App_Finder_2.0.1.py in <module>()
15 print "Checking category " + str(categoryCounter) + " of " + "23..." # progress
16 print "Opening iTunes RSS feed for top 50 English apps in category " + str(categoryCounter) + " of " + "23..." # progress
---> 17 data = urllib.urlopen("https://itunes.apple.com/us/rss/topfreeapplications/limit=50/genre=" + str(category) + "/json", "download.txt", context = gcontext).read() # Open data from iTunes RSS Feed. Genre = category, in English
18 d = json.loads(data) # Load data
19
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\urllib.pyc in urlopen(url, data, proxies, context)
87 return opener.open(url)
88 else:
---> 89 return opener.open(url, data)
90 def urlretrieve(url, filename=None, reporthook=None, data=None, context=None):
91 global _urlopener
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\urllib.pyc in open(self, fullurl, data)
213 return getattr(self, name)(url)
214 else:
--> 215 return getattr(self, name)(url, data)
216 except socket.error, msg:
217 raise IOError, ('socket error', msg), sys.exc_info()[2]
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\urllib.pyc in open_https(self, url, data)
441 if realhost: h.putheader('Host', realhost)
442 for args in self.addheaders: h.putheader(*args)
--> 443 h.endheaders(data)
444 errcode, errmsg, headers = h.getreply()
445 fp = h.getfile()
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\httplib.pyc in endheaders(self, message_body)
1047 else:
1048 raise CannotSendHeader()
-> 1049 self._send_output(message_body)
1050
1051 def request(self, method, url, body=None, headers={}):
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\httplib.pyc in _send_output(self, message_body)
891 msg += message_body
892 message_body = None
--> 893 self.send(msg)
894 if message_body is not None:
895 #message_body was not a string (i.e. it is a file) and
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\httplib.pyc in send(self, data)
853 if self.sock is None:
854 if self.auto_open:
--> 855 self.connect()
856 else:
857 raise NotConnected()
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\httplib.pyc in connect(self)
1272
1273 self.sock = self._context.wrap_socket(self.sock,
-> 1274 server_hostname=server_hostname)
1275
1276 __all__.append("HTTPSConnection")
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\ssl.pyc in wrap_socket(self, sock, server_side, do_handshake_on_connect, suppress_ragged_eofs, server_hostname)
350 suppress_ragged_eofs=suppress_ragged_eofs,
351 server_hostname=server_hostname,
--> 352 _context=self)
353
354 def set_npn_protocols(self, npn_protocols):
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\ssl.pyc in __init__(self, sock, keyfile, certfile, server_side, cert_reqs, ssl_version, ca_certs, do_handshake_on_connect, family, type, proto, fileno, suppress_ragged_eofs, npn_protocols, ciphers, server_hostname, _context)
577 # non-blocking
578 raise ValueError("do_handshake_on_connect should not be specified for non-blocking sockets")
--> 579 self.do_handshake()
580
581 except (OSError, ValueError):
C:\Users\Nathan\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.6.2.3262.win-x86_64\lib\ssl.pyc in do_handshake(self, block)
806 if timeout == 0.0 and block:
807 self.settimeout(None)
--> 808 self._sslobj.do_handshake()
809 finally:
810 self.settimeout(timeout)
Thanks a lot for your help!