通过无干预脚本导出GMail联系人

10 投票
4 回答
4790 浏览
提问于 2025-04-17 10:37

GMail有一个很方便的功能,可以让你把所有联系人导出为CSV文件。如果你这样做,然后查看浏览器的历史记录,你会发现用来开始下载的链接看起来像这样:

https://mail.google.com/mail/c/data/export?exportType=GROUP&groupToExport=%5EMine&out=GMAIL_CSV&tok=rQt5BTUBABA.N0gr2-zKkG9868fM7tF_FQ.fOgeVayblkGavK2AuFjZ2t

我想写一个Python的批处理脚本,每晚自动下载这个CSV文件到我的服务器上,但我不知道怎么获取“tok”这个参数。我查过Google的OAuth,但这似乎是一个需要人来操作的过程,而我需要在凌晨3点的时候自动完成,因为这个时候所有人都在睡觉。

这能做到吗,还是说Google把我的邮箱账号弄得太“安全”,以至于我无法通过无人值守的脚本访问它?

谢谢!
Bryon M. Elliott

4 个回答

0

可以看看 Gmail 的接口文档:http://code.google.com/apis/gmail/oauth/code.html

2

我在找一些类似的解决方案,但因为找不到现成的解决办法,所以我自己动手做了一个:(请原谅我这个懒散的脚本,只是想让它能工作 :D)

#!/bin/sh 
# google api requirements:
# https://developers.google.com/gdata/articles/using_cURL
# https://developers.google.com/gdata/faq#clientlogin
# https://developers.google.com/google-apps/contacts/v3/
# https://developers.google.com/google-apps/contacts/v3/reference
# json parser:
# https://github.com/dominictarr/JSON.sh#jsonsh
# recommendation(optional):
# https://developers.google.com/accounts/docs/OAuth2UserAgent

# echo "logging in to google and saving contact with given caller-number."
Auth=$(curl --silent https://www.google.com/accounts/ClientLogin --data-urlencode Email=${Email} --data-urlencode Passwd=${Passwd} -d accountType=GOOGLE -d source=Google cURL-Example -d service=cp | grep Auth | cut -d= -f2)
curl -o ${dir}/${tmpfile} --silent --header "Authorization: GoogleLogin auth=$Auth" "https://www.google.com/m8/feeds/contacts/$Email/full?v=3.0&q=$2&alt=$Format"

这可能会帮你找到你的解决方案;)

5

首先,你需要用你的账号和密码进行身份验证(可以参考这个链接:http://developers.google.com/accounts/docs/AuthForInstalledApps

auth=`curl --silent -d Email=whatever@gmail.com -d Passwd=yourpwd -d service=contacts https://www.google.com/accounts/ClientLogin|grep ^Auth=|cut -d= -f2`

接下来,获取那个神秘的“tok”变量。我发现它是一个JSON请求的一部分:

tok=`curl --silent --header "Authorization: GoogleLogin auth=$auth" "https://www.google.com/s2/gastatus?out=js&rc=0" |sed 's/,/\n/g' |grep AuthToken |cut -d'"' -f6`

然后,下载CSV文件(谷歌格式)。这个过程和手动下载是完全一样的,具体步骤可以参考这个链接:support.google.com/mail/answer/24911?hl=en

curl -s --stderr - -L -o contacts-google-whatever\@gmail.com-$(date +%Y-%m-%d-%H.%M.%S).csv -H "Authorization:GoogleLogin auth=$auth" --insecure "https://www.google.com/s2/data/exportquery?ac=false&cr=true&ct=true&df=true&ev=true&f=g2&gids=6&gp=true&hl=en-US&id=personal&max=-1&nge=true&out=google_csv&sf=display&sgids=6%2Cd%2Ce%2Cf%2C17&st=0&tok=$tok&type=4"

变量“out”可以是google_csv、outlook_csv或vcard中的一个。我的代码是用bash写的,你可能想把curl命令换成Python的写法。重要的信息是那些变量和网址。

撰写回答