Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用用户指定的HTML和纯文本正文以编程方式发布Gmail草稿_Python_Gmail Api_Mime Message - Fatal编程技术网

Python 用用户指定的HTML和纯文本正文以编程方式发布Gmail草稿

Python 用用户指定的HTML和纯文本正文以编程方式发布Gmail草稿,python,gmail-api,mime-message,Python,Gmail Api,Mime Message,我正在使用Gmail API用Python自动创建Gmail草稿。我需要创建HTML格式的电子邮件,但我个人也需要创建一个纯文本回退,因为这是正确的做法 我以为我已经完成了上述所有工作,直到我尝试使明文回退与HTML略有不同。谷歌似乎自行为我创建了纯文本回退,而不是使用我提供的,因此如果我的html正文是html正文,而我的纯文本正文是纯文本正文,那么最终的纯文本正文将是html正文,丢弃我提供的纯文本 我的问题:有没有人知道如何让Gmail API使用我提供的明文,而不是自动为我生成回退 我注

我正在使用Gmail API用Python自动创建Gmail草稿。我需要创建HTML格式的电子邮件,但我个人也需要创建一个纯文本回退,因为这是正确的做法

我以为我已经完成了上述所有工作,直到我尝试使明文回退与HTML略有不同。谷歌似乎自行为我创建了纯文本回退,而不是使用我提供的,因此如果我的html正文是
html正文
,而我的纯文本正文是
纯文本正文
,那么最终的纯文本正文将是
html正文
,丢弃我提供的纯文本

我的问题:有没有人知道如何让Gmail API使用我提供的明文,而不是自动为我生成回退

我注意到一个相关的问题:如果我以不同的顺序附加HTML和纯文本正文,则会发生相反的情况——GMail将根据我的纯文本自动生成HTML正文。所以它似乎只关注最后一个附着的身体

我正在使用的代码的精简版本:

import base64
import os
import httplib2
import oauth2client
from oauth2client import client
from oauth2client import tools
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from pathlib import Path
from apiclient import errors
from apiclient import discovery

SCOPES = 'https://mail.google.com/'
CLIENT_SECRET_FILE = 'client_id.json'
APPLICATION_NAME = 'Test Client'

def get_credentials():
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir, 'gmail-python-quickstart.json')

    store = oauth2client.file.Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else:  # Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials


def CreateDraft(service, user_id, message_body):
    message = {'message': message_body}
    draft = service.users().drafts().create(userId=user_id, body=message).execute()
    return draft


def CreateTestMessage(sender, to, subject):
    msg = MIMEMultipart('alternative')
    msg['Subject'] = subject
    msg['From'] = sender
    msg['To'] = to
    plain_text = "Text email message. It's plain. It's text."
    html_text = """\
<html>
  <head></head>
  <body>
    <p>HTML email message</p>
    <ol>
        <li>As easy as one</li>
        <li>two</li>
        <li>three!</li>
    </ol>
    <p>Includes <a href="http://stackoverflow.com/">linktacular</a> goodness</p>
  </body>
</html>
"""

    # Swapping the following two lines results in Gmail generating HTML
    # based on plaintext, as opposed to generating plaintext based on HTML
    msg.attach(MIMEText(plain_text, 'plain')) 
    msg.attach(MIMEText(html_text, 'html'))

    print('-----\nHere is the message:\n\n{m}'.format(m=msg))
    encoded = base64.urlsafe_b64encode(msg.as_string().encode('UTF-8')).decode('UTF-8') 
    return {'raw': encoded}


def main():
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('gmail', 'v1', http=http)

    my_address = 'example@gmail.com' # Obscured to protect the culpable

    test_message = CreateTestMessage(sender=my_address,
                                 to='example@gmail.com',
                                 subject='Subject line Here')

    draft = CreateDraft(service, my_address, test_message)


if __name__ == '__main__':
    main()
