BlackTDN Search

segunda-feira, 23 de agosto de 2010

Protheus :: Exemplo de WebService para envio de e-mail com anexo.

Hoje vou disponibilizar um exemplo de WebService que permite o envio de e-mail através do Protheus com a possibilidade de anexar um arquivo.

Para consumir o serviço desse WS usarei como "client" o WindowsPowerShell.



O nome do WS será: u_WsMail que possuirá o método SendMail.


#INCLUDE "APWEBSRV.CH"
#INCLUDE "PROTHEUS.CH"
#INCLUDE "TBICONN.CH"
#INCLUDE "TRYEXCEPTION.CH"

#DEFINE STR0001 "Web Service para Envio de e-mail"
#DEFINE STR0002 "Enviar e-mail"

/*/
WSSERVICE: u_WsMail
Autor:   Marinaldo de Jesus
Data:   22/08/2010

Descri‡…o: Enviar e Receber e-mails via WS do Protheus
Uso:  Envio e Recebimento de e-mail
/*/
WSSERVICE u_WsMail DESCRIPTION STR0001 NAMESPACE "http://localhost/naldo/u_wsmail.apw" //"Web Service para Envio de e-mail"

 
 WSDATA MailTo     AS String
 WSDATA Subject     AS String   OPTIONAL
 WSDATA Body      AS String   OPTIONAL
 WSDATA FileName     AS String    OPTIONAL
 WSDATA FileContent      AS BASE64BINARY  OPTIONAL

 WSDATA SendOk     AS Boolean

 WSMETHOD SendMail DESCRIPTION STR0002 //"Enviar e-mail"

ENDWSSERVICE

WSMETHOD;
   SendMail;
WSRECEIVE;
   MailTo,;

   Subject,;
   Body,;
   FileName,;
   FileContent;

WSSEND;
   SendOk;
