Chris W.
Chris W.

Reputation: 302

Using python in mutt for creating multipart/alternative mails

I'd like to create a text/plain message using Markdown formatting and transform that into a multipart/alternative message where the text/html part has been generated from the Markdown. I've tried using the filter command to filter this through a python program that creates the message, but it seems that the message doesn't get sent through properly. The code is below (this is just test code to see if I can make multipart/alternative messages at all.

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()

Unfortunately, in mutt, you only get the message body sent to the filter command when you compose (the headers are not included). Once I get this working, I think the markdown part won't be too hard.

Upvotes: 5

Views: 2784

Answers (2)

Chris W.
Chris W.

Reputation: 302

Looks like Mutt 1.13 has the ability to create a multipart/alternative from an external script. http://www.mutt.org/relnotes/1.13/

Upvotes: 2

karlcow
karlcow

Reputation: 6972

Update: Someone wrote an article on configuring mutt for using with a python script. I have myself never done it. hashcash and mutt, the article goes through the configuration of muttrc and give code example.


Old answer

Does it solve your issue?

#!/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'] = "[email protected]"
msg['To'] = "[email protected]"

# 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()

We save and test the program.

python test-email.py 

Which gives:

Content-Type: multipart/alternative;
 boundary="===============1440898741276032793=="
MIME-Version: 1.0
Subject: My subject
From: [email protected]
To: [email protected]

--===============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==--

Upvotes: 1

Related Questions