Python执行sendmail但不发送邮件
我在Stackoverflow上查了查,发现有类似的问题,但没有一个能解决我具体遇到的情况。我现在用的是Python 2.6。
我用下面这个函数成功发送了一封带附件的纯文本邮件:
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
登录服务器去检查/var/log/mail
。我问过服务器管理员,但没有得到任何帮助。
如果是代码错误的话,应该修复或改进什么呢?
谢谢你们耐心对待我的无知和给予的帮助。
1 个回答
0
在sendmail的命令行选项中加上
-i
,这样可以让它更好地处理输入。p = Popen(["/usr/sbin/sendmail", "-t", "-i"], stdin=PIPE)
要明确关闭由Popen创建的管道,这样可以避免资源浪费。
rc = p.close() if rc is not None and rc >> 8: print "出现了一些错误"
如果还是不行,可以在sendmail的命令行选项中加上
-v
(详细/调试)选项,然后在终端运行你的脚本,这样可以看到错误输出。
https://docs.python.org/2/library/subprocess.html#popen-objects