Propósito

✔ Programação GLOBAL® - Quaisquer soluções e/ou desenvolvimento de aplicações pessoais, ou da empresa, que não constem neste Blog devem ser tratados como consultoria freelance. Queiram contatar-nos: brazilsalesforceeffectiveness@gmail.com | ESTE BLOG NÃO SE RESPONSABILIZA POR QUAISQUER DANOS PROVENIENTES DO USO DOS CÓDIGOS AQUI POSTADOS EM APLICAÇÕES PESSOAIS OU DE TERCEIROS.

.: Vitrine

Carregando artigos...

Views

Mostrando postagens com marcador TLS. Mostrar todas as postagens
Mostrando postagens com marcador TLS. Mostrar todas as postagens

VBA Tips - Enviando e-mail com código VBA - Send From GMail





Baixe o Calendário Compacto para 2014 em Excel



O que é o fenômeno chamado BIG DATA?




O endereço do servidor de SMTP do GMail é "smtp.gmail.com". Este servidor requer conexões SSL ou TLS, e através destes poderemos enviar emails através da autenticação ESMTPPor exemplo, digamos que o seu email seja "bernardess@gmail.com", e o seu nome de usuário seja "bernardess@gmail.com".

Note que:


- O exemplo a seguir demonstra um código através do qual poderá enviar mensagens de email através do servidor de SMTP do GMail.


- Para implementar completamente este projeto, certifique-se de baixar e instalar o programa EASendMail na sua máquina.


- Para rodar o projeto corretamente, lembre-se de configurá-lo corretamente, mude o Servidor SMTP, o usuário, a senha, o destino, etc...


Divirta-se:

Private Sub btnSendMail_Click() 

    Dim oSmtp As New EASendMailObjLib.Mail 


    Let oSmtp.LicenseCode = "TryIt" 


    ' Set your Gmail email address

    Let oSmtp.FromAddr = "bernardess@gmail.com


    ' Add recipient email address

    oSmtp.AddRecipientEx "bernardess@gmail.com", 0 


    ' Set email subject

    Let oSmtp.Subject = "test email from gmail account" 


    ' Set email body

    Let oSmtp.BodyText = "this is a test email sent from VB 6.0 project with gmail" 


    ' Gmail SMTP server address

    Let oSmtp.ServerAddr = "smtp.gmail.com


    ' If you want to use direct SSL 465 port,

    ' Please add this line, otherwise TLS will be used.

    ' oSmtp.ServerPort = 465


    ' detect SSL/TLS automatically

    oSmtp.SSL_init 


    ' Gmail user authentication should use your

    ' Gmail email address as the user name.

    ' For example: your email is "bernardess@gmail.com", then the user should be "bernardess@gmail.com"


    Let oSmtp.UserName = "bernardess@gmail.com

    Let oSmtp.Password = "SUA SENHA" 


    MsgBox "start to send email ..." 


    If oSmtp.SendMail() = 0 Then 

        MsgBox "email was sent successfully!" 

    Else 

        MsgBox "failed to send email with the following error:" & oSmtp.GetLastErrDescription() 

    End If 


End Sub 


E sim, temos uma outra versão para você explorar:


'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

'>>> Database by Tony Hine, alias Uncle Gizmo                                 <<<
'>>> Created Mar, 2011                                                        <<<
'>>> Last up-dated Mar, 2011                                                  <<<
'>>> Telephone International: +44 1635 522233                                 <<<
'>>> Telephone UK: 01635 533322                                               <<<
'>>> e-mail: email@tonyhine.co.uk                                             <<<
'>>> Skype: unclegizmo                                                        <<<
'>>> I post at the following forum (mostly) :                                 <<<
'>>> http://www.access-programmers.co.uk/forums/  (alias Uncle Gizmo)         <<<
'>>> You can also find me on the Ecademy: http://www.ecademy.com/user/tonyhine<<<
'>>> try this website: http://www.tonyhine.co.uk/example_help.htm             <<<
'>>> I have now started a forum which contains video instructions here:       <<<
'>>> http://msAccessHintsAndTips.Ning.Com/                                    <<<
'>>> CODE SUPPLIED NOT CHECKED AND TESTED FOR ERRORS!!!! Be Warned            <<<
'>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
'<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

