使用Python将电子邮件转发到远程smtp服务器 [英] Forward email message to remote smtp server in Python

查看:98
本文介绍了使用Python将电子邮件转发到远程smtp服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个SMTP网关,该网关可以过滤电子邮件并将其重定向到远程SMTP服务器.

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)

如何将 process_message 中的消息重定向到远程服务器?

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

SMTP服务器的文档非常简短: https://docs.python.org/2/library/smtpd.html.我在那里找不到答案.

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

推荐答案

我自己找到了答案.

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

这篇关于使用Python将电子邮件转发到远程smtp服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