Jump to content
Fivewin Brasil

Envio de eMail com TSMTP


oribeiro

Recommended Posts

Pessoal,

Como alternativa para envio de email quando o usuário não informava a senha, eu usava essa classe TSMTP, mas depois que eu atualizei o FWH ela parou de funcionar.

Alguém tem essa classe atualizada?

USO:

      //////
      // ENVIO ATRAVES DO: TSMTP.PRG (NÃO PRECISA DE SENHA)
      //
      TRY
         CursorWait()
         WSAStartup()
         oMail:=TSmtp():New( cIP:=GetHostByName( cSMTP, nPorta ) )
         oMail:bConnecting = { || MsgRun("Conectando no SMTP = "+cSMTP)          }
         oMail:bConnected  = { || MsgRun("Conectado no IP = "+cIP     )          }
         oMail:bDone       = { || (oMail:End(),oMail:=TSmtp():New(),oMail:End()) }
         oMail:SendMail(cDe,{cPara},cMensagem,cAssunto,{cAnexo})
         WSaCleanUp()
         CursorArrow()
         SysRefresh()
         lRet := .T.
      CATCH oError
         lRet := .F.
      END

CLASSE:

// FiveWin Internet outgoing mail Class

#include "FiveWin.ch"

// different session status
#define ST_INIT       0
#define ST_CONNECTED  1
#define ST_RESET      2
#define ST_MAILFROM   3
#define ST_RCPTTO     4
#define ST_DATA       5
#define ST_SENT       6
#define ST_QUIT       7
#define ST_DONE       8

#ifdef __XPP__
   #define New _New
#endif

//----------------------------------------------------------------------------//

CLASS TSmtp

   DATA   oSocket     // socket used during the mail session
   DATA   cIPServer   // IP of the mail server

   DATA   cFrom       // Sender email address
   DATA   aTo         // Array of strings for each recipient email address

   DATA   nStatus     // Temporary session status
   DATA   nTo         // Temporary recipient index into aTo recipients array
   DATA   cMsg        // Msg Text to send
   DATA   cSubject    // msg subject
   DATA   dDate       // msg date
   DATA   cTime       // msg time
   DATA   nGmt        // GMT deviation
   DATA   cPriority   // msg priority: normal, high, low
   DATA   aFiles      // Attached files

   DATA   bConnecting // Action to perform while trying to connect
   DATA   bConnected  // Action to perform when already connected
   DATA   bDone       // Action to perform when Msg has been already sent

   METHOD New( cIPServer, nPort ) CONSTRUCTOR

   METHOD OnRead( oSocket )

   METHOD SendMail( cFrom, aTo, cMsg, cSubject, aFiles )

   METHOD Priority()

   METHOD End() INLINE ::oSocket:End()

ENDCLASS

//----------------------------------------------------------------------------//

METHOD New( cIPServer, nPort ) CLASS TSmtp

   #ifdef __XPP__
      #undef New
   #endif

   DEFAULT nPort := 25

   ::oSocket := TSocket():New( nPort )  // Leave := for Xbase++

   ::oSocket:bRead = { | o | ::OnRead( o ) }

   ::cIPServer = cIPServer
   ::nStatus   = ST_INIT

   // predefined events actions
   ::bDone = { || MsgInfo( "O email foi enviado com sucesso !!!", "Notificação" ) }

return Self

//----------------------------------------------------------------------------//

METHOD OnRead( oSocket ) CLASS TSmtp

   local cData := oSocket:GetData()
   local n

   do case
      case SubStr( cData, 1, 3 ) == "220"
           oSocket:SendData( "HELO " + ::cFrom + CRLF )
           ::nStatus = ST_CONNECTED
           if ::bConnected != nil
              Eval( ::bConnected )
           endif

