Python:使用sendmail以html格式发送邮件

Python:使用sendmail以html格式发送邮件,python,sendmail,Python,Sendmail,有人能告诉我如何用python中的sendmail发送HTML格式的邮件吗 我想寄这个: <pre>some code</pre> 一些代码 Python版本为2.4.3,无法更新。只需在消息中提供HTML代码,并将mime版本和内容提到text/HTML即可 您可以查看webpy micro framework的代码,了解发送电子邮件的各种方法,包括sendmail:我找到了一种简单的方法: 当我运行脚本时,我将输出写入一个文件(mail.txt),然后在最后调用:

有人能告诉我如何用python中的sendmail发送HTML格式的邮件吗

我想寄这个:

<pre>some code</pre>
一些代码

Python版本为2.4.3,无法更新。

只需在消息中提供HTML代码,并将mime版本和内容提到text/HTML即可

您可以查看webpy micro framework的代码,了解发送电子邮件的各种方法,包括sendmail:

我找到了一种简单的方法:

当我运行脚本时,我将输出写入一个文件(mail.txt),然后在最后调用:

To: my.mail@gmail.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="123"
Subject: My subject

This is a MIME-encapsulated message

--123
Content-Type: text/html

<html>
   <head>
      <title>HTML E-mail</title>
   </head>
   <body>
      <pre>Some code</pre>
   </body>
</html>
mail.txt内容:

# assemble the mail content
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
message = MIMEMultipart('alternative')
message.add_header('Subject', 'subject goes here')
# add a few more add_header calls here for things like "To", "Cc", "From"
message.attach(MIMEText('some code')) # plain text alternative
message.attach(MIMEText('<html><pre>some code</pre></html>', # html content
                        'html'))

# pipe the mail to sendmail
sendmail = os.popen('sendmail recipient@example.org', 'w')
sendmail.write(message.as_string())
if sendmail.close() is not None:
   print 'error: failed to send mail :-(' 
To:my。mail@gmail.com
MIME版本:1.0
内容类型:多部分/备选;
边界=“123”
主题:我的主题
这是一条MIME封装的消息
--123
内容类型:text/html
HTML电子邮件
一些代码
也许这不是最好的方法,但对我来说很好…

#组装邮件内容
从email.MIMEMultipart导入MIMEMultipart
从email.MIMEText导入MIMEText
message=MIMEMultipart('alternative')
message.add_头('Subject','Subject go here')
#在这里添加更多的add_头调用,例如“To”、“Cc”、“From”
message.attach(MIMEText('some code'))#纯文本可选
message.attach(MIMEText('some code',#html内容
“html”)
#通过管道将邮件发送到sendmail
sendmail=os.popen('sendmailrecipient@example.org','w')
sendmail.write(message.as_string())
如果sendmail.close()不是无:
“打印”错误:无法发送邮件:-('

如果smtp是一个可行的解决方案,您可以检查可能的重复-?实际上不是重复的,因为OP正在尝试使用sendmail,smtp可能不是一个可行的解决方案。此处smtp不是一个选项:S
# assemble the mail content
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
message = MIMEMultipart('alternative')
message.add_header('Subject', 'subject goes here')
# add a few more add_header calls here for things like "To", "Cc", "From"
message.attach(MIMEText('some code')) # plain text alternative
message.attach(MIMEText('<html><pre>some code</pre></html>', # html content
                        'html'))

# pipe the mail to sendmail
sendmail = os.popen('sendmail recipient@example.org', 'w')
sendmail.write(message.as_string())
if sendmail.close() is not None:
   print 'error: failed to send mail :-('