Reputation: 6647
I'm trying to make a simple smtp server using the Python smtpd module. I can receive an e-mail and print it out. I try to send an e-mail back to the person who sent me the e-mail with a hello world message and I end up with an infinite loop. I try to use my own server to send the e-mail and it just interprets it as another e-mail that's been received.
How can I use this to both send and receive e-mail?
import smtplib, smtpd
import asyncore
import email.utils
from email.mime.text import MIMEText
import threading
class SMTPReceiver(smtpd.SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data):
print 'Receiving message from:', peer
print 'Message addressed from:', mailfrom
print 'Message addressed to :', rcpttos
print 'Message length :', len(data)
print data
def send_response():
msg = MIMEText('Hello world!')
msg['To'] = email.utils.formataddr(('Recipient', mailfrom))
msg['From'] = email.utils.formataddr(('Author', '[email protected]'))
msg['Subject'] = ''
print 'Connecting to mail server'
server = smtplib.SMTP()
server.set_debuglevel(1)
server.connect()
print 'Attempting to send message'
try:
server.sendmail('[email protected]', [mailfrom], msg.as_string())
except Exception, ex:
print 'Could not send mail', ex
finally:
server.quit()
print 'Finished sending message'
threading.Thread(target=send_response).start()
return
def main():
server = SMTPReceiver(('', 25), None)
asyncore.loop()
if __name__ == '__main__':
main()
Note: Not using a real e-mail address in the example. Note 2: Not using this as a mail server. Just want to send/receive simple e-mails for a simple service.
Upvotes: 0
Views: 4310
Reputation: 798536
You're not supposed to send the message to yourself...
Perform a MX lookup and send the message to the appropriate SMTP server.
Upvotes: 1