//      case ::nStatus == ST_CONNECTED
//           oSocket:SendData( "RSET" + CRLF )
//           ::nStatus = ST_RESET

      case ::nStatus == ST_CONNECTED // ST_RESET
           oSocket:SendData( StrTran( "MAIL FROM:<%>", "%", ::cFrom ) + CRLF )
           ::nStatus = ST_MAILFROM
           ::nTo     = 1    // First recipient index to send mail to

      case ::nStatus == ST_MAILFROM .or. ::nStatus == ST_RCPTTO
           if ::nTo <= Len( ::aTo )
              oSocket:SendData( StrTran( "RCPT TO:<%>", "%", ::aTo[ ::nTo ] ) + ;
                                CRLF )
              ::nStatus = ST_RCPTTO
              ::nTo++
           else
              ::nStatus = ST_DATA
              oSocket:SendData( "DATA" + CRLF )
           endif

      case ::nStatus == ST_DATA
           DEFAULT ::cMsg := "", ::cSubject := "" ,;
                   ::dDate := Date(), ::cTime := Time(),;
                   ::nGmt := 0, ::cPriority := "Normal"

           oSocket:SendData( 'From: ' + ::cFrom + CRLF + ;
                             'To: ' + ::aTo[ 1 ] + CRLF + ;
                             'Cc: ' + CRLF + ;
                             'Subject: ' + ::cSubject + CRLF + ;
                             'Date: '+DTtoEDT(::dDate, ::cTime, ::nGmt) + CRLF + ;
                             'MIME-Version: 1.0' + CRLF + ;
                             'X-MSMail-Priority: ' + ::cPriority + CRLF + ;
                             'X-Priority: ' +lTrim(Str(::Priority())) + CRLF + ;
                             'X-Mailer: FiveWin Class TSmtp' + CRLF + ;
                             If( ! Empty( ::aFiles ),;
                             'Content-Type: multipart/mixed;' + CRLF + ;
                             Chr( 9 ) + 'boundary="NextPart"' + CRLF + CRLF + ;
                             "This is a multi-part message in MIME format." + CRLF + CRLF + ;
                             '--NextPart' + CRLF, "" ) + ;
                             'Content-Type: text/plain; ' + CRLF + ;
                             Chr( 9 ) + 'charset="iso-8859-1"' + CRLF + ;
                             'Content-Transfer-Encoding: 7bit' + CRLF + CRLF + ;
                             ::cMsg + CRLF )
           if ! Empty( ::aFiles )
              for n = 1 to Len( ::aFiles )
                 if File( ::aFiles[ n ] )
                    if Upper( cFileExt( ::aFiles[ n ] ) ) != "TXT" // OASyS 26/04/2007 = Alterei essa função para anexar qq. tipo de arquivo
                       oSocket:SendData( CRLF + "--NextPart" + CRLF + ;
                                         "Content-Type: " + DocType( Upper( cFileExt( ::aFiles[ n ] ) ) ) + ;
                                         'name="' + ::aFiles[ n ] + '"' + CRLF + ;
                                         "Content-Transfer-Encoding: base64" + CRLF + ;
                                         "Content-Disposition: attachment; " + ;
                                         'filename="' + cFileNoPath( ::aFiles[ n ] ) + '"' + CRLF + CRLF )
                       FMimeEnc( ::aFiles[ n ], "__temp" )
                       oSocket:SendFile( "__temp",, 0 )
                       FErase( "__temp" )
                    else
                       oSocket:SendData( CRLF + "--NextPart" + CRLF + ;
                                         "Content-Type: text/plain;" + CRLF + ;
                                         Chr( 9 ) + 'name="' + ::aFiles[ n ] + '"' + CRLF + ;
                                         "Content-Transfer-Encoding: quoted-printable" + CRLF + ;
                                         "Content-Disposition: attachment;" + CRLF + ;
                                         Chr( 9 ) + 'filename="' + cFileNoPath( ::aFiles[ n ] ) + '"' + CRLF + CRLF )
                       oSocket:SendFile( ::aFiles[ n ] )
                    endif
                 endif
              next
           endif
           oSocket:SendData( CRLF + ;
                             If( ! Empty( ::aFiles ), "--NextPart--" + CRLF + CRLF, "" ) + ;
                             "." + CRLF + Chr( 9 ) + CRLF )
           ::nStatus = ST_SENT

      case ::nStatus == ST_SENT
           oSocket:SendData( "QUIT" + CRLF )
           ::nStatus = ST_QUIT

      case ::nStatus == ST_QUIT
           ::nStatus = ST_DONE
           if ::bDone != nil
              Eval( ::bDone )
           endif
   endcase

return nil

