Página 1 de 2

Libcurl - Send SMTP (Email)

Publicado: Jue Feb 04, 2021 2:07 pm
por ricardo arraes
Hey everybody!

I've been struggling trying to send mime-type email using the libcurl and mod_harbour, but finally made it!

*in this case I'm sending it from a gmail account

here it is:

Código: Seleccionar todo

FUNCTION sendSmtp(wto, wfrom, wpsw)

  LOCAL hCurl,uValue,nHandle,cTxt:=""

  curl_global_init()

  if ! empty( hCurl := curl_easy_init() )    

    cTxt:="From: Email Test <"+wfrom+">"+Chr(13)+Chr(10)+;
        "To: Somebody <"+Alltrim(wto)+">"+Chr(13)+Chr(10)+;
        "Subject: Sending email"+Chr(13)+Chr(10)+;
        "Date: Tue, 3 Feb 2021 20:40:16"+Chr(13)+Chr(10)+Chr(13)+Chr(10)+;
        "Hey, "+Chr(13)+Chr(10)+Chr(13)+Chr(10)+;
        "This is a test!"

    nHandle := Fcreate("C:\xampp\htdocs\example\tmp\test.txt")
    Fwrite(nHandle,cTxt )
    FClose(nHandle)

    curl_easy_setopt( hCurl, HB_CURLOPT_USE_SSL, HB_CURLUSESSL_TRY )	 
	  curl_easy_setopt( hCurl, HB_CURLOPT_UPLOAD )
    curl_easy_setopt(hCurl, HB_CURLOPT_USERNAME, wfrom)
    curl_easy_setopt(hCurl, HB_CURLOPT_PASSWORD, wpsw)
    curl_easy_setopt(hCurl, HB_CURLOPT_URL, "smtps://smtp.gmail.com:465")
    curl_easy_setopt( hCurl, HB_CURLOPT_PROTOCOLS, hb_bitOr( HB_CURLPROTO_SMTPS, HB_CURLPROTO_SMTP ) )	 
    curl_easy_setopt( hCurl, HB_CURLOPT_TIMEOUT_MS, 15000 )
    curl_easy_setopt(hCurl, HB_CURLOPT_FOLLOWLOCATION, 1)
    curl_easy_setopt(hCurl, HB_CURLOPT_SSL_VERIFYPEER, 0)
    curl_easy_setopt(hCurl, HB_CURLOPT_MAIL_FROM, wfrom)
    curl_easy_setopt(hCurl, HB_CURLOPT_MAIL_RCPT, {wto})
    curl_easy_setopt(hCurl, HB_CURLOPT_VERBOSE, 0)
    curl_easy_setopt(hCurl, HB_CURLOPT_UPLOAD, 1)    
    curl_easy_setopt( hCurl, HB_CURLOPT_UL_FILE_SETUP, "C:\xampp\htdocs\example\tmp\test.txt" )           


    IF (nret:=curl_easy_perform( hCurl )) == 0
      uValue := nret
    ELSE 
      uValue:=nret
    ENDIF
  ENDIF
  
  curl_global_cleanup()   

RETURN uValue

Re: Libcurl - Send SMTP (Email)

Publicado: Jue Feb 04, 2021 5:54 pm
por ramirezosvaldo
Gracias!!!!
Saludos

Re: Libcurl - Send SMTP (Email)

Publicado: Vie Feb 05, 2021 6:18 am
por mag071
Gracias Ricardo ;

Probé tu función de smtp
pero no me hace el envio
igual estoy usando en la prueba un cuenta gmail
con los permisos adecuados

si corro desde consola
curl --url "smtps://smtp.gmail.com:465" --ssl-reqd --mail-from "prograg2021@gmail.com" --mail-rcpt "mag071@gmail.com" --upload-file C:\xampp\htdocs\examples\tmp\test.txt --user "prograg2021@gmail.com:xxclavexx"

si me hace el envio correctamente

pero cuando lo hago desde modharbour no me lo hace,
lo único que cambie de tu función fue esta línea

curl_easy_setopt(hCurl, HB_CURLOPT_MAIL_RCPT, wto)

