在mutt中使用Python创建multipart/alternative邮件
我想用Markdown格式创建一个 text/plain
消息,然后把它转换成一个 multipart/alternative
消息,其中的 text/html
部分是从Markdown生成的。我尝试使用过滤命令,通过一个Python程序来处理这个消息,但似乎消息没有正确发送。下面的代码是我用来测试是否能创建 multipart/alternative
消息的(这只是测试代码)。
import sys
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
html = """<html>
<body>
This is <i>HTML</i>
</body>
</html>
"""
msgbody = sys.stdin.read()
newmsg = MIMEMultipart("alternative")
plain = MIMEText(msgbody, "plain")
plain["Content-Disposition"] = "inline"
html = MIMEText(html, "html")
html["Content-Disposition"] = "inline"
newmsg.attach(plain)
newmsg.attach(html)
print newmsg.as_string()
不幸的是,在mutt中,当你撰写消息时,只有消息的主体会被发送到过滤命令,而标题部分不会包含在内。一旦我把这个搞定,我觉得处理Markdown部分应该不会太难。
2 个回答
1
更新: 有人写了一篇关于如何配置mutt以便与Python脚本一起使用的文章。我自己从来没有这样做过。hashcash和mutt,这篇文章详细讲解了mutt的配置文件muttrc,并提供了代码示例。
旧回答
这个解决了你的问题吗?
#!/usr/bin/env python
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
# create the message
msg = MIMEMultipart('alternative')
msg['Subject'] = "My subject"
msg['From'] = "foo@example.org"
msg['To'] = "bar@example.net"
# Text of the message
html = """<html>
<body>
This is <i>HTML</i>
</body>
</html>
"""
text="This is HTML"
# Create the two parts
plain = MIMEText(text, 'plain')
html = MIMEText(html, 'html')
# Let's add them
msg.attach(plain)
msg.attach(html)
print msg.as_string()
我们保存并测试这个程序。
python test-email.py
这将得到:
Content-Type: multipart/alternative;
boundary="===============1440898741276032793=="
MIME-Version: 1.0
Subject: My subject
From: foo@example.org
To: bar@example.net
--===============1440898741276032793==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
This is HTML
--===============1440898741276032793==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
<html>
<body>
This is <i>HTML</i>
</body>
</html>
--===============1440898741276032793==--
2
看起来Mutt 1.13版本可以通过外部脚本来创建一个叫做 multipart/alternative
的东西。你可以在这里查看详细信息:http://www.mutt.org/relnotes/1.13/