获取邮件,然后使用带有Python的Gmail API发送给另一封电子邮件

时间:2019-10-16 23:42:32

标签: python gmail-api

我正在遵循this thread上的建议,以使用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}

但是,当我发送实际的电子邮件时(如this thread所建议的那样),

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错误。

0 个答案:

没有答案