Python gmail imap/pop issues - python

I'm trying to write code to view messages from my g-mail, then search in the latest message for a certain phrase, that triggers a command.
But I'm having problems with connecting to my g-mail
from imapclient import IMAPClient
HOST = 'imap.gmail.com'
USERNAME = 'email'
PASSWORD = 'password'
ssl = False
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
server.login(USERNAME, PASSWORD)
server.select_folder('INBOX')
print ('success')
I just added the 'success' at the end to make sure it worked, I'm using imap here but I tried pop which seems to be more confusing.
When I run this code i get this.
Traceback (most recent call last):
File "C:/Users/Yousef/Desktop/parser.py", line 8, in <module>
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\imapclient.py", line 152, in __init__
self._imap = self._create_IMAP4()
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\imapclient.py", line 166, in _create_IMAP4
return imap4.IMAP4WithTimeout(self.host, self.port, self._timeout)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\imap4.py", line 13, in __init__
imaplib.IMAP4.__init__(self, address, port)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-
32\lib\imaplib.py", line 197, in __init__
self.open(host, port)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-
32\lib\imaplib.py", line 294, in open
self.sock = self._create_socket()
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\imap4.py", line 16, in _create_socket
return socket.create_connection((self.host, self.port), self._timeout)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-
32\lib\socket.py", line 722, in create_connection
raise err
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-
32\lib\socket.py", line 713, in create_connection
sock.connect(sa)
TimeoutError: [WinError 10060] A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to respond
Someone please help me with this, because this is my first time using imap/pop.
when I put ssl to true, I get this...
Traceback (most recent call last):
File "C:\Users\Yousef\Desktop\parser.py", line 8, in <module>
server = IMAPClient(HOST, use_uid=True, ssl=ssl)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\imapclient.py", line 152, in __init__
self._imap = self._create_IMAP4()
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\imapclient.py", line 164, in _create_IMAP4
self._timeout)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\tls.py", line 171, in __init__
imaplib.IMAP4.__init__(self, host, port)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-
32\lib\imaplib.py", line 197, in __init__
self.open(host, port)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\tls.py", line 177, in open
self.sock = wrap_socket(sock, self.ssl_context, host)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\tls.py", line 144, in wrap_socket
ssl_context = create_default_context()
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\imapclient\tls.py", line 127, in create_default_context
context.load_verify_locations(cadata=certs)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\backports\ssl\core.py", line 654, in load_verify_locations
self._ctx.load_verify_locations(cafile, capath)
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\OpenSSL\SSL.py", line 669, in load_verify_locations
_raise_current_error()
File "C:\Users\Yousef\AppData\Local\Programs\Python\Python36-32\lib\site-
packages\OpenSSL\_util.py", line 54, in exception_from_error_queue
raise exception_type(errors)
OpenSSL.SSL.Error: []
nvm i found a solution, thanks for the help anyways.

Related

How to handle connection reset in Python SignalR and reconnect again

