Ver Mensaje Individual
  #7  
Antiguo 04-04-2025
elguille elguille is offline
Miembro
 
Registrado: ene 2005
Posts: 130
Reputación: 22
elguille Va por buen camino
Mediante esta función y las utilidades clever (imagino que se puede hacer igual con Indy) obtengo un token de acceso valido para office365

Código Delphi [-]
function TMainForm.GetOAuth2Token(ClientID, ClientSecret, TenantID: string): string;
var
  Http: TclHttp;
  Request: TclHttpRequest;
  JsonResponse: string;
  JsonObj: TJSONObject;
begin
  Result := '';
  Http := TclHttp.Create(nil);
  Request := TclHttpRequest.Create(nil);
  try
    // Especificar el tipo de contenido
    // Request.ContentType := 'application/x-www-form-urlencoded';

    // Agregar los parámetros para obtener el token
    Request.AddFormField('client_id', ClientID);
    Request.AddFormField('client_secret', ClientSecret);
    Request.AddFormField('scope', 'https://outlook.office365.com/.default');
    Request.AddFormField('grant_type', 'client_credentials');

    // Enviar la solicitud POST y obtener la respuesta JSON
    JsonResponse := Http.Post('https://login.microsoftonline.com/' + TenantID + '/oauth2/v2.0/token', Request);

    // Parsear el JSON manualmente con System.JSON
    JsonObj := TJSONObject.ParseJSONValue(JsonResponse) as TJSONObject;
    try
      if Assigned(JsonObj) then
        Result := JsonObj.GetValue<string>('access_token')
      else
        raise Exception.Create('Error procesando la respuesta JSON.');
    finally
      JsonObj.Free;
    end;

    if Result = '' then
      raise Exception.Create('No se pudo obtener el Access Token.');
  finally
    Http.Free;
    Request.Free;
  end;
end;
pero luego no hay manera de conectarme por IMAP
Código Delphi [-]
procedure tMainForm.LeerEmailsOffice365(const Token: string);
var
  Imap: TclImap4;
  Msg: TclMailMessage;
  i: Integer;
begin
  Imap := TclImap4.Create(nil);
  Msg := TclMailMessage.Create(nil);
  try
    Imap.Server := 'outlook.office365.com';
    Imap.Port := 993;
    Imap.UseTLS := ctImplicit;
//    Imap.UserName := edit1.text;
    Imap.UserName := edtuser.text;

    // Usar OAuth2 como mecanismo de autenticación
    Imap.Authorization := 'XOAUTH2';
//    Imap.Password := Token;  // Token obtenido previamente
    Imap.Authorization := 'Bearer: '+Token;  // Token obtenido previamente
    Imap.Open;
    Imap.SelectMailBox('INBOX');


    Imap.Close;
  finally
    Imap.Free;
    Msg.Free;
  end;
end;
o enviar algún email, siempre recibo "a0002 NO AUTHENTICATE failed" ¿alguna idea?
Responder Con Cita