//==============================//
Static Function DocType( cExt ) // OASyS = Indica o tipo do arquivo que esá anexo
//==============================//
   Local cType
   If cExt $ "EXE*COM*OBJ*LIB*DLL*VBX*OCX*HLP*CHM"
      cType := "application/octet-stream; "
   Elseif cExt $ "ZIP*ARC*ZOO*TAR"
      cType := "application/x-zip-compressed; "
   Elseif cExt $ "HTM*HTML*SHT*SHTML*MHT*MHTML"
      cType := "text/html; "
   Elseif cExt == "CSS"
      cType := "text/css; "
   Elseif cExt $ "XML*XSL"
      cType := "text/xml; "
   Elseif cExt $ "TXT*TEXT*LOG*BAT"
      cType := "text/plain; "
   Elseif cExt == "PDF"
      cType := "application/pdf; "
   Elseif cExt $ "BMP*DIB"
      cType := "application/bmp; "
   Elseif cExt == "GIF"
      cType := "image/gif; "
   Elseif cExt $ "JPG*JPE**JPEG*JFI*JFIF*PJP"
      cType := "image/jpeg; "
   Elseif cExt $ "XLS*XLT*XLA*XLB*XLC*XLL*XLM*XLW"
      cType := "application/x-msexcel; "
   Elseif cExt $ "PPT*PPS*POT*PWZ"
      cType := "application/x-mspowerpoint; "
   Elseif cExt $ "MPG*MPE*MPEG*M1S*M1A*MP2*MPM*MPA"
      cType := "video/mpeg; "
   Elseif cExt $ "PIC*PICT*PCT"
      cType := "image/pict; "
   Elseif cExt == "PNG"
      cType := "image/png; "
   Elseif cExt $ "MOV*QT*QTL*QTS*QTX*QTI*QTI*QTIF*QDA*QDAT*QPX*QTP"
      cType := "video/quicktime; "
   Elseif cExt $ "TIF*TIFF"
      cType := "image/tiff; "
   Elseif cExt $ "AVI*VFW"
      cType := "video/avi; "
   Elseif cExt $ "DOC*RTF*WBK*DOT*WIZ"
      cType := "application/msword; "
   Elseif cExt $ "RMI*MID*WAV*CDA*MIDI*MP2*MP3*WMA*MJF*MP1*VOC*IT*XM*S3M*STM*MOD*ULT*MTM*HMI*XMI*CMF*MUS*MIZ*HMZ*MSS*GMD*MIDS*HMP"
      cType := "audio/mid; "
   Else
      cType := "application/x-unknown-content-type; "
   Endif
Return cType


//----------------------------------------------------------------------------//

METHOD SendMail( cFrom, aTo, cMsg, cSubject, aFiles ) CLASS TSmtp

   ::cFrom    = cFrom
   ::aTo      = aTo
   ::cMsg     = cMsg
   ::cSubject = cSubject
   ::aFiles   = aFiles

   if ::bConnecting != nil
      Eval( ::bConnecting )
   endif

   ::oSocket:Connect( ::cIPServer )

return nil

//----------------------------------------------------------------------------//

METHOD Priority() CLASS TSmtp

   LOCAL nType

   DO CASE
   CASE  Upper(::cPriority) == "HIGH"
      nType := 1
   CASE  Upper(::cPriority) == "LOW"
      nType := 5
   OTHERWISE
      nType := 3
   END CASE

RETURN nType

//----------------------------------------------------------------------------//

STATIC FUNCTION DTtoEDT(dDate, cTime, nGmt)

   local aWeek  := {"Sun", "Mon", "Tue", "Wed", "Thu", "Fry", "Sat"}
   local aMonth := {"Jan", "Feb", "Mar", "Apr", "May", "Jun",;
                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }
   local cGmt

   if nGmt != 0
      cGmt := " "+iif( nGmt > 0,"+" ,"-" )+"0"+lTrim(Str(Abs(nGmt)))+"00"
   else
      cGmt := ""
   endif

return ( aWeek[Dow(dDate)]    + ", " + lTrim(str(Day(dDate)))  + " " + ;
         aMonth[Month(dDate)] + " "  + lTrim(Str(Year(dDate))) + " " + ;
         cTime + cGmt                                             )
Link to comment
Share on other sites

Eu uso assim, mas meu provedor pede senha de acesso.



#Include "FiveWin.ch"
#Include "Mail.ch"

FUNCTION Main()

LOCAL cErrorLog

cErrorLog := "C:\FWH1306\SAMPLES\ERROR.Log"

SendEmail( cErrorLog )

RETURN NIL

FUNCTION SendEmail( cErrorLog )

TRY
oCfg := CREATEOBJECT( "CDO.Configuration" )

WITH OBJECT oCfg:Fields

:Item( "http://schemas.microsoft.com/cdo/configuration/smtpserver" ):Value := "smtp.pleno.com.br"
:Item( "http://schemas.microsoft.com/cdo/configuration/smtpserverport" ):Value := 587 // Porta do Servidor
: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 := "joao@pleno.com.br" //<seu_email>
:Item( "http://schemas.microsoft.com/cdo/configuration/sendpassword" ):Value := "senhass" // <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()
aAttach := "C:\FWH1306\SAMPLES\ERROR.Log"

