我们正在做一些与 plone 类似的事情,通过配置 postfix 在接收到特定域的电子邮件时向 plone 发出 HTTP 请求。这也应该可以通过 django 轻松实现,因此您只需配置服务器并在 django 中编写一个接收电子邮件的视图即可。
这就是你可以做到的:
1) 设置您的 DNS,以便域的 MX 记录指向您的服务器。
2)配置postfix虚拟别名/etc/postfix/virtual
:
example.com anything
[email protected] /cdn-cgi/l/email-protection django-mail-in
3) and /etc/aliases
:
django-mail-in: "|/usr/local/bin/mta2django.py http://127.0.0.1:8000/mail-inbound"
4) The /usr/local/bin/mta2django.py
由 postscript 调用并将邮件发送到mail-inbound
Django 视图。这mta2django.py
应该管用:
#!/usr/bin/python
import sys, urllib
import os
def post_message(url, recipient, message_txt):
""" post an email message to the given url
"""
if not url:
print "Invalid url."
print "usage: mta2django.py url <recipient>"
sys.exit(64)
data = {'mail': message_txt}
if recipient and len(recipient) > 0:
data ['recipient'] = recipient
try:
result = urllib.urlopen(url, urllib.urlencode(data)).read()
except (IOError,EOFError),e:
print "error: could not connect to server",e
sys.exit(73)
try:
exitcode, errormsg = result.split(':')
if exitcode != '0':
print 'Error %s: %s' % (exitcode, errormsg)
sys.exit(int(exitcode))
except ValueError:
print 'Unknown error.'
sys.exit(69)
sys.exit(0)
if __name__ == '__main__':
# This gets called by the MTA when a new message arrives.
# The mail message file gets passed in on the stdin
# Get the raw mail
message_txt = sys.stdin.read()
url = ''
if len(sys.argv)>1:
url = sys.argv[1]
recipient = ''
# If mta2django is executed as external command by the MTA, the
# environment variable ORIGINAL_RECIPIENT contains the entire
# recipient address, before any address rewriting or aliasing
recipient = os.environ.get('ORIGINAL_RECIPIENT')
if len(sys.argv)>2:
recipient = sys.argv[2]
post_message(url, recipient, message_txt)
5)编写django视图/mail-inbound
它接收邮件并执行您需要它执行的操作。在请求中您有:
-
mail
- 完整的电子邮件信息
-
recipient
- 原始收件人(当您没有捕获特定电子邮件地址而是整个域/子域时很有用)
您可以使用 python 解析电子邮件email
module:
import email
msg = email.message_from_string(request.get('mail'))
由于我不是后缀专家,我不确定是否可以编辑/etc/postfix/virtual
and /etc/aliases
足够了。详细信息请查阅 postfix 文档。