问题
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