I am using Python3, signalr, and WebSocket to connect to a server.
When the connection is closed or reset by the server or the network layer, I receive the following error in the output but my print_error function is not fired.
How can I handle this error and reconnect the connection?
Below is the connection part of my code and the error I receive in the output when the connection is reset.
import gevent.monkey
gevent.monkey.patch_all()
from requests import Session
from signalr import Connection
session=Session()
connection = Connection(server_url, session)
connection.qs.update({"token" : token})
connection.received += pushMessage
connection.error += print_error
hub = connection.register_hub('myhub')
connection.start()
# rest of the code
Traceback (most recent call last):
File "src/gevent/greenlet.py", line 854, in gevent._gevent_cgreenlet.Greenlet.run
File "/usr/local/lib/python3.5/dist-packages/signalr/_connection.py", line 53, in wrapped_listener
listener()
File "/usr/local/lib/python3.5/dist-packages/signalr/transports/_ws_transport.py", line 42, in _receive
for notification in self.ws:
File "/usr/local/lib/python3.5/dist-packages/websocket/_core.py", line 109, in __iter__
yield self.recv()
File "/usr/local/lib/python3.5/dist-packages/websocket/_core.py", line 314, in recv
opcode, data = self.recv_data()
File "/usr/local/lib/python3.5/dist-packages/websocket/_core.py", line 331, in recv_data
opcode, frame = self.recv_data_frame(control_frame)
File "/usr/local/lib/python3.5/dist-packages/websocket/_core.py", line 344, in recv_data_frame
frame = self.recv_frame()
File "/usr/local/lib/python3.5/dist-packages/websocket/_core.py", line 378, in recv_frame
return self.frame_buffer.recv_frame()
File "/usr/local/lib/python3.5/dist-packages/websocket/_abnf.py", line 361, in recv_frame
self.recv_header()
File "/usr/local/lib/python3.5/dist-packages/websocket/_abnf.py", line 309, in recv_header
header = self.recv_strict(2)
File "/usr/local/lib/python3.5/dist-packages/websocket/_abnf.py", line 396, in recv_strict
bytes_ = self.recv(min(16384, shortage))
File "/usr/local/lib/python3.5/dist-packages/websocket/_core.py", line 453, in _recv
return recv(self.sock, bufsize)
File "/usr/local/lib/python3.5/dist-packages/websocket/_socket.py", line 102, in recv
bytes_ = _recv()
File "/usr/local/lib/python3.5/dist-packages/websocket/_socket.py", line 84, in _recv
return sock.recv(bufsize)
File "/usr/local/lib/python3.5/dist-packages/gevent/_ssl3.py", line 554, in recv
return self.read(buflen)
File "/usr/local/lib/python3.5/dist-packages/gevent/_ssl3.py", line 385, in read
return self._sslobj.read(nbytes or 1024)
File "/usr/lib/python3.5/ssl.py", line 577, in read
v = self._sslobj.read(len)
ConnectionResetError: [Errno 104] Connection reset by peer
2022-05-14T05:32:02Z <Greenlet at 0x7f53a9e6a748: wrapped_listener> failed with ConnectionResetError

Celery send task to rabbitmq [Errno 111] Connection refused

I'am trying to send task from django local app too remote rabbitmq server (preprod through vpn) but when I'm trying to send it always same error occure. Two errors code are related [Errno -9] Address family for hostname not supported and [Errno 111] Connection refused. The port 5672 is open the user is not the default user and the broker url is amqp://dist:dist#amqp.nopow-link.com:5672.
If someone can help me to understand what I'm doing wrong.
From the client:
>>> task.hello_task.apply_async()
Traceback (most recent call last):
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/utils/functional.py", line 30, in __call__
return self.__value__
AttributeError: 'ChannelPromise' object has no attribute '__value__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/transport.py", line 173, in _connect
host, port, family, socket.SOCK_STREAM, SOL_TCP)
File "/usr/lib/python3.7/socket.py", line 748, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno -9] Address family for hostname not supported
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 447, in _reraise_as_library_errors
yield
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 438, in _ensure_connection
callback, timeout=timeout
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/utils/functional.py", line 312, in retry_over_time
return fun(*args, **kwargs)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 878, in _connection_factory
self._connection = self._establish_connection()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 813, in _establish_connection
conn = self.transport.establish_connection()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/transport/pyamqp.py", line 201, in establish_connection
conn.connect()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/connection.py", line 323, in connect
self.transport.connect()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/transport.py", line 113, in connect
self._connect(self.host, self.port, self.connect_timeout)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/transport.py", line 184, in _connect
"failed to resolve broker hostname"))
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/amqp/transport.py", line 197, in _connect
self.sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/celery/app/task.py", line 579, in apply_async
**options
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/celery/app/base.py", line 788, in send_task
amqp.send_task_message(P, name, message, **options)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/celery/app/amqp.py", line 519, in send_task_message
**properties
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/messaging.py", line 180, in publish
exchange_name, declare, timeout
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 524, in _ensured
return fun(*args, **kwargs)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/messaging.py", line 186, in _publish
channel = self.channel
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/messaging.py", line 209, in _get_channel
channel = self._channel = channel()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/utils/functional.py", line 32, in __call__
value = self.__value__ = self.__contract__()
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/messaging.py", line 225, in <lambda>
channel = ChannelPromise(lambda: connection.default_channel)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 896, in default_channel
self._ensure_connection(**conn_opts)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 438, in _ensure_connection
callback, timeout=timeout
File "/usr/lib/python3.7/contextlib.py", line 130, in __exit__
self.gen.throw(type, value, traceback)
File "/home/callmarl/env/nopow_link/website/application/lib/python3.7/site-packages/kombu/connection.py", line 451, in _reraise_as_library_errors
raise ConnectionError(str(exc)) from exc
kombu.exceptions.OperationalError: [Errno 111] Connection refused
On the server:
user
Listing permissions for user "dist" ...
/ .* .* .*
port
tcp 0 0 0.0.0.0:5672 0.0.0.0:* LISTEN 115995/beam.smp
On server nothing append when listening with tcpdump on port 5672 and no logs are displayed too (log.file.level = debug)
Notice: If I'am sending the same task from the server it's working well.
[2022-05-04 13:24:12,678: INFO/MainProcess] Task core.task.hello_task[a34f9869-03b8-4f4b-8139-b56f90deb469] received
[2022-05-04 13:24:12,680: WARNING/ForkPoolWorker-1] You want me to say hello?
[2022-05-04 13:24:12,680: WARNING/ForkPoolWorker-1] Hello.
[2022-05-04 13:24:12,680: INFO/ForkPoolWorker-1] Task core.task.hello_task[a34f9869-03b8-4f4b-8139-b56f90deb469] succeeded in 0.0006248119752854109s: None

