首页 > 解决方案 > 使用带有 Python 的 Gmail API 获取消息,然后发送到另一封电子邮件

问题描述

我正在按照此线程上的建议使用 Python 设置批量转发。我正在尝试使用特定关键字在收件箱中搜索邮件,获取这些邮件的邮件 ID,然后将这些邮件发送给其他人。

搜索和获取 ID 部分工作正常。这是代码:

def search_message(service, user_id, search_string):
    # initiate the list for returning
    list_ids = []

    # get the id of all messages that are in the search string
    search_ids = service.users().messages().list(userId=user_id, q=search_string).execute()

    # if there were no results, print warning and return empty string
    try:
        ids = search_ids['messages']

    except KeyError:
        print("WARNING: the search queried returned 0 results")
        print("returning an empty string")
        return ""

    if len(ids)>1:
        for msg_id in ids:
            list_ids.append(msg_id['id'])
        return(list_ids)

    else:
        list_ids.append(ids['id'])
        return list_ids

当我尝试发送消息时,事情变得很棘手。我目前正在对单个消息 ID 进行测试,这就是我尝试过的:

message_raw = service.users().messages().get(userId=user_id, id=msg_id,format='raw').execute()
message_full = service.users().messages().get(userId="me", id=msg_id, format="full", metadataHeaders=None).execute()

## get the subject line
msg_header = message_full['payload']['headers']

# this is a little faster then a loop
subj = [i['value'] for i in msg_header if i["name"]=="Subject"]
subject = subj[0] 

msg_str = base64.urlsafe_b64decode(message_raw['raw'].encode('UTF-8'))
msg_bytes = email.message_from_bytes(msg_str)

# get content type for msg
content_type = msg_bytes.get_content_maintype()

if content_type == 'multipart':
    # there will usually be 2 parts: the first will be the body as a raw string,
    # the second will be the body as html
    parts = msg_bytes.get_payload()

    # return the encoded text
    send_string = parts[0].get_payload()

    # force utf-8 encoding on the string
    send_string = send_string.encode('utf-8').decode('utf-8')

# now that we have the body in raw string, we will build a new mime object and
# send it via gmail
final_message = MIMEText(send_string)

# set send-to and subject line in the msg
final_message['to'] = to
final_message['subject'] = subject
final_message['from'] = 'tradethenewsapi@gmail.com'

# turn back into raw format and return
raw = base64.urlsafe_b64decode(final_message.as_bytes())
body = {'raw': raw}

但是,当我去发送实际的电子邮件时(正如这个线程所暗示的那样),

message_sent = (service.users().messages().send(userId='me', body=body).execute())

我不断收到此错误

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x89 in position 1: invalid start byte

无论我做什么search_string,它都不起作用,并不断给我 unicode 错误。

标签: pythongmail-api

解决方案


推荐阅读