简体   繁体   English

将电子邮件从一个Gmail邮箱导入到另一个Gmail邮箱

[英]Importing e-mails from one gmail mailbox to another

I have 2 Gmail accounts, and I use one ("gmail1") to forward all e-mail to the other one ("gmail2"). 我有2个Gmail帐户,我用一个(“ gmail1”)将所有电子邮件转发到另一个(“ gmail2”)。 This works fine, but I discovered recently (after years!) that in fact, Gmail does not forward all my e-mail, but only the e-mail it considers not to be spam. 这种方法效果很好,但我最近(几年后!)发现,事实上,Gmail不会转发我的所有电子邮件,而只会转发它认为不是垃圾邮件的电子邮件。 Therefore, checking my spam folder in gmail2 for missing e-mails, I have often blamed senders, when really the e-mail had gotten lost on gmail1. 因此,当我在gmail1上丢失电子邮件时,经常检查gmail2中的垃圾邮件文件夹中是否有丢失的电子邮件,我常常怪罪发件人。 I want to solve this programatically, by regularly checking for spam e-mails in gmail1 and importing them into gmail2 (then I'm fine with gmail2 categorizing as spam or not, as long as the mail makes its way there). 我想以编程方式解决此问题,方法是定期检查gmail1中的垃圾邮件并将其导入gmail2(然后,无论邮件是否发送到gmail2,我都可以将其分类为垃圾邮件)。 I'm only a very amateur programmer, and so far thanks to some samples from the gmail API docs, I've managed to log in to my accounts, and retrieve some messages corresponding to a query, including for example recent spam e-mails. 我只是一个非常业余的程序员,到目前为止,由于gmail API文档中的一些示例,我已经设法登录到我的帐户,并检索了与查询相对应的一些消息,包括最近的垃圾邮件。 However, I'm struggling with the "import" concept and how to use it. 但是,我在为“导入”概念及其使用方法而苦苦挣扎。 There are no Python examples for this, and I couldn't solve the problems I'm facing. 没有针对此的Python示例,我无法解决所面临的问题。

Where I am right now: - if I "get" a message from gmail1 and attempt an import_ call on gmail2, using the message I just retrieved, I get an error because threadId is not allowed - if I do the same and then "del message['threadId']" then the error becomes error 400 : 'raw' RFC822 payload message string or uploading message via /upload/* URL required. 我现在所在的位置:-如果我从gmail1中“获取”一条消息并尝试使用刚刚检索到的消息对gmail2进行import_调用,则会收到错误消息,因为不允许使用threadId-如果我这样做,则返回“ del” message ['threadId']“,然后错误变为错误400:“原始” RFC822有效负载消息字符串或需要通过/ upload / * URL上传的消息。 I've seen that there are some situations where upload is required, but I am completely lost as to what I should do to make this work. 我已经看到在某些情况下需要上载,但是我完全不知道该做些什么。

Here's what I have so far (sorry for the very hacky style): 到目前为止,这是我所拥有的(抱歉,这种样式很hacky):

# skipping imports
SCOPES = ['https://www.googleapis.com/auth/gmail.readonly','https://www.googleapis.com/auth/gmail.modify']


def getMessage(service, user_id, msg_id):
  """from gmail API examples"""
  try:
    message = service.users().messages().get(userId=user_id, id=msg_id).execute()
    return message
  except errors.HttpError as error:
    print ('An error occurred:' , error)


def listMessagesMatchingQuery(service, user_id, query=''):
    """from gmail API examples"""
    # skipping some code
    return messages

def login(accountId):
    """from gmail API examples, adapted to handle 2 accounts"""
    # skipping some code
    return build('gmail', 'v1', credentials=creds)

def importMessage(service, user_id, msg):
  """my daring attempt at using import, without any Python sample to use as a basis"""
  try:
    message = service.users().messages().import_(userId=user_id,  body=msg).execute()

    return message
  except errors.HttpError as error:
    print ('An error occurred:' , error)


if __name__ == '__main__':

    service_gmail = login('gmail2') 
    service_dnt = login('gmail1')

    messages = listMessagesMatchingQuery(service_dnt,"me","in:spam is:unread after:" + str(int((datetime.now() - timedelta(hours=12)).timestamp())))
    # this gets me some recent unread spam messages

    m=getMessage(service_dnt,"me",messages[0]['id'])
    # now I have a full message - I'm just investigating for now so the first message is enough

    del m['threadId']
    # if I don't do that, the error I get is that threadId is not allowed here, so I remove it

    imported = importMessage(service_gmail,"me",m)
    # this now gives me error 400 : 'raw' RFC822 payload message string or uploading message via /upload/* URL required

I'd like to find the way to make this work, so that the e-mail appears in gmail2 as if it had been received by gmail2 directly (though I would like to keep the To: address, as I use a catch-all on gmail1 and want to know which e-mail address the e-mail was directed to). 我想找到使这项工作有效的方法,以便使该电子邮件出现在gmail2中,就好像它是gmail2直接收到的一样(尽管我想保留To:地址,因为我使用了全包在gmail1上,并且想知道该电子邮件所指向的电子邮件地址)。 But right now, I get only errors about having to use upload; 但是现在,我只收到关于必须使用上载的错误; I'm not sure if that's what I really should be doing, and if it is , I have no idea how. 我不确定这是否是我真正应该做的,如果是,我不知道如何做。

Thanks a lot in advance for any help! 提前非常感谢您的帮助!

In the end I managed. 最后我设法了。 I had missed the fact that there are 2 ways to "get" messages, a simple one and a "raw" one. 我错过了以下事实:有两种“获取”消息的方法,一种是简单的,一种是“原始”消息。 With the "raw" way to access the message, I can use the import_ function easily: 通过“原始”方式访问消息,我可以轻松使用import_函数:

message = service_dnt.users().messages().get(userId="me", id=messageId,format='raw').execute()
imported = importMessage(service_gmail,"me",{'raw': message['raw']})

whereby the importMessage function is unchanged vs. the original code I posted. 从而importMessage函数与我发布的原始代码保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM