Giter Site home page Giter Site logo

geoffsmith82 / gmailauthsmtp Goto Github PK

View Code? Open in Web Editor NEW
98.0 19.0 11.0 392 KB

This project is a very basic demo showing how to authenticate with OAUTH2 and send an email message for gmail, microsoft/office365 as well as hotmail.com/outlook.com/live.com email addresses.

License: MIT License

Pascal 100.00%
delphi gmail oauth2 xoauth2-protocol authentication oauthbearer xoauth2 indy sasl hotmail

gmailauthsmtp's Introduction

GmailAuthSMTP

This project is a very basic demo showing how to authenticate with OAUTH2 and send an email message for gmail, microsoft/office365 as well as hotmail.com/outlook.com/live.com email addresses. Initially it was only for Gmail (hence the name), but has since been extended to support other other providers.

OAuth2 is an open standard for authorization that is used to grant access to resources protected by a server. It allows an application or service to authenticate with a resource server and access protected resources on behalf of a user, without requiring the user to provide their credentials directly to the application.

When a user wants to access their email using an email client or another application, the application can use OAuth2 to authenticate with the email service and request access to the user's email. The user is then prompted to log in to their email account and grant access to the application. Once access is granted, the application can use the OAuth2 access token to authenticate with the email service and access the user's email.

Using OAuth2 for authentication has several benefits. It allows users to grant access to their email without sharing their login credentials with the application, which helps to protect their privacy and security. It also makes it easier for users to access their email from multiple devices and applications, as they only need to grant access once and can then use the OAuth2 access token to authenticate with the email service from any device.

Google Setup

You will need to create a file called Globals.pas which contains the following constants

Microsoft Setup

Dependencies

This project requires OpenSSL. You can find the required files at https://github.com/IndySockets/OpenSSL-Binaries

Thanks

Geoffrey Smith

gmailauthsmtp's People

Contributors

geoffsmith82 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

gmailauthsmtp's Issues

Sending email via gmail:Too many login attempts

Hi!

The authentication button works success ( we have to use on the browser the [Go to OAuthTeszt (unsafe)) link.
But If we want to send an email ( Send MSG button) we got an error on this line: IdSMTP1.Authenticate;
Error message : " GMailAuthDemo.exe raised exception class EIdSMTPReplyError with message 'Too many login attempts, please try again later. b9-20020adfe309000000b0020d0c9c95d3sm2119253wrj.77 - gsmtp"

Check MSG and Check Imap are works well, just the Send MSG wasn't success,

Could you help me?

Thx G.!

Instructions for use with Office365

I've created an application token in Office365 and added it to Globals.pas, but when trying to Authenticate my browser pops up with the message

We're unable to complete your request
unauthorized_client: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal at https://go.microsoft.com/fwlink/?linkid=2083908.

However that link simply takes me back to the page where I created my application token (displaying the application token), so I'm assuming I've missed a step.

Any suggestions what I should be looking for ?

Microsoft tenant

Improve tenant property Implementation

After adding this code on unit REST.Authenticator.EnhancedOAuth

image

and in Globas.pas

image

solved the request on multiples tenance environment.

Microsoft Auth

Hi @geoffsmith82! Have you tried connecting with Microsoft's credentials? I don't know if I'm missing something, but after credentials login page is closed (in microsoft's login page), a message error is displayed stating that was not able to authenticate if you try sending a message.

Supporting other scopes for GMail

First off - great work on this, works like a charm with the included scope - but just might raise some eyebrows as it requires read and delete access to email.

Advice to others compiling on Delphi 10.1, add IPPeerClient to the uses clause, and cast TIdBytes to TBytes on the logging routines.

Any chance someone can help me with changing the scope to a more restricted scope - ie. gmail.send or gmail.compose?

ie. https://www.googleapis.com/auth/gmail.send

