Mandar email usando auth v2. Google.

Aqui você poderá oferecer suas Contribuições, Dicas e Tutoriais (Texto ou Vídeo) que sejam de interesse de todos.

Moderador: Moderadores

Avatar do usuário
Itamar M. Lins Jr.
Administrador
Administrador
Mensagens: 7928
Registrado em: 30 Mai 2007 11:31
Localização: Ilheus Bahia
Curtiu: 1 vez

Mandar email usando auth v2. Google.

Mensagem por Itamar M. Lins Jr. »

Olá!
Peguei no canal google user. Autor Fazio Diego(2024)

Código: Selecionar todos

**
**  sendGmail.prg - Compile with hbcurl.hbc
**  Send email via Gmail using oAuth v2
**  Need create a Google project and have access_token. See:
**  https://github.com/mod-harbour/mod_harbour.v2/tree/master/Samples/goauth
**
**  Developed by Fazio Diego(2024)
**
*/

#include "hbcurl.ch"

FUNCTION sendGmail( cGMAILuser, cGMAILaccesstoken, cSubject, cDestMail, cMsg, aAttach )

   LOCAL aHeader := {}, curl, ncurlErr, ncode, cJsonRes
   LOCAL cGUrl := "https://www.googleapis.com/gmail/v1/users/me/messages/send"
   LOCAL cBody := "", cFile

   hb_default( @aAttach, {} )

   AAdd( aHeader, "Authorization: Bearer " + AllTrim( cGMAILaccesstoken ) )
   AAdd( aHeader, "Content-Type: application/json" )

   cBody += "From: " + cGMAILuser + hb_eol()
   cBody += "To: " + cDestMail + hb_eol()
   cBody += "Subject: " + cSubject + hb_eol()
   cBody += "MIME-Version: 1.0" + hb_eol()
   cBody += 'Content-Type: multipart/mixed; boundary="boundary_string"' + hb_eol() + hb_eol()
   cBody += "--boundary_string" + hb_eol()
   cBody += 'Content-Type: text/plain; charset="UTF-8"' + hb_eol()
   cBody += "Content-Transfer-Encoding: 7bit" + hb_eol() + hb_eol()
   cBody += cMsg + hb_eol() + hb_eol()

   IF Len( aAttach ) > 0
      FOR EACH cFile in aAttach
         cBody += "--boundary_string" + hb_eol()
         cBody += 'Content-Type: text/plain; name="' + hb_FNameNameExt( cFile ) + '"' + hb_eol()
         cBody += 'Content-Disposition: attachment; filename="' + hb_FNameNameExt( cFile ) + '"' + hb_eol()
         cBody += "Content-Transfer-Encoding: base64" + hb_eol() + hb_eol()
         cBody += hb_base64Encode( hb_MemoRead( cFile ) ) + hb_eol()
      NEXT
   ENDIF

   cBody += "--boundary_string--" + hb_eol()

   curl_global_init()

   IF ! Empty( curl := curl_easy_init() )

      curl_easy_setopt( curl, HB_CURLOPT_HTTPHEADER, aHeader )
      curl_easy_setopt( curl, HB_CURLOPT_URL, cGUrl )
      curl_easy_setopt( curl, HB_CURLOPT_SSL_VERIFYPEER, .F. )
      curl_easy_setopt( curl, HB_CURLOPT_SSL_VERIFYHOST, .F. )
      curl_easy_setopt( curl, HB_CURLOPT_DOWNLOAD )
      curl_easy_setopt( curl, HB_CURLOPT_DL_BUFF_SETUP )
      curl_easy_setopt( curl, HB_CURLOPT_POSTFIELDS, hb_jsonEncode( { 'raw' => hb_base64Encode( cBody ) } ) )

      ncurlErr := curl_easy_perform ( curl )

      IF ncurlErr > 0
         ? "Curl Error: " + Str( ncurlErr )
      ENDIF

      ncode := curl_easy_getinfo( curl, HB_CURLINFO_RESPONSE_CODE )
      IF ncurlErr == 0
         cJsonRes := curl_easy_dl_buff_get( curl )
      ELSE
         cJsonRes := "Curl error"
      ENDIF

      curl_easy_cleanup( curl )

   ENDIF

   curl_global_cleanup()

RETURN cJsonRes
Saudações,
Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
lucimauro
Usuário Nível 3
Usuário Nível 3
Mensagens: 465
Registrado em: 21 Set 2004 21:02
Localização: Sobral-CE

Mandar email usando auth v2. Google.

Mensagem por lucimauro »

