你可以这样做:
1) 设置您的 DNS,以便域的 MX 记录指向您的服务器。
2)配置后缀虚拟别名/etc/postfix/virtual
:
@example.com django-mail-in
3) 和 /etc/别名:
django-mail-in: "|/usr/local/bin/mta2django.py http://127.0.0.1:8000/mail-inbound"
4) /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 模块解析电子邮件:
导入电子邮件
msg = email.message_from_string(request.get('mail'))
/etc/postfix/virtual
由于我不是后缀专家,我不确定编辑/etc/aliases
是否足够。有关详细信息,请参阅 postfix 文档。