导入base64
导入操作系统
导入httplib2
导入oauth2client
从oauth2client导入客户端
从oauth2client导入工具
从email.mime.text导入MIMEText
从email.mime.multipart导入MIMEMultipart
从pathlib导入路径
从apiclient导入错误
从apiclient导入发现
范围https://mail.google.com/'
CLIENT\u SECRET\u FILE='CLIENT\u id.json'
应用程序名称='测试客户端'
def get_凭据():
home\u dir=os.path.expanduser(“~”)
credential_dir=os.path.join(home_dir,“.credentials”)
如果操作系统路径不存在(凭证目录):
os.makedirs(凭证目录)
credential\u path=os.path.join(credential\u dir,'gmail python quickstart.json')
store=oauth2client.file.Storage(凭证路径)
凭据=store.get()
如果不是凭据或凭据。无效:
flow=client.flow\u from\u clientsecrets(client\u SECRET\u文件,作用域)
flow.user\u agent=应用程序\u名称
如果标志:
凭据=工具。运行\u流(流、存储、标志)
else:#仅在与Python 2.6兼容时才需要
凭据=工具。运行(流、存储)
打印('将凭证存储到'+凭证路径)
返回凭证
def CreateDraft(服务、用户id、消息正文):
message={'message':message_body}
draft=service.users().draft().create(userId=user\u id,body=message)。execute()
退票
def CreateTestMessage(发件人、收件人、主题):
msg=MIMEMultipart('alternative')
msg['Subject']=主语
msg['From']=发件人
msg['To']=To
plain_text=“文本电子邮件。它是纯文本。它是文本。”
html_text=“”\
HTML电子邮件

  • 一帆风顺
  • 两个
  • 三个
  • 包括善良

    """ #交换以下两行将导致Gmail生成HTML #基于纯文本,而不是基于HTML生成纯文本 msg.attach(MIMEText(纯文本,'plain')) msg.attach(MIMEText(html_text,'html')) print('----\n是消息:\n\n{m}。格式(m=msg)) encoded=base64.urlsafe\u b64encode(msg.as\u string().encode('UTF-8')).decode('UTF-8')) 返回{'raw':编码的} def main(): 凭证=获取凭证() http=credentials.authorize(httplib2.http()) service=discovery.build('gmail','v1',http=http) 我的地址是example@gmail.com"为了保护罪魁祸首, test\u message=CreateTestMessage(发送者=我的地址, 到example@gmail.com', subject='subject line Here') draft=CreateDraft(服务、我的地址、测试消息) 如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu': main()
    更新:以下是我发送给Gmail的内容与从Gmail发送的内容的对比,分别是HTML然后明文和明文然后HTML顺序(生成不同的结果)

    TL;医生:没有

    草稿对象与web UI和移动UI共享,如果文本/纯文本不仅仅是文本/html的简单转换,那么一旦用户使用任何其他UI编辑消息,特殊定制就会丢失。使用草稿UI的原因是允许用户在其他界面之间共享这些草稿


    如果你不在乎/不想拥有这种能力,就不要使用草稿,只需在结尾处发送(),这与SMTP-MSA一样允许更大的灵活性。

    你能用自己的电子邮件作为收件人创建草稿,发送它,然后用
    show original
    查看发送的邮件并显示内容吗?我很想看看。:)我确实可以。事实上,这就是我发现差异的原因。用一个链接来更新文章,以起草样本。另外,礼仪/风格问题:最好将这样的上下文作为外部链接(例如GIST)或嵌入原始文章中?我担心主帖子太长了,但我也担心主帖子可能会提供全部内容。老实说,我不知道这方面的礼仪。我喜欢现在的方式,因为正如你所说,要点相当大谢谢你的检查。我并没有尝试仅仅发送,因为这个特定的用例需要创建草稿,然后在发送之前运行QA过程。很高兴知道如果我直接去送信的话,我会把事情做好的!我们要求这些电子邮件在发送前必须经过质量保证人员的审查,因此,除非我们能找到其他方法在发送前审查电子邮件的最终形式,否则直接发送()是不可取的。考虑到这些限制,我认为我的最佳解决方案是“只发布HTML版本,并为Gmail自动提供文本回退而感到高兴”是的,我认为