Public Function fSendGmail (ByVal sTo As String, ByVal sEmail As String, ByVal sPass As String, _
    ByVal strMsg As String, ByVal strSubject As String) As Boolean 'Returns True if No Errors

On Error GoTo Err_ErrorHandler
fSendGmail = True

'Extract
'This basic example sends a simple, no-frills text message every time the script is run:            '
'Example File script0603.vbs                                                                        '

'Extract
'The SendMail() Function
'While longer, SendMail( ) is itself a simpler function than GetData( ) . It simply creates three   '
'objects: CDO. Message, CDO. Configuration, and a subobject of CDO. Configuration called            '
'Fields . The Scripting library used in GetData() is a default part of the ASP namespace, and       '
'therefore any new object created in the Scripting library is known. To use objects in the CDO      '
'library, the METADATA statements at the top of the ASP page are necessary.                         '

'Standard CDO Constants
'NOTE --- If you set conCdoSmtpUseSSL to True, you may need to set conCdoSendUsingPort to 465 or port number specified by your ISP.
Const conStrPrefix As String = "http://schemas.microsoft.com/cdo/configuration/"
Const conCdoSendUsingPort As Integer = 2    'If incorrect raises this Error: -2147220960
'Const conSendPassword As String = "YourGmailPasswordHere"
Const conCdoBasic As Integer = 1
'Const conSendUserName As String = "YourGmailAddrHere@gmail.com"
Const conStrSmtpServer As String = "smtp.gmail.com"     'If incorrect raises this Error: -2147220973
Const conCdoSmtpUseSSL As Boolean = True    'Use Secure Sockets Layer (SSL) when posting via SMTP.
Const conCdoSmtpServerPort As Integer = 465 'Can be 465 or 587 'If incorrect raises this Error: -2147220973

Dim oMsg As Object
Dim oConf As Object

Dim strEmailAddr As String
'CHANGE THIS!!
'strEmailAddr = sTo & ""

'Create Objects
Set oMsg = CreateObject("CDO.Message")
Set oConf = CreateObject("CDO.Configuration")
Set oMsg.Configuration = oConf

'Build the Message
With oMsg
    .To = "" & sTo       'If incorrect you will get an email From: Delivery Status Notification (Failure) Delivery to the following recipient failed permanently:
    .From = "Grievance Tracker <" & sEmail & ">"    'If incorrect raises this Error: -2147220973
    .Subject = strSubject
    .textBody = strMsg
    '.AddAttachment "H:\ATHDrive\ATH_Programming\ATH_Office\Access2007\My_MS_Access_Tools\GoogleEmail\TransscriptGmailFromVBA.txt"
End With
            
''Set Delivery Options
            With oConf.Fields
                .Item(conStrPrefix & "sendusing") = conCdoSendUsingPort
                .Item(conStrPrefix & "smtpserver") = conStrSmtpServer
                .Item(conStrPrefix & "smtpauthenticate") = conCdoBasic
                .Item(conStrPrefix & "sendusername") = sEmail
                .Item(conStrPrefix & "sendpassword") = sPass
                '.Item(conStrPrefix & "sendusername") = conSendUserName 'IF you want to hard code the username you can reactivate this line.
                '.Item(conStrPrefix & "sendpassword") = conSendPassword 'IF you want to hard code the password you can reactivate this line.
                .Item(conStrPrefix & "smtpusessl") = conCdoSmtpUseSSL
                .Item(conStrPrefix & "smtpserverport") = conCdoSmtpServerPort
                .Update 'Commit Changes
            End With

'Deliver the Message
oMsg.Send