Why am I not able to use the logging module with SMTPHandler to send emails?

I am trying very hard to get the logging module to be able to send emails, but I keep getting errors and nothing is working. My code and the error is below. How do I fix this to send emails?
>>> import logging
>>> logger = logging.getLogger("name")
>>> logger.setLevel(logging.DEBUG)
>>> import logging.handlers
>>> mail_handler = logging.handlers.SMTPHandler("smtp.gmail.com", "lenox.ben#gmail.com", "lenox.ben#gmail.com", "Testing", credentials=("lenox.ben#gmail.com", "Bl12224381"))
>>> mail_handler.setLevel(logging.DEBUG)
>>> mail_handler.setFormatter(logging.Formatter("%(asctime)s|%(levelname)s|%(message)s"))
>>> logger.addHandler(mail_handler)
>>> logger.info("Test email")
--- Logging error ---
Traceback (most recent call last):
File "C:\Users\benle\AppData\Local\Programs\Python\Python37\lib\logging\handlers.py", line 1007, in emit
smtp = smtplib.SMTP(self.mailhost, port, timeout=self.timeout)
File "C:\Users\benle\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 251, in __init__
(code, msg) = self.connect(host, port)
File "C:\Users\benle\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 336, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "C:\Users\benle\AppData\Local\Programs\Python\Python37\lib\smtplib.py", line 307, in _get_socket
self.source_address)
File "C:\Users\benle\AppData\Local\Programs\Python\Python37\lib\socket.py", line 727, in create_connection
raise err
File "C:\Users\benle\AppData\Local\Programs\Python\Python37\lib\socket.py", line 716, in create_connection
sock.connect(sa)
socket.timeout: timed out
Call stack:
File "<string>", line 1, in <module>
File "C:\Users\benle\AppData\Local\Programs\Python\Python37\lib\idlelib\run.py", line 144, in main
ret = method(*args, **kwargs)
File "C:\Users\benle\AppData\Local\Programs\Python\Python37\lib\idlelib\run.py", line 474, in runcode
exec(code, self.locals)
File "<pyshell#10>", line 1, in <module>
Message: 'Test email'
Arguments: ()

Pyftpsync works only without TLS

Hi I'm using pyftpsync in order to upload new images (downloaded every day) in a online store skipping the existing ones.
From the author site I'm using this code (with my personal data of course):
from ftpsync.targets import FsTarget
from ftpsync.ftp_target import FtpTarget
from ftpsync.synchronizers import UploadSynchronizer
local = FsTarget("~/temp")
user ="joe"
passwd = "secret"
remote = FtpTarget("/temp", "example.com", username=user, password=passwd)
opts= {"force": False, "delete_unmatched": True, "verbose": 3, "dry_run" : False}
s = UploadSynchronizer(local, remote, opts,tls=True)
s.run()
This work for me correctly only if I delete the tls option, otherwise I obtain this error while connecting to my server:
Traceback (most recent call last):
File "sync.py", line 25, in <module>
s.run()
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/synchronizers.py", line 139, in run
res = self._sync_dir()
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/synchronizers.py", line 416, in _sync_dir
remote_entries = self.remote.get_dir()
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/ftp_target.py", line 310, in get_dir
self.ftp.retrlines("MLSD", _addline)
File "/usr/lib/python3.4/ftplib.py", line 466, in retrlines
resp = self.sendcmd('TYPE A')
File "/usr/lib/python3.4/ftplib.py", line 272, in sendcmd
return self.getresp()
File "/usr/lib/python3.4/ftplib.py", line 235, in getresp
resp = self.getmultiline()
File "/usr/lib/python3.4/ftplib.py", line 221, in getmultiline
line = self.getline()
File "/usr/lib/python3.4/ftplib.py", line 209, in getline
raise EOFError
EOFError
Could not remove lock file: Underlying socket connection gone (_ssl.c:1570)
Exception ignored in: <bound method FtpTarget.__del__ of <ftpsync.ftp_target.FtpTarget object at 0x7fe397ae7710>>
Traceback (most recent call last):
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/targets.py", line 70, in __del__
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/ftp_target.py", line 153, in close
File "/media/luca/1E9C3E629C3E349D/luca/Documenti/attività/Cataloghi2/ftpsync/ftp_target.py", line 187, in _unlock
File "/usr/lib/python3.4/ftplib.py", line 613, in delete
File "/usr/lib/python3.4/ftplib.py", line 271, in sendcmd
File "/usr/lib/python3.4/ftplib.py", line 198, in putcmd
File "/usr/lib/python3.4/ftplib.py", line 193, in putline
File "/usr/lib/python3.4/ssl.py", line 720, in sendall
File "/usr/lib/python3.4/ssl.py", line 681, in send
ssl.SSLError: Underlying socket connection gone (_ssl.c:1570)
It's obviously a problem related to the encryption, but I don't know how to fix it.

