当我使用python sendmail.
从unix服务器发送邮件时,我得到了一个额外的内容,这个内容显示在邮件中。
From nobody Mon Dec 18 09:36:01 2017 Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit
我的代码如下。
#reading data from file
data = MIMEText(file('%s'%file_name).read())
#writing the content as html
content = MIMEText("<!DOCTYPE html><html><head><title></title></head><body>"+'%s'%data+"</body></html>", "html")
msg = MIMEMultipart("alternative")
msg["From"] = "[email protected]"
msg["To"] = "[email protected]"
msg["Subject"] = "python mail"
msg.attach(content)
p = Popen(["/usr/sbin/sendmail", "-t","-oi"], stdin=PIPE,universal_newlines=True)
p.communicate(msg.as_string())
您正在构建电子邮件内容分为两部分,如data
和content
。您需要明确确认两者都是HTML。所以改变
data = MIMEText(file('%s'%file_name).read())
至
data = MIMEText(file('%s'%file_name).read(), "html")
您应该查看消息字符串。您看到的消息不是警告,它只是您写入消息的内容:
data = MIMEText(file('%s'%file_name).read())
content = MIMEText("<!DOCTYPE html><html><head><title></title></head><body>"
+'%s'%data+"</body></html>", "html")
data.as_string()
实际上包含Content-Type: text/plain; ...
,因为它是由第一个MIMEText
行添加的,当你想将它包含在HTML页面的主体中时。
你真正想要的可能是:
data = file(file_name).read()
content = MIMEText("<!DOCTYPE html><html><head><title></title></head><body>"
+'%s'%data+"</body></html>", "html")
但我也认为你不需要用MIMEMultipart("alternative")
将它包含在另一个级别中:msg = content
可能已经足够了。
最后,当标准库中的smtplib
模块知道如何发送消息时,我不认为明确地开始执行sendmail的新进程真的有点过分了:
import smtplib
server = smtplib.SMTP()
server.send_message(msg)
server.quit()