WSSERVICE;
   u_WsMail

 
 Local aMailTo  := StrTokArr( Self:MAILTO , ";" )

 Local aMailCC  := {}
 Local aMailBCC  := {}

 Local aFile   := {}

 Local cSubject  := Self:Subject
 Local cBody   := Self:Body
 Local cFileName  := Self:FileName
 Local cFileContent := Self:FileContent
 
 Local cServer  := SuperGetMv( "MV_RELSERV" )

 Local cUser   := SuperGetMv( "MV_RELACNT" )
 Local cPassWord  := SuperGetMv( "MV_RELPSW" )

 Local cFrom   := SuperGetMv( "MV_RELFROM" )
 Local cUserAuth  := SuperGetMv( "MV_RELAUSR" )

 Local cPassAuth  := SuperGetMv( "MV_RELAPSW" )

 Local cTempDir  := ""

 Local cFilePath  := ""
 Local cMsgSoapFault := ""

 Local lFile   := .F.
 Local lAuth   := SuperGetMv( "MV_RELAUTH" )

 Local lWsMethodRet := .T.
 Local lTextFormat := .T.
 
 Local nBuffer
 Local nHandle
 Local nItried
 Local nTimeOut  := 60

 Local nAttempts   := 5
 Local nFileSize

 Local oException

 /*/

  MailAuth( cUser , cPassword )
  MailGetErr(<void>) -> cErr
  MailGetNumErr( <void>) -> nNumErr
  MailFormatText( lTextPlain )

  MailSmtpOn( cSmtp , cUser , cPassword , nTimeOut ) -> lSmtpOk
   MailSend( cFrom , aTo , aCc , aBcc , cSubject , cBody , aFiles , lText ) -> lSendOk
  MailSmtpOf( <void> )

 /*/
 
 TRYEXCEPTION 

  IF Empty( cFrom )
   cFrom := cUser
  EndIF 

  IF ( lAuth )

   IF Empty( cUserAuth )       
    cUserAuth := cUser
   EndIF
   IF Empty( cPassAuth )

    cPassAuth := cPassWord
   EndIF 
  EndIF 

  nItried := 0
  While !( Self:SendOk := MailSmtpOn( @cServer , @cUser , @cPassWord , @nTimeOut ) )

   IF ( ( ++nItried ) > nAttempts )
    cMsgSoapFault := MailGetErr()

    BREAK
   EndIF 
   Sleep( 100 )
  End While
 
  IF ( lAuth )

   nItried := 0
   While !( Self:SendOk := MailAuth( @cUserAuth , @cPassAuth ) )

    IF ( ( ++nItried ) > nAttempts )
     cMsgSoapFault := MailGetErr()

     BREAK
    EndIF 
    Sleep( 100 )
   End While
  EndIF

  lFile := !Empty( cFileName ) .and. !Empty( cFileContent )

  IF ( lFile )
   cFileName   := AllTrim( cFileName )

   IF ( "\" $ cFileName )
    cFileName  := SubStr( cFileName , Rat( "\" , cFileName ) + 1 )

   EndIF 
   cTempDir   := "\" + CriaTrab( NIL , .F. ) + "\"

   lFile    := MyMakeDir( cTempDir )
   IF ( lFile )

    cFilePath    := ( cTempDir + cFileName )
    lFile   := FileCreate( cFilePath , @nHandle , NIL , .F. )

                nFileSize  := Len( cFileContent )
    nBuffer   := 1

    While ( nFileSize > 0 )
     cBuffer := SubStr( cFileContent , nBuffer , 1024 )

     fWrite( @nHandle , @cBuffer , 1024 )
     nBuffer   += 1024

     nFileSize -= 1024
    End While
    lFile   := ( ( fError() == 0 ) .and. File( cFilePath ) )

    fClose( @nHandle )
    IF ( lFile )
     aAdd( aFile , cFilePath )

    EndIF 
   EndIF
  EndIF

  IF !( Self:SendOk := MailSend( @cFrom , @aMailTo , @aMailCC , @aMailBCC  , @cSubject , @cBody , @aFile , @lTextFormat ) )

   cMsgSoapFault := MailGetErr()
   BREAK
  EndIF

  IF File( cFilePath )

   FileErase( cFilePath )
  EndIF

  IF lIsDir( cTempDir )

   DirRemove( cTempDir )
  EndIF 

  MailSmtpOff()
 
 CATCHEXCEPTION USING oException
 
  Self:SendOk   := .F.
  lWsMethodRet   := .F.

  IF File( cFilePath )

   FileErase( cFilePath )
  EndIF

  IF lIsDir( cTempDir )

   DirRemove( cTempDir )
  EndIF 

  IF ( ValType( oException ) == "O" )

   cMsgSoapFault += IF( !Empty( oException:Description ) , oException:Description , "" )

   cMsgSoapFault += IF( !Empty( oException:ErrorStack ) , oException:ErrorStack  , "" )

  EndIF 

  SetSoapFault( "u_WsMail ::" + ProcName() , cMsgSoapFault )

 
 ENDEXCEPTION

Return( lWsMethodRet )

/*/
Fun‡…o:  MyMakeDir
Autor:  Marinaldo de Jesus 
Data:   22/08/2010

Descri‡…o: Cria um Diretorio
Uso:  Generico
/*/
Static Function MyMakeDir( cMakeDir , nTimes , nSleep  )

 Local lMakeOk
 Local nMakeOk
 
 IF !( lMakeOk := lIsDir( cMakeDir ) )

  MakeDir( cMakeDir )
  nMakeOk   := 0
  DEFAULT nTimes := 10

  DEFAULT nSleep := 1000
  While (;
    !( lMakeOk := lIsDir( cMakeDir ) );

    .and.;
    ( ++nMakeOk <= nTimes );

     )
   Sleep( nSleep )
   MakeDir( cMakeDir )

  End While
 EndIF

Return( lMakeOk )

/*/

Fun‡…o:  FileCreate
Autor:  Marinaldo de Jesus 
Data:   22/08/2010
Descri‡…o: Cria Arquivo e Retorna nHandle e nErr por Referencia
Uso:  Generico

/*/                             ³
Static Function FileCreate( cFile , nHandle , nErr , lClose )

 Local lCreateOk := .T.
 Local nCreateOk
 
 lCreateOk := ( ( nHandle := fCreate( cFile ) ) <> -1 )

 nCreateOk := 0
 IF !( lCreateOk )
  While (;

     !( lCreateOk := ( ( nErr := fError() ) == 0 ) );

     .and.;
     ( ++nCreateOk <= 50 );

    )
   Sleep( 100 )
   IF ( lCreateOk := ( ( nHandle := fCreate( cFile ) ) <> -1 ) )

    Exit
   EndIF
  End While
 EndIF
 
 DEFAULT lClose := .F.
 IF (;

   ( lCreateOk );
   .and.;
   ( lClose );

  )
  fClose( nHandle )
 EndIF  

Return( lCreateOk )

/*/
Fun‡…o:  FileErase
Autor:  Marinaldo de Jesus 
Data:   22/08/2010

Descri‡…o: Exclui Arquivo e Retorna nErr por Referencia
Uso:  Generico
/*/                             ³
Static Function FileErase( cFile , nErr )

 Local lEraseOk := .F.
 
 Local nEraseOk
 
 IF ( lEraseOk := File( cFile ) )

  fErase( cFile )
  nEraseOk := 0
  While (;

     ( ( nErr := fError() ) <> 0 );

     .and.;
     ( ++nEraseOk <= 50 );

    )
   Sleep( 100 )
   IF ( fErase( cFile ) <> -1 )

    Exit
   EndIF
  End While
  lEraseOk := !( File( cFile ) )

 EndIF

Return( lEraseOk )


Bem, agora vamos usar o Windows PowerShell para "consumir" esse ws.
Abra o console do Windows PowerShell e Digite:


$Ws = New-WebServiceProxy -Uri "http://localhost/naldo/ws/U_WSMAIL.apw?WSDL"

$Subject = "Arquivo TotvsShow"
$body = "Segue arquivo TotvsShow com o Show do Milhao da Totvs para o seu entretenimento"

$fileName = "TotvsShow.rar"
[byte[]]$fileContent = get-content -encoding byte -path "c:\downloads\TotvsShow.rar"

$Ws.SENDMAIL("teste.sendmail@teste.com",$Subject,$body,$fileName,$fileContent)
Onde a saída seria algo parecido com:



Windows PowerShell
Copyright (C) 2009 Microsoft Corporation. Todos os direitos reservados.

PS C:\Documents and Settings\marinaldo.jesus> cd\
PS C:\> $Ws = New-WebServiceProxy -Uri "http://localhost/naldo/ws/U_WSMAIL.apw?WSDL"
PS C:\> $Subject = "Arquivo TotvsShow"
PS C:\> $body = "Segue arquivo TotvsShow com o Show do Milhao da Totvs para o seu entretenimento"
PS C:\> $fileName = "TotvsShow.rar"
PS C:\> [byte[]]$fileContent = get-content -encoding byte -path "c:\downloads\To
tvsShow.rar"
PS C:\> $Ws.SENDMAIL("teste.sendmail@teste.com",$Subject,$body,$fileName,$fileContent)
True
PS C:\>






Bem, se baixou os arquivos de exemplo, compilou os fontes do "server" e do "client, modificou a url do exemplo e o e-mail do destinatário, provavelmente o seu e-mail foi enviado com sucesso.
Como sempre, basta clicar aqui, para obter todos os arquivos de exemplo relacionados a este "post".
[]s
иαldσ dj
....

Nenhum comentário:

Postar um comentário