Forward email message to remote smtp server in Python

≡放荡痞女 提交于 2020-01-17 07:55:08

问题


I want to create a SMTP-Gateway that filters emails and redirects them to the remote SMTP server.

from smtpd import SMTPServer
from email.parser import Parser

class SMTPGateway(SMTPServer):

    def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
        print('Processing message...')

        email = Parser().parsestr(data)
        for part in email.walk():
            if part.get_content_maintype() == 'text':
                text = part.get_payload()
                # Process text

        # forward email to upstream smtp server

With this code I can receive a message and process it. But I don't know how to forward the message to the remote server.

In my main program, I create the server like this:

localaddress = ('localhost', 3000)
remoteaddress = ('localhost', 9000)

gateway = SMTPGateway(localaddress, remoteaddress)

How can I redirect the message in process_message to the remote server?

The documentation of the SMTP-Server is very short: https://docs.python.org/2/library/smtpd.html. I could not find the answer there.


回答1:


I found the answer myself.

from smtpd import SMTPServer
from email.parser import Parser

class SMTPGateway(SMTPServer):
def process_message(self, peer, mailfrom, rcpttos, data, **kwargs):
    print('Processing message...')

    email = Parser().parsestr(data)
    for part in email.walk():
        if part.get_content_maintype() == 'text':
            text = part.get_payload()
            # Process text

    # forward email to upstream smtp server
    ip = self._remoteaddr[0]
    port = self._remoteaddr[1]
    server = SMTP(ip, port)
    server.send_message(email)
    server.quit()


来源:https://stackoverflow.com/questions/40412755/forward-email-message-to-remote-smtp-server-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!