2011-08-10 44 views
0

我正在尝试使用Python smtpd模块制作一个简单的smtp服务器。我可以收到一封电子邮件并将其打印出来。我尝试发送一封电子邮件给那些给我发送带有hello world消息的电子邮件的人,并最终导致无限循环。我尝试使用自己的服务器发送电子邮件,并将其解释为接收到的另一封电子邮件。使用Python smtpd模块发送/接收电子邮件

我该如何使用它来发送和接收电子邮件?

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() 

注意:在示例中不使用真实的电子邮件地址。注2:不使用这个作为邮件服务器。只想发送/接收简单的电子邮件以获得简单的服务。

回答

1

应该将消息发送到自己 ...

执行MX lookup,并发送邮件到适当的SMTP服务器。

+0

如何做到这一点的任何建议?我从来没有尝试过修改过一个smtp守护进程。 –

+0

你......并不需要修改任何东西。您只需使用DNS库来执行MX查找,然后连接到该服务器。 –

相关问题