如何在Gmail API中正确设置“回复至”和“参考”标头

时间:2019-05-04 16:22:45

标签: python api email gmail gmail-api

我正在尝试回复使用Gmail API收到的邮件。我尝试了以下代码,它将发送消息附加到我邮箱的线程中,但是对于接收者,它作为新消息发送。声明In-Reply-To和Reference标头的正确方法是什么?

def create_message(origin=None, destination=to, subject=None, msg_txt=None, thr_id=None):
    """Create a message for an email.
    Args:
      origin: Email address of the sender.
      destination: Email address of the receiver.
      subject: The subject of the email message.
      msg_txt: The text of the email message.
      thr_id: the threadId of the message to attach
    Returns:
      An object containing a base64url encoded email object.
    """
    message = MIMEText(msg_txt)
    message['to'] = destination
    message['from'] = origin
    message['subject'] = subject
    raw_msg={'raw': (base64.urlsafe_b64encode(message.as_bytes()).decode())}
    raw_msg['threadId'] =thr_id
    raw_msg['Reference'] = '<CANyAw3CWm33sKL80GMKp-b=8JgXz3MVPkvCVbJ_oK4NuGJcb3w@mail.gmail.com>'
    raw_msg['In-Reply-To'] = '<CANyAw3CWm33sKL80GMKp-b=8JgXz3MVPkvCVbJ_oK4NuGJcb3w@mail.gmail.com>'
    raw_msg['Message-ID'] = '<CANyAw3CWm33sKL80GMKp-b=8JgXz3MVPkvCVbJ_oK4NuGJcb3w@mail.gmail.com>'
    return raw_msg

我的主要方法如下,

def main():
    """Canned reply responder using the Gmail API.
    Creates a Gmail API service object and responds to a query with a standard response
    whilst giving it a label to ensure only 1 response per thread is sent
    """

    # get credentials first and create gmail service object
    store = file.Storage('token.json')
    creds = store.get()
    if not creds or creds.invalid:
        flow = client.flow_from_clientsecrets('gmailApiCredentials.json', SCOPES)
        creds = tools.run_flow(flow, store)
    gmail_service = build('gmail', 'v1', http=creds.authorize(Http()))

    # receive email messages
    q = 'subject:this is a test message'
    messages = list_messages_matching_query(gmail_service, user_id,
                                            query=q,
                                            maxResults=1)
    if not messages:
        print("No messages to show")
    else:
        pprint.pprint('Messages to show: {}'.format(messages))

    # get thread of first document - so you can label the thread itself if need be
    thread_id = messages[0]['threadId']
    thread = get_thread(gmail_service, user_id, thread_id)

    msg_id = messages[0]['id']
    message = get_message(gmail_service, user_id, msg_id)

    subject ='Re:this is a test message'
    msg = create_message(destination=to, origin=to,
                         subject=subject,
                         msg_txt='Hai', thr_id=thread_id)
    send_message(gmail_service,"me", msg)
    print("Message Sent")

2 个答案:

答案 0 :(得分:1)

我也遇到了这个问题,threadId出现在我的“顶层”标头中,如下所示:

return {'raw': base64.urlsafe_b64encode(message.as_string()), 'threadId': thread_id}

似乎可以解决问题!

答案 1 :(得分:1)

应按如下所示更改create_message方法,以设置“ Reference”和“ In-Reply-To”标头。

  def create_message(来源=无,目的地= TO,主题=无,msg_txt =无,thr_id =无,msgID =无):
    “”“为电子邮件创建一条消息。
    精氨酸:
      来源:发件人的电子邮件地址。
      目的地:收件人的电子邮件地址。
      主题:电子邮件的主题。
      msg_txt:电子邮件的文本。
      thr_id:要附加的消息的threadId
    返回值:
      包含base64url编码的电子邮件对象的对象。
    “”
    消息= MIMEText(msg_txt)
    message ['to'] =目的地
    message ['from'] =来源
    message ['subject'] =主题
    message.add_header('参考',msgID)
    message.add_header('In-Reply-To',msgID)
    raw_msg = {'raw':(base64.urlsafe_b64encode(message.as_bytes())。decode())}
    raw_msg ['threadId'] = thr_id
    返回raw_msg

 

可以通过以下方法获得正确的msgID

  ef get_mime_message(服务,user_id,msg_id):
    尝试:
        消息= service.users()。messages()。get(userId = user_id,id = msg_id,
                                                 format ='raw')。execute()

        msg_str = base64.urlsafe_b64decode(message ['raw'])。decode()

        mime_msg = email.message_from_string(msg_str)

        返回mime_msg
    除了errors.HttpError作为错误:
        print('发生错误:%s'%error
 

可以通过以下方式获取msgID,

  ms = get_mime_message(gmail_service,USER_ID,msg_id)
    msgID = format(ms ['Message-ID'])
 

请勿将msg_id与msgID混淆。 msg_id是gmail特定的,而msgID是全局的。此msgID应该在“参考”和“回复中”标头中使用。