Envio de Email com anexo release 12.1.2410 da Linha Protheus

Usamos a função TMailManager atualizada da TOTVS para envio de e-mail com anexo, conforme documentação no TDN:

https://tdn.totvs.com/display/tec/Classe+TMailMessage

No ambiente atual 12.1.23.10 funcionou, porém no ambiente novo 12.1.2410 (WebAgent) retornou o erro abaixo.

7.00.240223P-20250220
THREAD ERROR ([337412], RicardoD, INFO06) 01/04/2025 08:15:00
invalid handle used in file E:\build-dir\TP11-OF2430X-W6\lib_base\diskman.cpp at line 321
on U_FTSTMAIL(LIB_0004.PRW) 01/04/2025 08:10:00 line : 3091

Importante: Sem o anexo funciona normalmente.

2 curtidas

Uso esta rotina e está funcionando normalmente:

User Function BkSnMail(cPrw, cAssunto, cPara, cCc, cCorpo, aAnexos, lAviso)
Local aArea := GetArea()
Local nAtual := 0
Local lRet := .T.
Local oMsg := Nil
Local oSrv := Nil
Local nRet := 0
Local cFrom := Alltrim(GetMV(“MV_RELACNT”))
Local cUser := SubStr(cFrom, 1, At(‘@’, cFrom)-1)
Local cPass := Alltrim(GetMV(“MV_RELPSW”))
Local cSrvFull := Alltrim(GetMV(“MV_RELSERV”))
Local cServer := Iif(‘:’ $ cSrvFull, SubStr(cSrvFull, 1, At(‘:’, cSrvFull)-1), cSrvFull)
Local nPort := Iif(‘:’ $ cSrvFull, Val(SubStr(cSrvFull, At(‘:’, cSrvFull)+1, Len(cSrvFull))), 587)
Local nTimeOut := GetMV(“MV_RELTIME”)
Local cLog := “”
Local cPath := u_STmpDir()
//Local cPathH := U_STmpDir()
Local cArqLog := u_SLogDir()+“bksendmail.log”
Local cArqAviso := “”

Local cDrive       := ""
Local cDir         := ""
Local cNome        := ""
Local cExt         := ""
Local lUsaTLS      := .T.
Local aUsers       := {}

Default cPara      := ""
Default cAssunto   := ""
Default cCorpo     := ""
Default aAnexos    := {}
Default lAviso     := .T.

IF ValType(aAnexos) <> "A"
    aAnexos    := {}
ENDIF

cAssunto := StrIConv( cAssunto, "CP1252", "UTF-8")

u_xxLog(cArqLog,cPrw+"- Assunto: "+ALLTRIM(cAssunto)+" - Para: "+cPara+" - CC: "+cCC)

// Para testes
If "TST" $ UPPER(GetEnvServer()) .OR. "TESTE" $ UPPER(GetEnvServer())
	cPara := cCc := u_EmailAdm()
    u_MsgLog(cPrw,"E-mail simulado: "+TRIM(cAssunto))
EndIf
// Fim testes

If lAviso
    aUsers := u_EmailUsr(cPara+";"+cCC)
    If LEN(aAnexos) > 0
        cArqAviso := aAnexos[1]
        /*
        SplitPath( aAnexos[1], @cDrive, @cDir, @cNome, @cExt )
        cArqAviso := cPathH+cNome+cExt

        If ":" $ aAnexos[1]
            CpyT2S( cArqAviso , cPathH, .T. )
        Else
            If aAnexos[1] <> cArqAviso
                __CopyFile( aAnexos[1], cArqAviso )
            EndIf
        EndIf
        */
    EndIf
    u_BKMsgUs(cEmpAnt,cPrw,aUsers,"",cAssunto,cAssunto,"N",cArqAviso,DataValida(DATE()+1))
EndIf

//Se tiver em branco o destinatário, o assunto ou o corpo do email
If Empty(cPara) .Or. Empty(cAssunto) .Or. Empty(cCorpo)
    cLog += "001 - Destinatario, Assunto ou Corpo do e-Mail vazio(s)!" + CRLF
    lRet := .F.
EndIf

