Python 发送邮件,错误

Python sendmail, error

当我使用 python 从 unix 服务器发送邮件时,我收到如下所示的附加内容 sendmail.此内容显示在邮件中。

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"] = "sender@mail.com"
   msg["To"] = "mymailid@mail.com"
   msg["Subject"] = "python mail"

   msg.attach(content)

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

您正在分两部分构建电子邮件内容,如 datacontent。您需要明确确认两者都是 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()