【问题标题】:Include html part in a mail with python libgmail使用 python libgmail 在邮件中包含 html 部分
【发布时间】:2010-10-09 03:49:59
【问题描述】:

我有一个关于它的用法的问题:我需要发送一个 html 格式的邮件。我用

准备我的信息
ga = libgmail.GmailAccount(USERNAME,PASSWORD)
msg = MIMEMultipart('alternative') 
msg.attach(part1)
msg.attach(part2)
...
ga.sendMessage(msg.as_string())

这种方式不行,好像不能用sendMessage方法发送msg。 什么是正确的方法? : D

【问题讨论】:

    标签: python html gmail mime libgmail


    【解决方案1】:

    如果您从 sourceforge 引用 libgmail,您需要使用 email module 撰写邮件。

    将 HTML 消息生成为 MIME document,并将其作为 multipart MIME message 的一部分包含在内。当你有一个完全构造的多部分 MIME 时,将它作为一个字符串传递给 libgmail 构造函数,使用 .as_string() 方法。

    example in the doc 包含类似要求的代码:

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

    【讨论】:

    • 感谢您的解释。现在我有了 msg 对象,但我不知道如何将它传递给 libgmail 方法来发送邮件,比如 libgmail.GmailAccount(USERNAME,PASSWORD) ga.sendMessage(msg.as_string()) 不起作用:/跨度>
    • 尝试从字符串中创建一个“GmailComposedMessage”,然后尝试发送这个对象。
    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 2011-06-22
    • 2011-04-11
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 2016-08-23
    相关资源
    最近更新 更多