Python执行sendmail但不发送电子邮件

时间:2014-06-14 05:25:18

标签: python email sendmail

我检查过Stackoverflow并发现了类似的问题,但似乎没有人回答我的具体问题。我正在使用Python 2.6。

以下函数用于通过sendmail成功发送包含附件的纯文本电子邮件:

def sndmsg(u,A,a):
    """
    + sends email(s) with plain text and attachment

    u = str - company url
    A = str - manager's name
    a = list of email addresses to send to
    """
    u=u.replace('/','')
    file = open('message.txt','rb')
    txt=file.read()
    file.close()
    for t in a:
        out = MIMEMultipart()
        out['Subject'] = 'Free Report'
        out['From'] = 'admin@example.com'
        out['To'] = t.strip()
        out['Date'] = date()

        pt1 = MIMEText(txt.format(A,u))
        out.attach(pt1)

        att = MIMEApplication(open('/path/'+u+'.xls',"rb").read())
        att.add_header('Content-Disposition', 'attachment', filename=u+'.xls')
        out.attach(att)

        p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
        p.communicate(out.as_string())

然后修改它以包含html格式的文本(下面)。代码执行正常并移动到下一个函数而没有错误,但这次我在任何收件箱或垃圾邮件文件夹中都没有收到任何电子邮件。

def sndmsg(u,A,a):
    """
    + sends email(s) with html text, plain text and attachment

    u = str - company url
    A = str - manager's name
    a = list of email addresses to send to

    H[0] = str - html table
    """
    u=u.replace('/','')
    file = open('message.txt','rb')
    txt=file.read()
    file.close()
    file = open('message.html','rb')
    htm=file.read()
    file.close()
    for t in a:
        out = MIMEMultipart()
        out['Subject'] = 'Free Report'
        out['From'] = 'admin@example.com'
        out['To'] = t.strip()
        out['Date'] = date()

        inn = MIMEMultipart('alternative')
        pt1 = MIMEText(txt.format(A,u))
        pt2 = MIMEText(htm.format(A,u,H[0]), 'html')
        inn.attach(pt1)
        inn.attach(pt2)
        out.attach(inn)

        att = MIMEApplication(open('/path/'+u+'.xls',"rb").read())
        att.add_header('Content-Disposition', 'attachment', filename=u+'.xls')
        out.attach(att)

        p = Popen(["/usr/sbin/sendmail", "-t"], stdin=PIPE)
        p.communicate(out.as_string())

我的主要问题是它是编码问题还是Sendmail问题。

我尝试独立使用第二个功能并在我的浏览器中单独打开html消息,它看起来不错但电子邮件仍未发送。

我没有SSH对服务器的root访问权限并检查/var/log/mail。我已经问过服务器管理员但没有得到任何帮助。

如果编码错误需要修复或改进?

感谢您对我的无知和对您的帮助的耐心。

1 个答案:

答案 0 :(得分:0)

  1. -i添加到sendmail的联播行选项

    p = Popen(["/usr/sbin/sendmail", "-t", "-i"], stdin=PIPE)

  2. 由Popen

    创建的明确关闭管道

    rc = p.close() if rc is not None and rc >> 8: print "There were some errors"

  3. 如果无法修复,请在sendmail的命令行选项中添加-v(详细/调试)选项,并在终端中执行sctipt以查看其stderr输出。

    < / LI>

    https://docs.python.org/2/library/subprocess.html#popen-objects