Exit_ErrorHandler:
'Access 2007 Developer Reference > Microsoft Data Access Objects (DAO) Reference > DAO Reference > Recordset Object > Methods
'An alternative to the Close method is to set the value of an object variable to Nothing (Set dbsTemp = Nothing).
    Set oMsg.Configuration = Nothing
    Set oConf = Nothing
    Set oMsg = Nothing
    Exit Function

Err_ErrorHandler:
    If Err.Number <> 0 Then fSendGmail = False
        Select Case Err.Number

            Case -2147220977  'Likely cause, Incorrectly Formatted Email Address, server rejected the Email Format
                MsgBox "Error From --- fSendGmail --- Incorrectly Formatted Email ---  Error Number >>>  " _
                & Err.Number & "  Error Desc >>  " & Err.Description, , "Format the Email Address Correctly"

            Case -2147220980  'Likely cause, No Recipient Provided (No Email Address)
                MsgBox "Error From --- fSendGmail --- No Email Address ---  Error Number >>>  " _
                & Err.Number & "  Error Desc >>  " & Err.Description, , "You Need to Provide an Email Address"

            Case -2147220960 'Likely cause, SendUsing Configuration Error
                MsgBox "Error From --- fSendGmail --- The SendUsing configuration value is invalid --- LOOK HERE >>> sendusing) = conCdoSendUsingPort ---  Error Number >>>  " _
                & Err.Number & "  Error Desc >>  " & Err.Description, , "SendUsing Configuration Error"
            
            Case -2147220973  'Likely cause, No Internet Connection
                MsgBox "Error From --- fSendGmail --- No Internet Connection ---  Error Number >>>  " _
                & Err.Number & "  Error Desc >>  " & Err.Description, , "No Internet Connection"
            
            Case -2147220975  'Likely cause, Incorrect Password
                MsgBox "Error From --- fSendGmail --- Incorrect Password ---  Error Number >>>  " _
                & Err.Number & "  Error Desc >>  " & Err.Description, , "Incorrect Password"
            
            Case Else   'Report Other Errors
                MsgBox "Error From --- fSendGmail --- Error Number >>>  " & Err.Number _
                & "  <<< Error Description >>  " & Err.Description
        End Select
        
    Resume Exit_ErrorHandler
End Function      'fSendGmail


Tags: VBA. GMail, e-mail, mail, send, SMTP, SSL, TLS, ESMTP, CDO, 






VBA Tips - Envie emails diretamente através do BOL e UOL - Send Email using brazilian free Account - BOL

Pode ser que prefiramos enviar os nossos relatórios através de uma conta externa ao nosso email corporativo para não sobrecarregar o servidor e desse modo utilizemos uma conta externa para isso.


Neste exemplo utilizaremos o UOL ou BOL.


O endereço do servidor SMTP do BOL/UOL é "smtps.bol.com.br". Ele suporta conexão SSL para fazer a autenticação do usuário, e devemos usar o seu endereço de email do BOL/UOL, como o nome do usuário de autenticação SMTP. Por exemplo: seu e-mail é "bernardess@bol.com.br", e em seguida o nome do usuário deve ser "bernardess@bol.com.br".

Se quisermos fazer uso da conexão SSL do servidor SMTP no BOL/UOL, precisaremos definir a porta para 465 ou 587. 



Secure Socket Layer - SSL



É um padrão global em tecnologia de segurança desenvolvida pela Netscape em 1994. Ele cria um canal criptografado entre um servidor web e um navegador (browser) para garantir que todos os dados transmitidos sejam sigilosos e seguros. Milhões de consumidores reconhecem o "cadeado dourado" que aparece nos navegadores quando estão acessando um website seguro. 