que aparecía
{wtol}

lo quite y puse
wto

de antemano gracias Ricardo.

Re: Libcurl - Send SMTP (Email)

Publicado: Vie Feb 05, 2021 12:55 pm
por ricardo arraes
Hello my friend.

sorry, my mistake, I'll correct it.
the right line is:

Código: Seleccionar todo

curl_easy_setopt(hCurl, HB_CURLOPT_MAIL_RCPT, {wto})
you gotta keep the {} because the HB_CURLOPT_MAIL_RCPT parameter is expecting an array, even if you are sending it to only one email address. I made the changes as you described and it didn't send the email, but using {wto} it worked fine!

Let me know if you are having any trouble :)

Re: Libcurl - Send SMTP (Email)

Publicado: Sab Feb 06, 2021 2:53 am
por mag071
Gracias Ricardo;

Pero no se porque razón a mi no me funciona el envio,
la prueba la estoy haciendo localmente
no en un servidor remoto,

usando curl desde linea de comando cmd como aparece en el post pasado me funciona bien.
es con un prg que no me corre
si intento usarlo desde ngrok para probar con https en la nube via gateway me aparece este error
ngrok gateway error
The server returned an invalid or incomplete HTTP response.

aclaro esto lo de local porque se de un problema que existía con php y mail() en modo local
o no se si debo colocar algún .dll en el directorio donde corre el .prg
Igual coloco el código que uso, que es una copia del tuyo.

Código: Seleccionar todo

#ifdef __PLATFORM__WINDOWS
   #include "c:\harbour\contrib\hbcurl\hbcurl.ch"
#else
   #include "/usr/include/harbour/hbcurl.ch"
#endif

function Main()

  ? sendSmtp( "emailto@gmail.com","emailfrom@gmail.com","clavegmailqueenvia" ) 

return nil

FUNCTION sendSmtp(wto, wfrom, wpsw)

  LOCAL hCurl,uValue,nHandle,cTxt:=""

  curl_global_init()

  if ! empty( hCurl := curl_easy_init() )    

    cTxt:="From: Email Test <"+wfrom+">"+Chr(13)+Chr(10)+;
        "To: Somebody <"+Alltrim(wto)+">"+Chr(13)+Chr(10)+;
        "Subject: Sending email"+Chr(13)+Chr(10)+;
        "Date: Tue, 3 Feb 2021 20:40:16"+Chr(13)+Chr(10)+Chr(13)+Chr(10)+;
        "Hey, "+Chr(13)+Chr(10)+Chr(13)+Chr(10)+;
        "This is a test!"

    nHandle := Fcreate("C:\xampp\htdocs\example\tmp\test.txt")
    Fwrite(nHandle,cTxt )
    FClose(nHandle)

    curl_easy_setopt(hCurl, HB_CURLOPT_USE_SSL, HB_CURLUSESSL_TRY )   
    curl_easy_setopt(hCurl, HB_CURLOPT_UPLOAD )
    curl_easy_setopt(hCurl, HB_CURLOPT_USERNAME, wfrom)
    curl_easy_setopt(hCurl, HB_CURLOPT_PASSWORD, wpsw)
    curl_easy_setopt(hCurl, HB_CURLOPT_URL, "smtps://smtp.gmail.com:465")
    curl_easy_setopt(hCurl, HB_CURLOPT_PROTOCOLS, hb_bitOr( HB_CURLPROTO_SMTPS, HB_CURLPROTO_SMTP ) )   
    curl_easy_setopt(hCurl, HB_CURLOPT_TIMEOUT_MS, 15000 )
    curl_easy_setopt(hCurl, HB_CURLOPT_FOLLOWLOCATION, 1)
    curl_easy_setopt(hCurl, HB_CURLOPT_SSL_VERIFYPEER, 0)
    curl_easy_setopt(hCurl, HB_CURLOPT_MAIL_FROM, wfrom)
    curl_easy_setopt(hCurl, HB_CURLOPT_MAIL_RCPT, {wto})
    curl_easy_setopt(hCurl, HB_CURLOPT_VERBOSE, 0)
    curl_easy_setopt(hCurl, HB_CURLOPT_UPLOAD, 1)    
    curl_easy_setopt(hCurl, HB_CURLOPT_UL_FILE_SETUP, "C:\xampp\htdocs\example\tmp\test.txt" )           

    IF (nret:=curl_easy_perform( hCurl )) == 0
      uValue := nret
    ELSE 
      uValue:=nret
    ENDIF
  ENDIF
  
  curl_global_cleanup()   

