Python mail script

博客首页 » Python mail script

发布于 22 Jun 2014 15:29
标签 blog
这是一个Python的mail script。并不是在所有的服务器上,我们都有权限安装软件包。不过,只要有Python,我们就能解决问题。

这个mail.py与Linux的标准mail一样,支持-b -c -s Option。

使用这个命令加入用户的shell中。

echo "alias mail='/home/myuser/bin/mail.py'" » ~/.bash_profile

cat mail.py
#!/usr/bin/python
import smtplib, getopt, sys
 
try:
    opts, args = getopt.getopt(sys.argv[1:], "s:b:c:", ["subject"])
except getopt.GetoptError, err:
    # print help information and exit:
    print str(err) # will print something like "option -a not recognized"
    usage()
    sys.exit(2)
 
smtpserver = 'intsmtp.hikari.co.jp'
AUTHREQUIRED = 0 # if you need to use SMTP AUTH set to 1
smtpuser = ''  # for SMTP AUTH, set SMTP username here
smtppass = ''  # for SMTP AUTH, set SMTP password here
 
subject = ''
bcc_arg = ''
cc_arg = ''
for o, a in opts:
        if o in ("-b"):
            bcc_arg = a
        elif o in ("-c"):
            cc_arg = a
        elif o in ("-s", "--subject"):
            subject = a
        else:
            assert False, "unhandled option"
 
toaddr = args[0].split(',')
 
body = sys.stdin.read()
mssg = ""
if vars().has_key('subject'):
    mssg = mssg + "Subject: %s\n" % subject
else:
    mssg = mssg + "Subject: \n"
SENDER = 'tm-admin@po.hikari.co.jp'
mssg = mssg + "From: %s\n" % SENDER
RECIPIENTS = toaddr
mssg = mssg + "To: %s\n" % ",".join(toaddr)
if vars().has_key('cc_arg'):
    #print "found cc_arg"
    cc = cc_arg.split(',')
    RECIPIENTS = RECIPIENTS + cc
    mssg = mssg + "CC: %s\n" % ",".join(cc)
if vars().has_key('bcc_arg'):
    #print "found bcc_arg"
    bcc = bcc_arg.split(',')
    RECIPIENTS = RECIPIENTS + bcc
    mssg = mssg + "BCC: %s\n" % ",".join(bcc)
mssg = mssg + body
session = smtplib.SMTP(smtpserver)
if AUTHREQUIRED:
    session.login(smtpuser, smtppass)
smtpresult = session.sendmail(SENDER, RECIPIENTS, mssg)
 
if smtpresult:
    errstr = ""
    for recip in smtpresult.keys():
        errstr = """Could not delivery mail to: %s
 
Server said: %s
%s
 
%s""" % (recip, smtpresult[recip][0], smtpresult[recip][1], errstr)
    raise smtplib.SMTPException, errstr

本页面的文字允许在知识共享 署名-相同方式共享 3.0协议和GNU自由文档许可证下修改和再使用,仅有一个特殊要求,请用链接方式注明文章引用出处及作者。请协助维护作者合法权益。


系列文章

文章列表

  • Python mail script

这篇文章对你有帮助吗,投个票吧?

rating: 0+x

留下你的评论

Add a New Comment
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License