If lRet
    //Cria a nova mensagem
    oMsg := TMailMessage():New()
    oMsg:Clear()

    //Define os atributos da mensagem
    oMsg:cFrom    := cFrom
    oMsg:cTo      := cPara
	If !Empty(cCC)
		oMsg:cCC  := cCC
	EndIf
    oMsg:cSubject := cAssunto
    oMsg:cBody    := cCorpo

    //Percorre os anexos
    For nAtual := 1 To Len(aAnexos)
        //Se o arquivo não existir, procura na pasta tmp
        If !File(aAnexos[nAtual])
            If !(":" $ aAnexos[nAtual]) .AND. !("\" $ aAnexos[nAtual])
                aAnexos[nAtual] := U_STmpDir()+aAnexos[nAtual]
            EndIf
        EndIf

        //Se o arquivo existir
        If File(aAnexos[nAtual])

            If ":" $ aAnexos[nAtual]
                CpyT2S( aAnexos[nAtual] , cPath, .T. )
                SplitPath( aAnexos[nAtual], @cDrive, @cDir, @cNome, @cExt )
                aAnexos[nAtual] := cPath+cNome+cExt
            EndIf    

            //Anexa o arquivo na mensagem de e-Mail
            nRet := oMsg:AttachFile(aAnexos[nAtual])
            If nRet < 0
                cLog += "002 - Nao foi possivel anexar o arquivo '"+aAnexos[nAtual]+"'!" + CRLF
            EndIf

        //Senao, acrescenta no log
        ElseIf !Empty(aAnexos[nAtual])
            cLog += "003 - Arquivo '"+aAnexos[nAtual]+"' nao encontrado!" + CRLF
        EndIf
    Next

    //Cria servidor para disparo do e-Mail
    oSrv := tMailManager():New()

    //Define se irá utilizar o TLS
    If lUsaTLS
        oSrv:SetUseTLS(.T.)
    EndIf

    //Inicializa conexão
    nRet := oSrv:Init("", cServer, cUser, cPass, 0, nPort)
    If nRet != 0
        cLog += "004 - Nao foi possivel inicializar o servidor SMTP: " + oSrv:GetErrorString(nRet) + CRLF
        lRet := .F.
    EndIf

    If lRet
        //Define o time out
        nRet := oSrv:SetSMTPTimeout(nTimeOut)
        If nRet != 0
            cLog += "005 - Nao foi possivel definir o TimeOut '"+cValToChar(nTimeOut)+"'" + CRLF
        EndIf

        //Conecta no servidor
        nRet := oSrv:SMTPConnect()
        If nRet <> 0
            cLog += "006 - Nao foi possivel conectar no servidor SMTP: " + oSrv:GetErrorString(nRet) + CRLF
            lRet := .F.
        EndIf

        If lRet
            //Realiza a autenticação do usuário e senha
            nRet := oSrv:SmtpAuth(cFrom, cPass)
            If nRet <> 0
                cLog += "007 - Nao foi possivel autenticar no servidor SMTP: " + oSrv:GetErrorString(nRet) + CRLF
                lRet := .F.
            EndIf

            If lRet
                //Envia a mensagem
                nRet := oMsg:Send(oSrv)
                If nRet <> 0
                    cLog += "008 - Nao foi possivel enviar a mensagem: " + oSrv:GetErrorString(nRet) + CRLF
                    lRet := .F.
                EndIf
            EndIf

            //Disconecta do servidor
            nRet := oSrv:SMTPDisconnect()
            If nRet <> 0
                cLog += "009 - Nao foi possivel desconectar do servidor SMTP: " + oSrv:GetErrorString(nRet) + CRLF
            EndIf
        EndIf
    EndIf
EndIf

//Se tiver log de avisos/erros
If !Empty(cLog)
	u_MsgLog(cPrw,"ERROR: "+ALLTRIM(cLog),"E")
EndIf

RestArea(aArea)

Return lRet

Bloco de Citação

Está função CpyT2S pra mim tbm não funciona, a sua função funciona na versão nova do protheus WebAgent (Onça Preta - Release 12.1.2410)?

Se o seu arquivo estiver no cliente, você vai precisar ter o webagent instalado no cliente para reconhecer corretamente os arquivos locais dele.

sim, estou com webagent instalado e rodando no cliente.

Testei um relatório de cadastro nativo do protheus, ocorreu o mesmo erro, logo estou abrindo um chamado:

THREAD ERROR ([379584], GiliardL, INFO11) 01/04/2025 15:31:55
invalid handle used in file E:\build-dir\TP11-OF2430X-W6\lib_base\diskman.cpp at line 321
on MAILSEND(AP5MAIL.PRW) 20/02/2025 09:42:49 line : 231

[TOTVS build: 7.00.240223P-20250220]
Called from SETMAIL(MSSPOOL.PRW) 20/02/2025 09:42:49 line : 1535
Called from MSSPOOL:PREPAREEMAIL(FWMSSPOOL.PRW) 20/02/2025 09:42:44 line : 1948
Called from TREPORT:SENDMAIL(REPORT01.PRW) 20/02/2025 09:42:44 line : 1519
Called from TREPORT:SENDTOPRINTER(REPORT01.PRW) 20/02/2025 09:42:44 line : 1278
Called from TREPORT:PRINT(REPORT01.PRW) 20/02/2025 09:42:44 line : 2325
Called from TREPORT:PRINTDIALOG(REPORT01.PRW) 20/02/2025 09:42:44 line : 3562
Called from MPREPORT(REPORT04.PRW) 20/02/2025 09:42:44 line : 62
Called from MATR050(MATR050.PRX) 12/09/2019 14:46:45 line : 33
Called from __EXECUTE(APLIB090.PRW) 20/02/2025 09:42:44 line : 735
Called from MDIEXECUTE(APLIB260.PRW) 20/02/2025 09:42:44 line : 931

Não tive problemas com CpyT2S na 2410

Só para registro, sim a função CpyT2S continua funcionando normalmente, exceto via job.
obrigado

@giliardl mas a função cpyT2S não vai funcionar via Job, porque não tem o client para processar é o comportamento esperado mesmo. Como vai copiar um arquivo pro cliente se não existe cliente ?