Jump to content
Fivewin Brasil

DEFINE MAIL oMail - Enviar Erros do programa


kapiaba

Recommended Posts

Galera dá para criticar esta função, porfa:

#Include "FiveWin.ch"
#Include "Mail.ch"
 
FUNCTION Main()
 
   LOCAL MailTo, cSndFile, cText, cSubj
 
   // Campo Para:
   MailTo   := "contato@pleno.com.br; joao@pleno.com.br"
 
   // Arquivo a Anexar
   cSndFile := "C:\FWH1306\SAMPLES\VoNfeUtil2G.Log"
 
   // Texto do Corpo do Email
   cText    := "Favor Verificar Erros da Nota Fiscal Eletrônica - Arquivo Anexo"
 
   // Titulo do Email
   cSubj    := "Erros da Nota Fiscal Eletrônica"
 
   //LogOn in the mail system
   MAPILogOn()
 
   // Abre o OutLook Express ou o Windows Live Mail
   SendMail2( MailTo, cSndFile, cText, cSubj )
 
   // LogOff from the mail system
   MAPILogOff()
 
RETURN NIL
 
// Envia o arquivo de erro do programa
 
FUNCTION SendMail2( MailTo, cSndFile, cText, cSubj )
 
   LOCAL oMail
 
   DEFINE MAIL oMail           ;
      SUBJECT cSubj            ;
      TEXT cText               ;
      FILES cSndFile, cSndFile ;
      FROM USER                ;
      TO MailTo
 
   ACTIVATE MAIL oMail
 
   IF ( oMail:nRetCode ) = 0
 
      MsgInfo( "Mensagem Enviada com Sucesso", "Aviso" )
 
   ELSE
 
      MsgInfo( OemToAnsi( "NÆo Foi Possivel Enviar a Mensagem de Erro" )+CRLF+;
               OemToAnsi( "Por Favor Verifique se o Enviador de Email" )+CRLF+;
               OemToAnsi( "OutLook Express ou Windows Live Mail,     " )+CRLF+;
               OemToAnsi( "Est  Definido Como Enviador PadrÆo, nas   " )+CRLF+;
               OemToAnsi( "Op‡äes da Internet - Internet Explorer.   " ),     ;
               OemToAnsi( "NÆo Foi Possivel Enviar a Mensagem de Erro" ) )
 
   ENDIF
 
RETURN( .T. )
 
/*
MAPI Mail Syntax:
 
DEFINE MAIL [ <oMail> ];
[ SUBJECT <cSubject> ];
[ TEXT <cText> ];
[ TYPE <cType> ];
[ DATE <dDate> ];
[ TIME <cTime> ];
[ CONVERSATION <cConversation> ]:
[ RECEIPT ];
[ FROM USER ];
[ FILES <cFilename1> ,<cDescript1>, <cFilenameN>, <cDescriptN> ] ];
[ ORIGIN <cOrigin> [ <cOriginAddress> ] ];
[ TO <cTarget1>, [ <cTargetAddress1> ] [ <cTargetN> [ <cTargetAddressN> ] ] ];
 
DEFINE MAIL...FILES cFilename1,,cFilename2,,Filename3
*/
 
// FIM DO PROGRAMA
Link to comment
Share on other sites

STATIC FUNCTION SendEmail(cErrorLog)

	TRY
	 oCfg := CREATEOBJECT( "CDO.Configuration" )
	   WITH OBJECT oCfg:Fields
	        :Item( "http://schemas.microsoft.com/cdo/configuration/smtpserver"       ):Value := <seu_smtp>
	        :Item( "http://schemas.microsoft.com/cdo/configuration/smtpserverport"   ):Value := <sua_porta>
	        :Item( "http://schemas.microsoft.com/cdo/configuration/sendusing"        ):Value := 2
	        :Item( "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate" ):Value := .T.
	        :Item( "http://schemas.microsoft.com/cdo/configuration/smtpusessl"       ):Value := .F.
	        :Item( "http://schemas.microsoft.com/cdo/configuration/sendusername"     ):Value := <seu_email>
	        :Item( "http://schemas.microsoft.com/cdo/configuration/sendpassword"     ):Value := <sua_senha>
	        :Item( "http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout")   :Value = 30
			  :Update()
	      END WITH
	CATCH oError
	 MsgInfo( "Não Foi possível Enviar o e-Mail!"  +CRLF+ ;
	          "Error: "     + Transform(oError:GenCode,   nil) + ";" +CRLF+ ;
	          "SubC: "      + Transform(oError:SubCode,   nil) + ";" +CRLF+ ;
	          "OSCode: "    + Transform(oError:OsCode,    nil) + ";" +CRLF+ ;
	          "SubSystem: " + Transform(oError:SubSystem, nil) + ";" +CRLF+ ;
	          "Mensaje: "   + oError:Description, "CDO.Configuração" )
	
	END

	aAttach := SetErrorPath() + SetErrorFileName()

	TRY
		oMsg := CREATEOBJECT ( "CDO.Message" )
		WITH OBJECT oMsg
			:Configuration = oCfg
			:From = CHR(34) + <nome_empresa_cliente> + CHR(34)+ <email_seu_envio>
			:To = <para_qual_email_enviar_o_LOG>
			:Subject = "Envio Automático do Erro"
			:MDNRequested = .F.
			:TextBody = cErrorLog
			:AddAttachment(aAttach)
			:Send()
		END WITH
		MsgInfo("Mensagem Enviada com Sucesso!","Atençao")
	CATCH oError
		 MsgInfo( "Não Foi possível Enviar o e-Mail!"  +CRLF+ ;
		          "Error: "     + Transform(oError:GenCode,   nil) + ";" +CRLF+ ;
		          "SubC: "      + Transform(oError:SubCode,   nil) + ";" +CRLF+ ;
		          "OSCode: "    + Transform(oError:OsCode,    nil) + ";" +CRLF+ ;
		          "SubSystem: " + Transform(oError:SubSystem, nil) + ";" +CRLF+ ;
		          "Mensaje: "   + oError:Description, "CDO.Message" )
	END TRY