Quando escolher ativar o SSL no seu servidor web você terá que responder algumas questões sobre a identidade do seu site (ex. a URL) e da sua empresa (ex. a Razão Social e o endereço). Seu servidor web então criará duas chaves criptográficas - a Chave Privada (Private Key) e a Chave Pública (Public Key). Sua Chave Privada não possui esse nome à toa - ela deve ser mantida privada e segura. Já a Chave Pública não necessita ser secreta e deve ser colocada na CSR (Certificate Signing Request) - um arquivo de dados contendo os detalhes do site e da empresa. Você deverá enviar esta CSR através do formulário de solicitação em nosso site, seus dados serão validados e se estiverem corretos seu certificado digital será emitido.





Seu servidor web irá associar o certificado emitido com a sua Chave Privada. Seu servidor irá estebelecer um link criptografado entre seu website e o navegador do seu consumidor.



Transport Layer Security - TLS



É um protocolo criptográfico cuja função é conferir segurança para a comunicação na Internet para serviços como email (SMTP), navegação por páginas (HTTP) e outros tipos de transferência de dados.




Simple Mail Transfer Protocol - SMTP  




É protocolo que transfere emails, é instalado como parte dos serviços de email junto o serviço POP3. O SMTP controla como o email é transportado e entregue através da Internet ao servidor de destino. O serviço SMTP envia e recebe emails entre os servidores, ao passo que o serviço POP3 recupera o email do servidor de email para o computador do usuário.


Extended Simple Mail Transfer Protocol - ESMTP  


ESMTP é uma definição de extensões de protocolo para o padrão Simple Mail Transfer Protocol. O formato da extensão foi definido na RFC 1869 em 1995. A RFC 1869 estabeleceu uma estrutura para as atuais e futuras extensões, para produzir um meio gerenciável e consistente pelo qual os clientes e servidores SMTP possam ser identificados e servidores SMTP possam indicar extensões suportadas para clientes conectados.




O código a seguir demonstrará como enviar e-mail usando o servidor SMTP do Hotmail / MSN Live.



Para tornar o seu projeto funcional faça o download e instale o
EASendMail em sua máquina.


Não deixe de adicionar a referência ao controle ActiveX de SMTP do objeto EASendMail no seu projeto. 



Inline image 1

Lembre-se, antes de executá-lo corretamente, por favor, mude o servidor SMTPusuáriosenharemetente, e destinatário conforme a conta a ser utilizada.






Private Sub btnSendMail_Click() 

    Dim oSmtp As New EASendMailObjLib.Mail 
    Let oSmtp.LicenseCode = "TryIt" 

    ' Set your Yahoo email address
    Let oSmtp.FromAddr = "bernardess@bol.com.br

    ' Add recipient email address
    oSmtp.AddRecipientEx "bernardess@gmail.com", 0 

    ' Set email subject
    Let oSmtp.Subject = "Teste de envio de email a partir da minha conta do UOL/BOL" 

    ' Set email body
    Let oSmtp.BodyText = "Teste de envio de email com VBA a partir da minha conta do UOL/BOL" 

    ' Yahoo SMTP server address
    Let oSmtp.ServerAddr = "smtps.bol.com.br

    ' For example: your email is "bernardess@bol.com.br", then the user should be "bernardess@bol.com.br"
    Let oSmtp.UserName = "bernardess@bol.com.br
    Let oSmtp.Password = "<Digite a sua senha aqui>" 

    ' Because Yahoo deploys SMTP server on 465 port with direct SSL connection.
    ' So we should change the port to 465 ou 587.
    Let oSmtp.ServerPort = 465 ' or 587

    ' Detect SSL/TLS automatically
    oSmtp.SSL_init 

    MsgBox "Iniciando o envio do email. . . " 

    If oSmtp.SendMail() = 0 Then 
        MsgBox "O email foi enviado com sucesso!" 
    Else 
        MsgBox "Falha no envio de email - Erro nº: " & oSmtp.GetLastErrDescription() 
    End If 

End Sub 



Tags: VBA, UOL, BOL, email, e-mail, SMTP, SSL, TLS, ESMTP, HTTP, CSR, RFC 1869, 
diHITT - Notícias