有人可以告诉我如何在python中使用sendmail以HTML格式发送邮件吗?
我想发送此信息:
<pre>some code</pre>
Python版本是2.4.3,无法更新。
答案 0 :(得分:3)
# 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 :-('
答案 1 :(得分:1)
您可以查看webpy微框架的代码,了解各种发送电子邮件的方法,包括sendmail:https://github.com/webpy/webpy/blob/master/web/utils.py#L1415
答案 2 :(得分:0)
只需在邮件中提供HTML代码,并将mime版本和内容称为text / html。 http://www.tutorialspoint.com/python/python_sending_email.htm
答案 3 :(得分:0)
我找到了一种简单的方法:
当我运行我的脚本时,我将输出写入文件(mail.txt),然后在最后,我只是打电话:
os.popen('cat mail.txt | sendmail -t')
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>
也许这不是最好的方法,但对我来说效果很好......