Listed here: [(https://developers.google.com/gmail/api/auth/scopes)]

These are all the rights that should be required for sending email, but if I try to apply that to the scope, it has an error saying issue with username/password which I think is just a general rights error really.

IPPeerCommon

Hi,

Nice project! I'm using D 10.2 Tokyo on win 7 with CHrome as default browser. When the authentication is finished I get the error:

IPProcs is not defined. Make sure IPPeerCommon (or an alternative IP Implementation unit) is in the uses clause

So I added IPPeerClient, as stated here:
https://stackoverflow.com/questions/39747533/error-when-creating-trestclient-no-peer-with-the-interface-with-guid-has

Which seems to work. But the IdHTTPSevrerCommand.Get is called twice. The first time for the toke, the second time it has an empty requestinfo.params and the value of the rawhttp = 'GET /favicon.ico HTTP/1.1'.

I've added:

if ARequestInfo.QueryParams = '' then Exit;

Which seems to solve the problem.

Error when authenticating

I juts downloaded you GMailAuthDemo app and ran it in Delphi 10.4.1

I have a Gmail account and when I Authenticate I get the follwoing error at "GMailAuthDemo" of "TEnhancedOAuth2Authenticator.ChangeAuthCodeToAccesToken":

raised exception class EHTProtocolException with message 'HTTP:1.1 400 Bad Request'

This happens when I select the Gmail account in the browser session.

What am I doing wrong?

TIA

error sending email

hello,

I have a problem sending an email, the error message is like this.
image

what causes this error message to appear?

Coping with Stupid users

I've just spent a day trying to debug why this oAuth2 stuff was failing for a particular customer. Seems that the customer was telling my application that they were using the email address someone@mydomain.com, but when the Microsoft authentication browser window popped up, they were actually authenticating against someone@mydomain.net. (it seems that their Microsoft account supports both domains)

I can't find any reference as to how to get oAuth2 to work with different email addresses like this, and to be frank I doubt it does, so I've added some code to my implementation of IdSASL.Outh.Base.

I've copied it below in case it's of use to anyone else.

unit IdSASL.OAuth.Base;

interface

uses
    Classes
  , SysUtils
  , IdSASL
  , System.NetEncoding
  , System.JSON
    ;

type
  TIdSASLOAuthBase = class(TIdSASL)
  private
    procedure SetToken(const Value: string);
    procedure SetUser(const Value: string);
    procedure ValidateCredentials;
  protected
    FToken: string;
    FUser: string;
  public
    property User: string read FUser write SetUser;
    property Token: string read FToken write SetToken;
  end;

implementation

resourcestring
  StrYourEmailProivder = 'Can not Authenticate with mail server: ' + #10+#13+#10+#13 +
  'Your email provider expects you to use the email address %s, but you are using %s';

procedure TIdSASLOAuthBase.SetToken(const Value: string);
begin
  FToken := Value;
  if not FUser.isempty then ValidateCredentials;

end;

procedure TIdSASLOAuthBase.SetUser(const Value: string);
begin
  FUser := Value;
  if not FToken.isempty then ValidateCredentials;
end;



function Base64URLDecode(const Base64URL: string): string;
var
  Base64Str: string;
begin
  // Replace Base64URL characters with Base64 characters
  Base64Str := StringReplace(Base64URL, '-', '+', [rfReplaceAll]);
  Base64Str := StringReplace(Base64Str, '_', '/', [rfReplaceAll]);

  // Add padding if necessary
  case Length(Base64Str) mod 4 of
    2: Base64Str := Base64Str + '==';
    3: Base64Str := Base64Str + '=';
  end;

  // Decode from Base64
  Result := TNetEncoding.Base64.Decode(Base64Str);
end;

function DecodeJWT(const Token: string): TJSONObject;
var
  Parts: TArray<string>;
  Payload: string;
  JSONPayload: TJSONObject;
begin
  Result := nil;

  // Split the JWT into its three parts
  Parts := Token.Split(['.']);

  if Length(Parts) <> 3 then
    raise Exception.Create('Invalid JWT token');

  // Decode the payload
  Payload := Base64URLDecode(Parts[1]);

  // Parse the JSON payload
  JSONPayload := TJSONObject.ParseJSONValue(Payload) as TJSONObject;

  if Assigned(JSONPayload) then
    Result := JSONPayload
  else
    raise Exception.Create('Invalid JSON payload in JWT token');
end;

function ExtractUPNFromJWT(const Token: string): string;
var
  Claims: TJSONObject;
  UPNValue: string;
begin
  Claims := DecodeJWT(Token);
  try
    if Assigned(Claims) then
    begin
      // Check if the "upn" claim exists and extract its value
      if Claims.TryGetValue<string>('upn', UPNValue) then
        Result := UPNValue
      else
        Result := 'UPN claim not found in the JWT token.';
    end;
  finally
    Claims.Free;
  end;
end;




procedure TIdSASLOAuthBase.ValidateCredentials;
Var
lEmail : string;
begin
  lEmail := ExtractUPNFromJWT(token);
  if CompareText(FUser,lEmail) <> 0 then
  raise exception.Create(Format(StrYourEmailProivder,[lEmail, FUser]));
end;

end.

how do we know that the mail was sent?

Hey,

This is a Great code. And I would like to thank you for supplying it.

In the Form there is a Check if Send. Which works if you send the mail to yourself.
Is there a way to receive a more definitive answer if the mail was accepted? to inform the user?

like checking in outgoing mail box?
or receiving status from the server ?

Thanks.

Globals

where is Globals.pas?
using d10.2.3

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.