Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python in mutt for creating multipart/alternative mails

Tags:

python

mime

mutt

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.

like image 551
Chris W. Avatar asked Nov 04 '22 05:11

Chris W.


1 Answers

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==--
like image 117
karlcow Avatar answered Nov 15 '22 13:11

karlcow