RETURN uValue

Gracias

Re: Libcurl - Send SMTP (Email)

Publicado: Lun Feb 08, 2021 10:22 am
por charly
Mr. Ricardo

Muy buen aporte :D

A ver si puedo probarlo este fin de semana

Gracias.

C.

Re: Libcurl - Send SMTP (Email)

Publicado: Mar Feb 09, 2021 9:47 pm
por ricardo arraes
Hey mag071!

Sorry for the late answer...

let me ask you a couple of questions.

Did you configured your gmail account to accept sending email from unsecure sources?

Did you check the permissions on the directory where you are creating the .TXT file?

Re: Libcurl - Send SMTP (Email)

Publicado: Jue Abr 15, 2021 4:24 pm
por Verhoven
¿Hay alguna manera de poder anezar un archivo al enviar el mail?

Re: Libcurl - Send SMTP (Email)

Publicado: Jue Abr 15, 2021 7:46 pm
por ricardo arraes
Hey Verhoven!

There's a greate example here in this repository:

https://github.com/vszakats/hb/blob/mas ... /email.prg

I haven't done any test over this example yet, but it seems to be funcional.

*remember that if you are following my example using hbcurl, the "lAPI_curl" variable in this example will be .T.

take a look at the line 143, probably that's what you are looking for...

Código: Seleccionar todo

...

IF lAPI_curl
         curl_easy_setopt( curl, HB_CURLOPT_HTTPHEADER, { ;
            "Date: " + hb_curl_date(), ;
            "To: " + cTo, ;
            "From: hbcurl " + cFrom, ;
            "Cc: " + cTo, ;
            "Message-ID: <dcd7cb36-11db-487a-9f3a-e652a9458efd@rfcpedant.example.org>", ;
            "Reply-To: " + cFrom, ;
            "Disposition-Notification-To: " + cFrom, ;
            "X-Priority: " + hb_ntos( 3 ), ;  /* 1: high, 3: standard, 5: low */
            "Subject: " + cSubject } )

         /* NOTE: 'charset' to be added when implemented */
         curl_easy_setopt( curl, HB_CURLOPT_MIMEPOST, { ;
            { "subparts" => { ;
              { "data" => cHTML, ;
                "type" => "text/html" }, ;
              { "data" => cText } }, ;
              "type" => "multipart/alternative", ;
              "headers" => { "Content-Disposition: inline" } }, ;
            { "filedata" => __FILE__ }, ;
            { "data" => Replicate( hb_BChar( 123 ), 1024 ), ;
              "type" => "image/png", ;
              "encoder" => "base64", ;  /* binary, 8bit, 7bit, base64, quoted-printable */
              "filename" => "mock.png" } } )
      ELSE
      
      ...
      
hope it helps you!

Re: Libcurl - Send SMTP (Email)

Publicado: Sab May 08, 2021 1:00 pm
por Baxajaun
Buenos días !

Lo habéis probado con 2FA (Doble factor de autenticación de la cuenta) ?

Nosotros en una aplicación web en php que utilizamos una cuenta de GMail (Corporativo) y usando el puerto 587 y usando TLS para el envio de forma segura. Hemos tenido que activar el 2FA sobre la cuenta de correo y después crear contraseña de aplicación.

- Activar Google 2FA

- Crear contraseña de aplicación

En contraseña de aplicación Seleccionar Otros y hacer clic en Generar y usaremos la contraseña generada para el envío del correo.

Podéis ver el proceso de 2FA y Generar contraseña de apliación en el siguiente enlace Generar contraseñas de aplicaciones en usuarios de Google APPS

Espero que esta información os sea de utilidad.

Muchas gracias.

Un abrazo,