简单的服务器端 2G 移动电话应用程序
2010-06-28 00:00:00 来源:WEB开发网现在我想起了选择编程语言的一条重要准则,那就是可以使用什么样的库来处理应用程序中较为单调的任务,而解析电子邮件头、寻找正确的邮件部分和根据需要解码邮件无疑属于单调的任务。 在 CPAN 上,我找到了一个 Perl 模块来解析各种电子邮件头,这样,无论各种邮件头格式之间有多大差异,我都可以通过函数调用获取所需的信息。然而,这个库依赖于其他 Perl 库,并且我的主机提供程序有其中一个库的过期版本,因此我在这个方面分析了 Python 提供的功能。我找到了一个 Python email 包,编写了一些简单测试,然后决定使用 Python 重新编写我的程序在网上快速搜索一下,就可以找到一些可用于 Ruby、Java™、PHP 和其他编程语言的类似的库,因此,如果您想编写一个电子邮件自动回复脚本,不再局限于只使用 Perl 或 Python 语言。
自动回复脚本
清单 3 给出了 aci.py 脚本。请注意开始处的 import 语句如何拉入 email.Parser 库以及其他几个流行的 Python 库。底部的 __main__ 部分保存程序的基本逻辑:解析收到的消息,从中拉取发件人地址和消息正文(存储在变量 areaCode 中),使用在脚本中定义的 areaCodeInfo 函数搜索有关特定区号的信息,将此信息作为回复发送,然后记录该消息。
清单 3. aci.py 脚本
#!/usr/local/bin/python
# aci.pl: (area code information) read e-mail message to find area
# code, then send information about that area code.
# Bob DuCharme 2010-01 no warranty expressed or implied
import os
import email.Parser
import sys
import datetime
import re
def multipartBody(msg):
# following code from
# http://docs.python.org/library/email-examples.html
partCounter=1
for part in msg.walk():
if part.get_content_maintype()=="multipart":
continue
name=part.get_param("name")
if name==None:
name="part-%i" % partCounter
partCounter+=1
msgText = part.get_payload(decode=1)
msgSender = msgSenderText
return msgText.strip() # strip whitespace
def areaCodeInfo(areaCode):
# Look for data about that area code in areacodes.txt.
# First initialize values that should get overridden.
response = "No information available for area code " + areaCode + "."
foundAreaCode = False
line = "dummy"
acFile = open(aciPath + "areacodes.txt")
while ((not foundAreaCode) and line):
line = acFile.readline()
if (line[0:5] == areaCode + ": "): # e.g. "212: "
response = line
foundAreaCode = True
return response
def sendReply(msgSender,response):
f = os.popen("%s -t" % SENDMAIL, "w")
f.write("To: " + msgSender + "\n")
f.write("From: area code information <acinfo@snee.com>\n")
f.write("Return-Path: area code information <acinfo@snee.com>\n")
f.write("Content-type: text/plain\n\n")
f.write(response)
sts = f.close()
def logIt(msgSenderText,areaCode):
timestamp = datetime.datetime.today().isoformat()[0:19]
log = open(aciPath + "log.txt",'a')
log.write(timestamp + " " + msgSenderText + " " + areaCode + "\n")
log.close()
if __name__ == "__main__":
SENDMAIL = "/usr/sbin/sendmail" # sendmail location
aciPath = "/usr/home/bobd/aci/"
keepFullLog = False # For debugging. More detailed than log.txt.
response = ""
# Parse the standard input to find the message and sender value
mailFile=sys.stdin
p=email.Parser.Parser()
msg=p.parse(mailFile)
mailFile.close()
msgSenderText = msg['From'] # text showing msg sender's name
msgSender = msgSenderText # save msgSenderText for log
# If msgSender has the form "Some Guy <someguy@example.com>"
# then we just want someguy@example.com
emailAddrRegEx = re.compile(r"\<(?P<emailAddr>.+)\>")
result = emailAddrRegEx.search(msgSender)
if result != None:
msgSender = result.group('emailAddr')
if keepFullLog:
output = open(aciPath + "fulllog.txt",'a')
output.write(str(msg) + "\n-- end of mail msg --\n\n")
output.close()
if msg.has_key("X-Mailer") and \
msg["X-Mailer"][0:24] == "Microsoft Office Outlook":
response = "Microsoft Outlook format is not supported."
areaCode = ""
else:
areaCode = multipartBody(msg)
response = areaCodeInfo(areaCode)
sendReply(msgSender,response)
logIt(msgSenderText,areaCode)
更多精彩
赞助商链接