Skip to content

Instantly share code, notes, and snippets.

@mugifly
Created December 2, 2012 05:01
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save mugifly/4187031 to your computer and use it in GitHub Desktop.
Save mugifly/4187031 to your computer and use it in GitHub Desktop.
Perl - Gmail IMAP Using OAuth 2.0 (XOAUTH2)
#!/usr/bin/env perl
# Perl - Gmail IMAP Using OAuth 2.0 (XOAUTH2)
# I referred to: http://eatenbyagrue.org/tags/oauth/index.html Thank you.
use strict;
use warnings;
use utf8;
use Mail::IMAPClient;
use URI::Escape;
use MIME::Base64;
my $oauth_token = "xxxxxxxxxxx"; # Get its token by using a Net::OAuth2 module, normally.
my $username = "xxxx@gmail.com"; # Login ID of the user same as an above token.
my $oauth_sign = encode_base64("user=". $username ."\x01auth=Bearer ". $oauth_token ."\x01\x01", '');
# detail: https://developers.google.com/google-apps/gmail/xoauth2_protocol
my $imap = Mail::IMAPClient->new(
Server => 'imap.gmail.com',
Port => 993,
Ssl => 1,
Uid => 1,
) or die('Can\'t connect to imap server.');
$imap->authenticate('XOAUTH2', sub { return $oauth_sign }) or die("Auth error: ". $imap->LastError);
print $imap->folders or die("List folders error: ". $imap->LastError);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment