Deleting Gmail Emails via Google API using Powershell v2.0

吃可爱长大的小学妹 提交于 2020-01-11 10:48:48

问题


$user = "example@gmail.com"
$pass= "examplepassword" 
$secpasswd = ConvertTo-SecureString $user -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($pass, $secpasswd)

Invoke-RestMethod  'https://www.googleapis.com/gmail/v1/users/me/messages/0' -Method Delete -Credentials $cred

So, my problem here is twofold.

I originally tried using Invoke-WebRequest to delete gmail emails via the Google API with a http delete request. However, this did not work because Powershell 2.0 does not support Invoke-WebRequest.

Thereafter, I turned to attempting to utilize Invoke-RestMethod after experimentation with IMAP and POP3, which both required external dependencies (Adding .dlls to the machines I am working with is not optimal).

Therefore, if someone could show me the appropriate way to delete an email via the Google API in Powershell, I would appreciate it. I have provided some sample code as to what I am working with above. Please excuse any mistakes it may contain, as I am relatively new to Powershell, and my experience remains limited in working with RESTful services.


回答1:


The GMail API is going to require Oauth2 authentication unless this is a gsuit / domain admin / GMail account in which case you can use a service account for authentication. In either case you cant use login and password.

My powershell knowledge is very limited have you considered doing this directly though the mail server IMAP and SMTP and not using the API. No idea if that's possible or not with powershell

Update:

I was able to do it using Invoke-WebRequest you will still need to get an access token first.

Invoke-WebRequest -Uri "https://www.googleapis.com/gmail/v1/users/me/messages/0?access_token=$accesstoken"-Method Get | ConvertFrom-Json

seams to also work

Invoke-RestMethod -Uri "https://www.googleapis.com/gmail/v1/users/me/messages/0?access_token=$accesstoken"-Method Get 

Put up a the code for OAuth on GitHub if your interested: Google Oauth Powershell



来源:https://stackoverflow.com/questions/41236955/deleting-gmail-emails-via-google-api-using-powershell-v2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!