以下内容在文件中。我使用shell脚本来调用python脚本。这个python脚本发送mail.But在邮件内容中我看到输出如下所示。它全部在线上。什么是我做错了
/usr/bin/python $DIR/sm.py "$message" "`cat /tmp/alert.txt`"
输入:以下是alert.txt
的内容 Thu Jun 28 14:29:26 IST 2012
Disk usage limit exceeded -Current disk usage is 167G-Configured disk usage is 200HTTPD connections exceeded configured usage limit -Current HTTPD connections is 21-Configured HTTPD connection is 20
========================OTHER INFO==================
Total fds: 8
Socket fds: 0
Other fds: 8
Free memory :Free Memory:183732
Buffered memory Buffered Memory:78224
Cache memory : Cache Memory:579040
Disk usage is 167G
DB connections 1
Network connections 21
CPU Usage: 0.0
输出:
Thu Jun 28 14:29:26 IST 2012 Disk usage limit exceeded -Current disk usage is 167G-Configured disk usage is 200HTTPD connections exceeded configured usage limit -Current HTTPD connections is 21-Configured HTTPD connection is 20 ========================OTHER INFO================== Total fds: 8 Socket fds: 0 Other fds: 8 Free memory :Free Memory:183732 Buffered memory Buffered Memory:78224 Cache memory : Cache Memory:579040 Disk usage is 167G DB connections 1 Network connections 21 CPU Usage: 0.0
这是sm.py
import logging
import smtplib
import sys
from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
try:
smaid = qs[0].id
gmailUser = 'no-reply@xxxxxxxxxxx.com'
gmailPassword = '12345'
mailServer = smtplib.SMTP('smtp.gmail.com', 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(gmailUser, gmailPassword)
to_addr = "xxxxx@xx.com"
subject = sys.argv[1]
body = sys.argv[2]
try:
msg = MIMEMultipart()
msg['From'] = gmailUser
msg['To'] = to_addr
msg["Content-type"] = "text/html"
sub = subject
msg['Subject'] = sub
body = body
msg.attach(MIMEText(body, 'html'))
mailServer.sendmail(gmailUser, to_addr, msg.as_string())
except:
write_exception("send exception")
mailServer.close()
except:
write_exception("send exception1")
答案 0 :(得分:2)
如果您坚持发送HTML,则需要HTML换行符:
import cgi
# escape special HTML characters
body = cgi.escape(body)
# use HTML line breaks
body = body.replace("\r\n", "\n").replace("\n", "<br />\n")
但可能您既不需要Multipart也不需要HTML,因此您只需使用smtplib.SMTP.sendmail
:
headers = (('From', gmailUser),
('To', to_addr),
('Subject', subject))
# normalize newlines to CR+LF, as required by SMTP
body = body.replace("\r\n", "\n").replace("\n", "\r\n")
msg = '\r\n'.join("%s: %s" % kv for kv in headers) + '\r\n'*2 + body
mailServer.sendmail(gmailUser, [to_addr], msg)
此外,您不应通过命令行提供文件内容,因为命令行是长度限制的。相反,你应该通过STDIN提供文件,就像在python ... < /tmp/alert.txt
中一样,并通过
import sys
body = sys.stdin.read()
答案 1 :(得分:2)
以text/plain
而不是text/html
发送。
你那里没有任何HTML。
这应该解决它,因为它取决于客户端正确显示文本。新行在HTML中的效果不同。
答案 2 :(得分:0)
您将邮件的内容类型设置为“text / html”,因此用户的邮件代理显然会将主体解释并呈现为html。如果要保留纯文本格式,请不要将内容类型设置为text / html。
答案 3 :(得分:0)
您使用的是哪个shell?
"`cat xxx`"
csh中的将删除所有换行符并返回空格分隔的字符串
> cat >testfile
line 1
line 2
<ctrl-d>
> echo "`cat testfile`"
line 1 line 2