Access to your Gmail using a script can be extremely useful,
as it allows you to export data from it based on queries or parameters and
manipulate the data freely. However, Gmail is highly secure, so this can be a
little tricky. Here’s how it’s done.
1.
Download GIT and install it
from https://git-scm.com/downloads
2.
Visit the GIT repository for
the Gmail PowerShell extension to download and install it: https://github.com/nblagoev/Gmail.ps#install
3.
Open Windows “Credential
manager” from the start menu
4.
Go to the Windows
Credentials tab
5.
Click “Add a generic
credential”
6.
Add your Gmail account
credentials
7.
Open a PowerShell admin
window
8.
Install the PowerShell
Credential Manager:
9.
Install-Module -Name
CredentialManager -AllowClobber -Force
-Verbose -Scope AllUsers
10.
Get your own “App Password”,
which is a unique character string that Google generates for your account. This
article shows the steps: https://support.google.com/accounts/answer/185833
11.
Use the following code to auth
to Gmail in the PowerShell window:
$Gmailcred = Get-Credential
(Then select your Gmail account, and type in
the app password you obtained in step 9)
1.
This creates a Gmail
session you can work-against:
$Gmail = New-GmailSession -Credential $Gmailcred
1.
Use the following loop to
retrieve messages and dump them into a text file. You can use various other
filters to create your query, such as a date/time range, subject keywords,
whatever you want. This example is for emails received from a specific contact:
$messages = $inbox | Get-Message $Gmail
-From "joe@cnn.com" | Receive-Message
$File
= 'c:\temp\DownloadedMessages.txt'
$Stream =
[System.IO.StreamWriter]::new($File)
foreach ($msg in $messages) {
$Stream.WriteLine($msg.Body)
}
The resulting file is a flat text with the full body of the
messages, which you can then parse using any other script you like, or just
archive for whatever purpose. You can also use other options instead of $msg.Body,
like $msg.subject, if you just want to list the subjects. You can also
substitute the $StreamWriteLine with some other commands to process the
messages as they are read by PowerShell. For example, you might prefer to
create an individual file from each message, or fish-out specific pieces of
text from the messages. There’s no limit to what you might do.
No comments:
Post a Comment