TRY
oMsg := CREATEOBJECT ( "CDO.Message" )

WITH OBJECT oMsg

:Configuration = oCfg

//:From = CHR(34) + "<nome_empresa_cliente>" + CHR(34)+ <email_seu_envio>
:From = CHR(34) + "TORBAL IND E COM DE ESCAPAMENTOS LTDA" + CHR(34)+ "joao@pleno.com.br"

//:To = <para_qual_email_enviar_o_LOG>
:To = "joao@pleno.com.br" //<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
Link to comment
Share on other sites

João,

Agradeço pelo seu interesse em ajudar.

Eu também uso dessa forma, o TSMTP é uma classe opcional que eu usava quando o Schema do Windows não funcionava. Normalmente quando o usuário informava senha errada ou nem informava a senha.

Se ninguém tiver ela atualizada para as versões mais recentes do FiveWin eu vou desativá-la. Apenas coloquei aqui para, quem sabe, encontrar alguém que também a utiliza.

Um abraço,

Link to comment
Share on other sites

  • 3 weeks later...

Exemplo retirado do site indicado pelo Gilmer

* Connect to SMTP server then send email

Function SendMail(ToList, Subject, Message)
Local Kode
Local SmtpHost
Local SmtpUser
Local SmtpPass
Local SmtpFrom
Local SmtpRepl
y Local ccList
Local bccList
Local Attachments
SmtpHost = "smtp.my-isp.com"
SmtpUser = "my-user-name"
SmtpPass = "my-password"
SmtpFrom = "<mike@my-isp.com>"
SmtpReply= "<mike@my-isp.com>"
ccList = Chr(0)
bccList = Chr(0)
Attachments = Chr(0)
* specify the port to connect on (default port is 25)
seeIntegerParam(0, SEE_SMTP_PORT, 587)
* enable "SMTP Authentication"
Kode = seeIntegerParam(0, SEE_ENABLE_ESMTP, 1)
* specify the user name and password for SMTP authentication
seeStringParam(0, SEE_SET_USER, SmtpUser)
seeStringParam(0, SEE_SET_SECRET, SmtpPass)
* connect to SMTP server
Kode = seeSmtpConnect(0, SmtpHost, SmtpFrom, SmtpReply)
* error ? (negative return Kodes are errors)
if Kode < 0
return Kode
endif
* send email to list of recipients (ToList)
Kode = seeSendEmail(0,ToList,ccList,bccList,Subject,Message,Attachments)
return Kode

Link to comment
Share on other sites

  • 6 months later...

Outra forma fácil de enviar email. Testado e aprovado em: FWH1306 e xHarbour última versão.

#Include "FiveWin.ch"
 
Function ENVIA_ERRO()
 
   LOCAL oSmtp, oEMail
   LOCAL cSmtpUrl
   LOCAL cSubject, cFrom, cTo, cBody, cFile
 
   /*
   cSmtpUrl := "smtp://meuemail:senha@smtp.mail.yahoo.com.br"
   cFrom  := "meuemail@yahoo.com.br"
   cTo   := "meuemail@ymail.com"
   */
 
   cSmtpUrl := "smtp://meuemail@dominio.com.br:senha@smtp.dominio.com.br"
   cFrom  := "joao@pleno.com.br"
   cTo   := "joao@pleno.com.br"
 
   cSubject := [Envio de erro do programa]
 
   cFile  := "COMP.LOG" //cNOME
 
   cBody  := [Envio de erro do programa]
 
   oEMail := TIpMail():new()
   oEMail:setHeader( cSubject, cFrom, cTo )
   oEMail:setBody( cBody )
   oEMail:attachFile( cFile )
 
   //oEMail:hHeaders[ "Disposition-Notification-To" ] := cFrom // solicita confirmacao
 
   oSmtp := TIpClientSmtp():new( cSmtpUrl )
 
   IF oSmtp:open()
 
      oSmtp:sendMail( oEMail )
 
      oSmtp:close()
 
      MSGINFO( [Email enviado com sucesso], [Aviso-Uhuuuu abestado!] )
 
   ELSE
 
      MSGINFO( "Erro:", oSmtp:lastErrorMessage() )
 
   ENDIF
 
RETURN Nil
 
// FIM DO PROGRAMA
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...