aiosmtpd 是为电子邮件编写自定义路由和标头重写规则的出色工具。但是,aiosmtpd 不是 MTA,因为它不进行消息队列或 DSN 生成。一个流行的 MTA 选择是 postfix,因为 postfix 可以配置为将域的所有电子邮件中继到另一个本地 SMTP 服务器(例如 aiosmtpd),一个自然的选择是使用 postfix 作为面向互联网的前端和 aiosmtpd 作为业务-逻辑后端。
使用 postfix 作为中间人而不是让 aiosmtpd 面对公共互联网的优点:
- 无需在 aiosmtpd 中处理 DNS MX 查找——只需通过 postfix (localhost:25) 中继
- 不用担心 aiosmtpd 中的不合规 SMTP 客户端
- 不用担心 aiosmtpd 中的 STARTTLS —— 改为在 postfix 中配置它(更简单,更久经沙场)
- 无需担心重试失败的电子邮件递送和发送递送状态通知
- aiosmtpd 可以配置为在编程错误时响应“暂时失败”(SMTP 4xx 代码),因此只要在 4 天内修复编程错误,就不会丢失电子邮件
下面介绍如何配置 postfix 以使用由例如 aiosmtpd 提供支持的本地 SMTP 服务器。
我们将在端口 25 上运行 postfix,在端口 20381 上运行 aiosmtpd。
要指定 postfix 应将电子邮件中继example.com到在端口 20381 上运行的 SMTP 服务器,请将以下内容添加到/etc/postfix/main.cf:
transport_maps = hash:/etc/postfix/smtp_transport
relay_domains = example.com
并/etc/postfix/smtp_transport使用内容创建:
# Table of special transport method for domains in
# virtual_mailbox_domains. See postmap(5), virtual(5) and
# transport(5).
#
# Remember to run
# postmap /etc/postfix/smtp_transport
# and update relay_domains in main.cf after changing this file!
example.com smtp:127.0.0.1:20381
在创建该文件后运行postmap /etc/postfix/smtp_transport(以及每次修改它时)。
在 aiosmtpd 方面,有几件事情需要考虑。
最重要的是您如何处理退回电子邮件。简而言之,您应该将信封发件人设置为您控制的专用于接收退回邮件的电子邮件地址,例如bounce@example.com. 当电子邮件到达此地址时,应将其存储在某处,以便您可以处理退回邮件,例如通过从数据库中删除成员电子邮件地址。
要考虑的另一件重要事情是如何告诉会员的电子邮件提供商您正在进行邮件列表转发。将电子邮件转发到时,您可能希望添加以下标头GROUP@example.com:
Sender: bounce@example.com
List-Name: GROUP
List-Id: GROUP.example.com
List-Unsubscribe: <mailto:postmaster@example.com?subject=unsubscribe%20GROUP>
List-Help: <mailto:postmaster@example.com?subject=list-help>
List-Subscribe: <mailto:postmaster@example.com?subject=subscribe%20GROUP>
Precedence: bulk
X-Auto-Response-Suppress: OOF
在这里,我用作postmaster@example.com列表取消订阅请求的接收者。这应该是转发给电子邮件管理员(即您)的地址。
下面是执行上述操作的骨架(未经测试)。它将退回的电子邮件存储在一个名为的目录中,并根据组列表(在 中)bounces转发具有有效 From:-header(出现在 中)的电子邮件。MEMBERSGROUPS
import os
import email
import email.utils
import mailbox
import smtplib
import aiosmtpd.controller
LISTEN_HOST = '127.0.0.1'
LISTEN_PORT = 20381
DOMAIN = 'example.com'
BOUNCE_ADDRESS = 'bounce'
POSTMASTER = 'postmaster'
BOUNCE_DIRECTORY = os.path.join(
os.path.dirname(__file__), 'bounces')
def get_extra_headers(list_name, is_group=True, skip=()):
list_id = '%s.%s' % (list_name, DOMAIN)
bounce = '%s@%s' % (BOUNCE_ADDRESS, DOMAIN)
postmaster = '%s@%s' % (POSTMASTER, DOMAIN)
unsub = '<mailto:%s?subject=unsubscribe%%20%s>' % (postmaster, list_name)
help = '<mailto:%s?subject=list-help>' % (postmaster,)
sub = '<mailto:%s?subject=subscribe%%20%s>' % (postmaster, list_name)
headers = [
('Sender', bounce),
('List-Name', list_name),
('List-Id', list_id),
('List-Unsubscribe', unsub),
('List-Help', help),
('List-Subscribe', sub),
]
if is_group:
headers.extend([
('Precedence', 'bulk'),
('X-Auto-Response-Suppress', 'OOF'),
])
headers = [(k, v) for k, v in headers if k.lower() not in skip]
return headers
def store_bounce_message(message):
mbox = mailbox.Maildir(BOUNCE_DIRECTORY)
mbox.add(message)
MEMBERS = ['foo@example.net', 'bar@example.org',
'clubadmin@example.org']
GROUPS = {
'group1': ['foo@example.net', 'bar@example.org'],
POSTMASTER: ['clubadmin@example.org'],
}
class ClubHandler:
def validate_sender(self, message):
from_ = message.get('From')
if not from_:
return False
realname, address = email.utils.parseaddr(from_)
if address not in MEMBERS:
return False
return True
def translate_recipient(self, local_part):
try:
return GROUPS[local_part]
except KeyError:
return None
async def handle_RCPT(self, server, session, envelope, address, rcpt_options):
local, domain = address.split('@')
if domain.lower() != DOMAIN:
return '550 wrong domain'
if local.lower() == BOUNCE:
envelope.is_bounce = True
return '250 OK'
translated = self.translate_recipient(local.lower())
if translated is None:
return '550 no such user'
envelope.rcpt_tos.extend(translated)
return '250 OK'
async def handle_DATA(self, server, session, envelope):
if getattr(envelope, 'is_bounce', False):
if len(envelope.rcpt_tos) > 0:
return '500 Cannot send bounce message to multiple recipients'
store_bounce_message(envelope.original_content)
return '250 OK'
message = email.message_from_bytes(envelope.original_content)
if not self.validate_sender(message):
return '500 I do not know you'
for header_key, header_value in get_extra_headers('club'):
message[header_key] = header_value
bounce = '%s@%s' % (BOUNCE_ADDRESS, DOMAIN)
with smtplib.SMTP('localhost', 25) as smtp:
smtp.sendmail(bounce, envelope.rcpt_tos, message.as_bytes())
return '250 OK'
if __name__ == '__main__':
controller = aiosmtpd.controller.Controller(ClubHandler, hostname=LISTEN_HOST, port=LISTEN_PORT)
controller.start()
print("Controller started")
try:
while True:
input()
except (EOFError, KeyboardInterrupt):
controller.stop()