Issue with setting up email sender with Django 1.8 and Plesk

I'm trying to configure a website using Django 1.8 and Plesk, and setting the email variables to any value gets the traceback below. I've tried with Gmail and the email server from the host, and the error is the same. I have tested Python's smtplib and successfully sent an email through that, so it looks like it may be something between Django and Plesk. If I set up the website on a test CentOS 6 server, then I don't run into this problem.
Example Config settings
EMAIL_HOST = "smtp.gmail.com"
EMAIL_HOST_PASSWORD = "mypassword"
EMAIL_HOST_USER = "user#gmail.com"
EMAIL_PORT = 587
Traceback
mod_wsgi (pid=1703): Exception occurred processing WSGI script '/var/www/vhosts/s1085163.instanturl.net/oozoa.wsgi'.
Traceback (most recent call last):
File "/usr/local/lib/python2.7/site-packages/whitenoise/base.py", line 119, in __call__
return self.application(environ, start_response)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/wsgi.py", line 189, in __call__
response = self.get_response(request)
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 218, in get_response
response = self.handle_uncaught_exception(request, resolver, sys.exc_info())
File "/usr/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 256, in handle_uncaught_exception
'request': request
File "/usr/local/lib/python2.7/logging/__init__.py", line 1185, in error
self._log(ERROR, msg, args, **kwargs)
File "/usr/local/lib/python2.7/logging/__init__.py", line 1278, in _log
self.handle(record)
File "/usr/local/lib/python2.7/logging/__init__.py", line 1288, in handle
self.callHandlers(record)
File "/usr/local/lib/python2.7/logging/__init__.py", line 1328, in callHandlers
hdlr.handle(record)
File "/usr/local/lib/python2.7/logging/__init__.py", line 751, in handle
self.emit(record)
File "/usr/local/lib/python2.7/site-packages/django/utils/log.py", line 129, in emit
self.send_mail(subject, message, fail_silently=True, html_message=html_message)
File "/usr/local/lib/python2.7/site-packages/django/utils/log.py", line 132, in send_mail
mail.mail_admins(subject, message, *args, connection=self.connection(), **kwargs)
File "/usr/local/lib/python2.7/site-packages/django/core/mail/__init__.py", line 98, in mail_admins
mail.send(fail_silently=fail_silently)
File "/usr/local/lib/python2.7/site-packages/django/core/mail/message.py", line 303, in send
return self.get_connection(fail_silently).send_messages([self])
File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 100, in send_messages
new_conn_created = self.open()
File "/usr/local/lib/python2.7/site-packages/django/core/mail/backends/smtp.py", line 58, in open
self.connection = connection_class(self.host, self.port, **connection_params)
File "/usr/local/lib/python2.7/smtplib.py", line 256, in __init__
(code, msg) = self.connect(host, port)
File "/usr/local/lib/python2.7/smtplib.py", line 316, in connect
self.sock = self._get_socket(host, port, self.timeout)
File "/usr/local/lib/python2.7/smtplib.py", line 291, in _get_socket
return socket.create_connection((host, port), timeout)
File "/usr/local/lib/python2.7/socket.py", line 557, in create_connection
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
gaierror: [Errno -2] Name or service not known
Might be there is an issues with the firewall. Please try to disabled plesk firewall and IPtables on your server for the testing purpose and check it again.

Categories