RETURN NIL

mas tb, de vez enquando, dá erro, não sei o pq, mas na maioria das vezes funciona.

Link to comment
Share on other sites

Eu uso esta para os clientes enviarem emails dos arquivos .xml das nfe´s, só dá erro se o servidor de email deles ou a senha estiver errada, uma troca de senha e já era, se mudar a porta já era, se mudar para https, já era.

Melhor é forçar que configurem o outlook express ou windows live mail.

Mas gostei da ideía.

Obg. abs

Link to comment
Share on other sites

a questão fica qdo o cliente não quer configurar um email na maquina, entende?

ahcei outro que funciona tb.

    static function SendEmail (cSubject, cBody, cMsg, oWnd, cImgFile)

      LOCAL oInit, oMail, aSet, i, lOk := .f.
      LOCAL lReceipt  := .f.
      LOCAL lAuth     := .f.
      LOCAL cFrom
      LOCAL aAttach

      DEFAULT cMsg := nil        //HTML Email

      aSet := ReadIni ()
      cFrom := TRIM (aSet[E_USER])+" <"+TRIM (aSet[E_FROM])+">"
      FOR i := 1 TO Len (aSet)
        lOk := !Empty (aSet[i])
        //? aSet[i]
      NEXT

      IF ! lOk
        MsgAlert (  aLang[emailALERT1],  aLang[emailALERT2])
        RETURN (nil)
      ENDIF
      FErase (cErrorPath+"Smtp.log")         // delete old logfile
       if file( cImgFile )
          aAttach := { cErrorPath+"error.log", cImgFile }
       else
          aAttach := { cErrorPath+"error.log" }
       endif

      oInit := TSmtp():New( aSet [E_SMTP] )
      oMail := TSmtp():New( aSet [E_SMTP], , lAuth, aSet [E_LOGIN], aSet [E_PASS] ) // [jlalin], IBTC
      oMail:cReplyTo         :=  aSet[E_FROM] //aSet [E_REPLYTO] //cReplyTo
      oMail:nGMT             := 1   // 8 = Pacific Standard Time (GMT -08:00) - Adjust this to your own Time Zone!
      //oMail:lTxtAsAttach     := .F.         // uncomment to force txt, log and htm files as inline as opposed to attachement
      oMail:nDelay           := 2
      oMail:oSocket:lDebug   := .T.         // uncomment to create log file
      oMail:oSocket:cLogFile := cErrorPath+"smtp.log"
      oMail:bConnecting      := {||MsgRun(  aLang[emailCONNECTING1] + aSet [E_SMTP] + " (" + oMail:cIPServer + ") "+ aLang[emailCONNECTING2]) }
      oMail:bConnected       := {||MsgRun (  aLang[emailCONNECTED] ) }
      oMail:SendMail( ;
            cFrom, ;                 // from/de
            { aSet[E_TO] }, ;        // to/para (arreglo) - I use cSender here also because it's an "autotest". Actually you would type a different address here
            cBody,;                  // Body/Mensaje
            cSubject,;               // Subject/Asunto
            aAttach, ;               //  Array of filenames to attach/Arreglo de nombres de archivos a agregar
            { }, ;                   // aCC
            {  }, ;                  // aBCC
            lReceipt, ;              // Return Receipt/acuse de recibo
            cMsg )                   // msg in HTML format/mensaje en HTML

      oInit:end()

   return (nil)

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...