Eu ate vi um exemplo aqui e tentei testar mais mais apanhei e não consigo compilar Hbcurl usando Harbour 3.2
Não consegui gerar a hbcurl.a e nem encontrei um versão compilada que funcione aqui sempre dando erro ao compilar.
SOSSOFT
Usuário Nível 3
Usuário Nível 3
Mensagens: 118
Registrado em: 23 Out 2024 10:04

Mandar email usando auth v2. Google.

Mensagem por SOSSOFT »

Gmail não funciona mais com hb_tip?
Avatar do usuário
Itamar M. Lins Jr.
Administrador
Administrador
Mensagens: 7928
Registrado em: 30 Mai 2007 11:31
Localização: Ilheus Bahia
Curtiu: 1 vez

Mandar email usando auth v2. Google.

Mensagem por Itamar M. Lins Jr. »

Olá!
Começando aqui o PROCESSO!
Essa parte de pegar ID e Senha no Google Clound.
Agora é compilar a hbcurl

Saudações,
Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
Avatar do usuário
Itamar M. Lins Jr.
Administrador
Administrador
Mensagens: 7928
Registrado em: 30 Mai 2007 11:31
Localização: Ilheus Bahia
Curtiu: 1 vez

Mandar email usando auth v2. Google.

Mensagem por Itamar M. Lins Jr. »

Olá!
Fui até onde pude entender.
E parece que é "quase" impossível!!!!
Pq tenho que instalar um SERVIDOR WEB aqui, para conversar com o google.(É mole ?) Até linkar as libs(hbcurl) estaticamente consegui. em 64Bit!
2024-11-07_16-59-41.png
Para linkar a hbCurl estática vai precisar disso ai em baixo:

Código: Selecionar todos

#colocar essa linha no arquivo .hbc ai do seu projeto
{win}libs=unistring idn2 bcrypt ws2_32 wldap32 crypto crypt32 nghttp2 nghttp3 zstd brotlicommon brotlienc brotlidec ntdll psl iconv 
Mas desisti, muito mais simples usar o ThunderBird via linha de comando. Não irei instalar servidor web em nenhum cliente, nem vou ficar mandando servidor A ou B ou C ficar retornando arquivo json...
Ou mais simples pagar um servidor de email que funcione da maneira tradicional.
Aqui a saga para instalar um servidor WEB para conversar com o google.

Código: Selecionar todos

There are three different things...

Your project credentials (a .json file downloaded from Google Console Dev)
The authorization code (obtained after the Google sign-in screen)
The access token (sent by Google via GET to your redirect_uri)
To use the function I uploaded, you need to have the access token. To do this, first create your project in Google Console Dev, enable the Gmail API, create your consent screen with the correct redirect URI, and also enable permissions there to send Gmail emails (.../auth/gmail.send). Once you have this set up, download the credentials .json file.

Next, you'll need to construct the URL so that Google prompts the user for permission to use the API that you've specified in the URL's scope. For this, you'll need to use a web server. The URL you need to create has this format:

https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id=client_id&redirect_uri=redirect_uris&scope=https://www.googleapis.com/auth/gmail.send&access_type=offline&include_granted_scopes=true" class="google-btn"

You need to get client_id and redirect_uri from your credentials .json file. When you visit this URL, Google's sign-in page will appear, asking to authorize the services listed in the scope. If the sign-in is successful, Google will redirect via GET to your redirect_uri with the access_token. You only need to perform this step once; once saved, you can use the token as many times as needed for the requested service, in our case, Gmail.
In summary, to obtain an access_token, you'll need to use a web server to handle the request from the URL detailed above. I included an example for mod_harbourV2.1 showing how to obtain an access token to use Google sign-in in a web app. Just add the Gmail scope as detailed above, and you're all set.

Diego
Bem, foi o que entendi.

Saudações,
Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
Avatar do usuário
Itamar M. Lins Jr.
Administrador
Administrador
Mensagens: 7928
Registrado em: 30 Mai 2007 11:31
Localização: Ilheus Bahia
Curtiu: 1 vez

Mandar email usando auth v2. Google.

Mensagem por Itamar M. Lins Jr. »

Olá!
Ah! sim! já ia me esquecendo.
Retirar a linha -> curl_global_init()! dá problema em modo MT. Não é necessária
IF ! Empty( curl := curl_easy_init() ) //-> curl_easy_init() já chama ela.

Para quem quer usar via servidor web.

Saudações,
Itamar M. Lins Jr.
Saudações,
Itamar M. Lins Jr.
Responder