2013-12-10 79 views
2

我想構建一個小的SMTP服務器,通過它我可以發送一些消息。看着smtpd庫發現有什麼東西。但我只能創建一個讀取收到的電子郵件的服務器,但從未將它發送到請求的地址。通過Python發送郵件SMTP服務器

import smtpd 
import asyncore 

class CustomSMTPServer(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) 
    return 

server = CustomSMTPServer(('127.0.0.1', 1025), None) 

asyncore.loop() 

客戶端:

import smtplib 
import email.utils 
from email.mime.text import MIMEText 

# Create the message 
msg = MIMEText('This is the body of the message.') 
msg['To'] = email.utils.formataddr(('Recipient', '[email protected]')) 
msg['From'] = email.utils.formataddr(('Author', '[email protected]')) 
msg['Subject'] = 'Simple test message' 

server = smtplib.SMTP('127.0.0.1', 1025) 
server.set_debuglevel(True) # show communication with the server 
try: 
    server.sendmail('[email protected]', ['[email protected]'], msg.as_string()) 
finally: 
    server.quit() 
+0

你爲什麼要寫你自己的MTA? –

+0

能夠自定義並且可以方便地存儲所有內容 – Blas

+0

請參閱下面的答案。許多優秀的MTA實現提供了相當多的配置選項。 –

回答

3

如果你真的要做到這一點 然後檢查出扭曲的例子:

http://twistedmatrix.com/documents/current/mail/examples/index.html#auto0

我真的不建議你寫您自己的MTA(郵件傳輸代理),因爲這是一個複雜的任務,有許多邊緣案例和標準需要擔心。

使用現有的MTA,例如Postfix,Exim或Sendmail。

+0

謝謝你!我不知道Postfix或Exim – Blas

+1

沒問題。沒有意義重新發明輪子或輪子。 –

相關問題