Thursday, April 7, 2011

Include html part in a mail with python libgmail

I've a question about its usage: i need to send an html formatted mail. I prepare my message with

ga = libgmail.GmailAccount(USERNAME,PASSWORD)
msg = MIMEMultipart('alternative') 
msg.attach(part1)
msg.attach(part2)
...
ga.sendMessage(msg.as_string())

This way doesn't works, it seems can't send msg with sendMessage method. What is the right way? : D

From stackoverflow
  • If you refer to libgmail from sourceforge, you need to compose your messages with the email module.

    Generate the HTML message as a MIME document, and include it as a part of a multipart MIME message. When you have a fully constructed multipart MIME, pass it along as a string to the libgmail constructor, using to .as_string() method.

    An example in the doc contains the code for a similar requirement:

    # Create message container - the correct MIME type is multipart/alternative.
    msg = MIMEMultipart('alternative')
    msg['Subject'] = "Link"
    msg['From'] = me
    msg['To'] = you
    ...
    # Record the MIME types of both parts - text/plain and text/html.
    # ... text and html are strings with appropriate content.
    part1 = MIMEText(text, 'plain')
    part2 = MIMEText(html, 'html')
    
    # Attach parts into message container.
    # According to RFC 2046, the last part of a multipart message, in this case
    # the HTML message, is best and preferred.
    msg.attach(part1)
    msg.attach(part2)
    
    Emilio : thanks for the explanation. Now i have the msg object, but i don't know how pass it to libgmail methods to send mail, like libgmail.GmailAccount(USERNAME,PASSWORD) ga.sendMessage(msg.as_string()) doesn't works :/
    gimel : try to create a "GmailComposedMessage" from the string, and then try to send this object.
    Emilio : I don't understand how :/

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.