I need to create a class that can receive and store SMTP messages, i.e. E-Mails. To do so, I am using asyncore
according to an example posted here. However, asyncore.loop()
is blocking so I cannot do anything else in the code.
So I thought of using threads. Here is an example-code that shows what I have in mind:
class MyServer(smtpd.SMTPServer):
# derive from the python server class
def process_message(..):
# overwrite a smtpd.SMTPServer method to be able to handle the received messages
...
self.list_emails.append(this_email)
def get_number_received_emails(self):
"""Return the current number of stored emails"""
return len(self.list_emails)
def start_receiving(self):
"""Start the actual server to listen on port 25"""
self.thread = threading.Thread(target=asyncore.loop)
self.thread.start()
def stop(self):
"""Stop listening now to port 25"""
# close the SMTPserver from itself
self.close()
self.thread.join()
I hope you get the picture. The class MyServer
should be able to start and stop listening to port 25 in a non-blocking way, able to be queried for messages while listening (or not). The start
method starts the asyncore.loop()
listener, which, when a reception of an email occurs, append to an internal list. Similar, the stop
method should be able to stop this server, as suggested here.
Despite the fact this code does not work as I expect to (asyncore seems to run forever, even I call the above stop
method. The error
I raise is catched within stop
, but not within the target
function containing asyncore.loop()
), I am not sure if my approach to the problem is senseful. Any suggestions for fixing the above code or proposing a more solid implementation (without using third party software), are appreciated.
asyncore.loop()
blocking ? Do you understand why you call theloop
function and what it does ? – Hickieasyncore.loop()
is that it is blocking. I want to be able to use the class at any time within some other code. On the other side, I am not an expert onasyncore.loop()
, but AFAIK it handles internal theselect.select
, which is looking e.g. for incoming SMTP messages on port 25, in this case. – Buyer