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 send. Mostrar todas as postagens
Mostrando postagens com marcador send. Mostrar todas as postagens

VBA Excel - Enviando emails via VBA - Send Email Using VBA


Um dos meios mais fáceis de automatizar o envio de e-mails através do MS Excel é invocar a função ObjectOutlook.Application.

Esta função devolve a referência ao objeto ActiveX, neste caso a aplicação Outlook, o qual é utilizado para a criação e o envio do  e-mail.

Copie e cole o código abaixo para que isso aconteça:

Sub EnvieMailVBA()
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String

Dim Mail_Object, Mail_Single As Variant

Let Email_Subject = "A&A: Enviando e-mail com VBA"
Let Email_Send_From = "<Digite o seu e-mail aqui>"
Let Email_Send_To = "<Digite o email para quem enviará>"
Let Email_Cc = "<Digite a pessoa para quem enviará a cópia deste email >"
Let Email_Bcc = "<Digite o email para quem enviará uma cópia oculta>"
Let Email_Body = "Parabéns!!!! O seu envio ocorreu com sucesso !!!!"

On Error GoTo debugs

Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)

With Mail_Single
Let .Subject = Email_Subject
Let .To = Email_Send_To
Let .cc = Email_Cc
Let .BCC = "bernardess@gmail.com" 'Email_Bcc
Let .Body = Email_Body

.send
End With

debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub


Como um lembrete: Quando enviar um e-mail usando este código VBA, uma janela pop-up alertando os usuários de que o "Um programa está tentando enviar automaticamente um email em seu nome. Você quer permitir isso? " aparece. 

Este é um aviso de segurança válido e não há nenhum trabalho direto ao redor dele. No entanto, existem outros dois meios pelos quais essa tarefa pode ser executada, uma através do uso de CDO e outro que simula a utilização do teclado.




Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...





Tags: VBA, Excel, e-mail, email, mail, send, objectoutlook.application, activeX


VBA Excel - Enviando emails via CDO - Send Email Using CDO

O que é CDO?

É uma biblioteca de objetos que expõe as interfaces do Messaging Application Programming Interface (MAPI). 

O CDO permite que manipulemos os dados do Exchange para enviar e receber mensagens.

O uso do CDO pode ser preferível em casos onde gostaríamos de evitar a segurança pop-up que aparecem, tais como: "um programa está tentando enviar automaticamente um e-mail em seu nome", atrasando o nosso envio de e-mail até que o usuário forneça um resposta.

Neste exemplo usaremos a função CreateObject ("CDO.Message").

Um ponto importante a observar aqui é definir a configuração SMTP corretamente, de modo a evitar o temido "Erro em tempo de execução -2147220973 (80040213) " ou o " valor de configuração SendUsing erros é inválido "de aparecer.

Sub EnvieMail_CDO()
Dim CDO_Mail_Object As Object
Dim CDO_Config As Object
Dim SMTP_Config As Variant
Dim Email_Subject, Email_Send_From, Email_Send_To, Email_Cc, Email_Bcc, Email_Body As String

Let Email_Subject = "Enviando email via CDO"
Let Email_Send_From = "< Seu endereço de email >"
Let Email_Send_To = "< Endereço de email para envio >"
Let Email_Cc = "< Endereço de email de cópia >"
Let Email_Bcc = "< Endereço de email de cópia oculta >"
Let Email_Body = "Parabéns!!!! Seu envio através de CDO funcionou !!!!"

Set CDO_Mail_Object = CreateObject("CDO.Message")
On Error GoTo debugs

Set CDO_Config = CreateObject("CDO.Configuration")
CDO_Config.Load -1

Set SMTP_Config = CDO_Config.Fields

With SMTP_Config
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2

' Coloque o nome do seu SERVIDOR abaixo:
Let .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "YOURSERVERNAME"

Let .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25

.Update
End With

With CDO_Mail_Object
Set .Configuration = CDO_Config
End With

Let CDO_Mail_Object.Subject = Email_Subject
Let CDO_Mail_Object.From = Email_Send_From
Let CDO_Mail_Object.To = Email_Send_To
Let CDO_Mail_Object.TextBody = Email_Body
Let CDO_Mail_Object.cc = Email_Cc 'Use se achar necessário
Let CDO_Mail_Object.BCC = "bernardess@gmail.com" 'Use se achar necessário
'CDO_Mail_Object.AddAttachment FileToAttach 'Use se achar necessário
CDO_Mail_Object.send

debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub



Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...




Tags: VBA, Excel, e-mail, email, mail, send, CDO, SMTP, CreateObject, MAPI, 



VBA Excel - Enviando emails usando Send Keys - Send Email Using Send Keys


Um outro modo de enviarmos um e-mail é por utilizarmos o comando ShellExecute para executar qualquer programa dentro do VBA. O comando ShellExecute pode ser usado para carregar um documento com um programa associado. Em essência, criamos um objeto string e o passamos como um parâmetro para a função ShellExecute. O resto do trabalho é feito pelo Windows. Ele decide automaticamente qual programa está associado a determinado tipo de documento.

Podemos usar a função ShellExecute para abrirmos o IExplorer, Word, Paintbrush e uma série de outras aplicações. 

A operação pode ser lenta e se não quiser executar o Send Keys antes mesmo do e-mail aparecer na tela e esperar alguns segundos, certifique-se que o envio do e-mail foi processos totalmente e, em seguida, ative o Send Keys. O envio precipitado impedirá que o email seja enviado.

Sub SendKeyMail()
Dim Mail_Object As String
Dim Email_Subject, Email_Send_To, Email_Cc, Email_Bcc, Email_Body As String

Email_Subject = "A&A: Enviando email via Keys"
Email_Send_To = " <Endereço de email para quem envia> "
Email_Cc = " <Endereço de email para quem deseja enviar cópia> "
Email_Bcc = " <Cópia oculta deste email> "
Email_Body = " Parabéns!!!! Seu email foi enviado !!!!"
Mail_Object = "mailto:" & Email_Send_To & "?subject=" & Email_Subject & "& body=" & Email_Body & "& cc=" & Email_Cc & "& bcc=" & Email_Bcc

On Error GoTo debugs

ShellExecute 0&, vbNullString, Mail_Object, vbNullString, vbNullString, vbNormalFocus

Application.Wait (Now + TimeValue("0:00:03"))

Application.SendKeys "%s"

debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub



Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...

Tags: VBA, Excel, e-mail, email, mail, send, send keys, ShellExecute, 




VBA Tips - SendLotusEmails - Envie e-mail com o Lotus Notes

Envie e-mails através do Lotus Notes. Requer as Classes de Automação do Lotus (Lotus Automation Classes - notes32.tlb).

  ' Attribute VB_Name = "modLotus"

' This public sub will send a mail and attachment if neccessary to the recipient including the body text.
' Requires that notes client is installed on the system.

Public Sub SendLotusEMail(Subject As String, Attachment As String, recipient As String, bodytext As String, saveit As Boolean)

    ' Set up the objects required for Automation into lotus notes
    
    Dim MailDB As Object ' The mail database
    
    Dim UserName As String ' The current users notes name
    
    Dim MailDBName As String ' THe current users notes mail database name
    
    Dim MailDoc As Object ' The mail document itself
    
    Dim AttachME As Object ' The attachment richtextfile object
    
    Dim LotusSession As Object ' The notes session
    
    Dim EmbedObj As Object ' The embedded object (Attachment)
    
    ' Start a session to notes
    
    Set LotusSession = CreateObject("Notes.NotesSession")
    
    ' Get the sessions username and then calculate the mail file name
    
    ' You may or may not need this as for MailDBname with some systems you
    
    ' can pass an empty string
    
    UserName = LotusSession.UserName
    
    MailDBName = Left$(UserName, 1) & Right$(UserName, (Len(UserName) - InStr(1, UserName, " "))) & ".nsf"
    
    ' Open the mail database in notes
    
    Set MailDB = LotusSession.GetDatabase("", MailDBName)
     
     If MailDB.isOpen = True Then
          
          ' Already open for mail
     
     Else
         
         MailDB.OPENMAIL
     
     End If
    
    ' Set up the new mail document
    
    Set MailDoc = MailDB.CreateDocument
    
    MailDoc.Form = "Memo"
    
    MailDoc.sendto = recipient
    
    MailDoc.Subject = Subject
    
    MailDoc.body = bodytext
    
    MailDoc.SaveMessageOnSend = saveit
    
    ' Set up the embedded object and attachment and attach it
    
    If Attachment <> "" Then
        
        Set AttachME = MailDoc.CreateRichTextItem("Attachment")
        
        Set EmbedObj = AttachME.EmbedObject(1454, "", Attachment, "Attachment")
        
        MailDoc.CreateRichTextItem ("Attachment")
    
    End If
    
    ' Send the document
    
    MailDoc.PostedDate = Now() 'Gets the mail to appear in the sent items folder
    
    MailDoc.Send 0, recipient
    
    
    ' Clean Up
    
    Set MailDB = Nothing
    
    Set MailDoc = Nothing
    
    Set AttachME = Nothing
    
    Set LotusSession = Nothing
    
    Set EmbedObj = Nothing

End Sub

Deixe os seus comentários! Envie este artigo, divulgue este link na sua rede social...


Tags: VBA, Lotus, Lotus Notes, e-mails, notes32.tlb, send,



Excel Tips - Enviando e-mails a partir do Excel


Estender certa praticidade aos nossos clientes, facilitando-lhes o dia-a-dia, é um prazer para nós desenvolvedores, certo?

Abaixo replico um post antigo, e agora ampliado, com uma funcionalidade que visa facilitar o compartilhamento dos nossos 

BIs (Business Information), 

BSCs

Dashboards

Scorecards 

Ou mesmo dos relatórios e gráficos que estão contidos em nossos MISs.

Como? 

Enviando-os por e-mail. Sugiro algumas aplicabilidades práticas para a utilização do envio automatizado e e-mails:

: : Sabe quando você está responsável por consolidar diversas planilhas em uma só e o pessoal que precisa enviar-lhe as planilhas (ou disponibilizá-las em algum lugar) não o fazem? então, automatize a cobrança por e-mail


: : Ao invés de gastar tempo reunindo todas as planilhas após o fechamento e enviá-las uma-a-uma a todos os gestores, reúna os dados em um só recipiente, crie uma lista de quem receberá as planilhas e pronto!

A primeira opção utiliza o método SEND, e serve como incentivo a sua pesquisa e estudo. 

Sub SendPlanNow()
    ActiveWorkbook.SendMail _

    Recipients:="bernardess@gmail.com", _

    Subject:="Enviando e-mail da aplicação Excel em: " & Format(Date, "dd/mm/yyyy")
End Sub
Outras necessidades vão se desenrolando com o passar do tempo, como por exemplo copiar a pasta ativa (ActiveSheet), envindo a planilha em seguida:

Sub Send1Sheet_ActiveWorkbook()
    ' Criando uma nova planilha (workbook) contendo um Sheet, e enviando-a 
      como um arquivo anexado.

    ThisWorkbook.Sheets(1).Copy   

    With ActiveWorkbook

         .SendMail Recipients:="bernardess@gmail.com", _

          Subject:="Tente contatar-me em: " & Format(Date, "dd/mmm/yy")

         .Close SaveChanges:=False

    End With

End Sub

Outro método que pode ser usado é o Método de Roteirização, este encaminha a pasta de trabalho (worksheet), a partir de uma lista seguindo o roteiro atual, isto nos permite especificar inúmeros destinatários.

Sub RoutingActwBook()
    With ActiveWorkbook

       Let .HasRoutingSlip = True

           With .RoutingSlip

                Let .Delivery = xlOneAfterAnother
                Let .Recipients = Array("bernardess@gmail.com", "inanyplace01@gmail.com", "inanyplace02@gmail.com")
                Let .Subject = "Por favor, dê atenção a este relatório"
                'Let.Message = ""

          End With

        .Route

    End With
End Sub

Um outro problema comum encontrado em diversos códigos onde se faz citação ao envio de e-mails de modo automatizado é a aparição de mensagens similares a:

"A program is trying to automatically send e-mail..."

"Um programa está tentando enviar..."

Como eliminar de vez esta constante mensagem de exibição? 

Bem, a solução não está no MS Excel, neste caso, pois esta solução pode ser implementada em qualquer um dos produtos do MS Office.

Crie um novo módulo no MS Outlook e cole o código abaixo (Agradecimentos antecipados ao Waine Phillips, dono da solução):

Public Function FnSendMailSafe(strTo As String, _

                                strCC As String, _

                                strBCC As String, _

                                strSubject As String, _

                                strMessageBody As String, _

                                Optional strAttachments) As Boolean

    On Error GoTo ErrorHandler:

    Dim MAPISession As Outlook.NameSpace
    Dim MAPIFolder As Outlook.MAPIFolder
    Dim MAPIMailItem As Outlook.MailItem
    Dim oRecipient As Outlook.Recipient
    Dim TempArray() As String
    Dim varArrayItem As Variant
    Dim strEmailAddress As String
    Dim strAttachmentPath As String
    Dim blnSuccessful As Boolean

    'Obtendo o MAPI do objeto NameSpace

    Set MAPISession = Application.Session

    If Not MAPISession Is Nothing Then

      'Logando-se na sessão MAPI

      MAPISession.Logon , , True, False

      'Criando um ponteiro na pasta Outbox

      Set MAPIFolder = MAPISession.GetDefaultFolder(olFolderOutbox)

      If Not MAPIFolder Is Nothing Then

        ' Criando um novo item de e-mail item na pasta "Outbox"

        Set MAPIMailItem = MAPIFolder.Items.Add(olMailItem)

        If Not MAPIMailItem Is Nothing Then
         
          With MAPIMailItem

            'Criando um novo recipiente para TO

                Let TempArray = Split(strTo, ";")

                For Each varArrayItem In TempArray

                    Let strEmailAddress = Trim(varArrayItem)

                    If Len(strEmailAddress) > 0 Then

                        Set oRecipient = .Recipients.Add(strEmailAddress)

                        Let oRecipient.Type = olTo

                        Set oRecipient = Nothing

                    End If
               
                Next varArrayItem
           

            'Criando um recipiente para CC

                Let TempArray = Split(strCC, ";")

                For Each varArrayItem In TempArray

                    Let strEmailAddress = Trim(varArrayItem)

                    If Len(strEmailAddress) > 0 Then

                        Set oRecipient = .Recipients.Add(strEmailAddress)

                        Let oRecipient.Type = olCC

                        Set oRecipient = Nothing

                    End If

                Next varArrayItem
           
            'Criando recipiente para BCC

                Let TempArray = Split(strBCC, ";")

                For Each varArrayItem In TempArray

                    Let strEmailAddress = Trim(varArrayItem)

                    If Len(strEmailAddress) > 0 Then

                        Set oRecipient = .Recipients.Add(strEmailAddress)

                        Let oRecipient.Type = olBCC

                        Set oRecipient = Nothing

                    End If
               

                Next varArrayItem
           

            'Configurado a mensagem do SUBJECT

                Let .Subject = strSubject
           

            'Configurando a mensagem do corpo od e-mail (em HTML ou texto)

                If StrComp(Left(strMessageBody, 6), "<HTML>", vbTextCompare) = 0 Then

                    Let .HTMLBody = strMessageBody

                Else

                    Let .Body = strMessageBody

                End If


            'Adicionando qualquer anexo especificado

                'Let TempArray = strAttachments

                For Each varArrayItem In strAttachments

                    Let strAttachmentPath = Trim(varArrayItem)

                    If Len(strAttachmentPath) > 0 Then
                        .Attachments.Add strAttachmentPath
                    End If
               

                Next varArrayItem

            .Send


            Set MAPIMailItem = Nothing

          End With

        End If

        Set MAPIFolder = Nothing

      End If

      MAPISession.Logoff

    End If


    Let blnSuccessful = True
   

ExitRoutine:

    Set MAPISession = Nothing
    Let FnSendMailSafe = blnSuccessful

    Exit Function


ErrorHandler:

    MsgBox "Occoreu um erro na função VBA FnSendMailSafe()" & vbCrLf & vbCrLf & _

            "Nº do erro: " & CStr(Err.Number) & vbCrLf & _

            "Descrição do erro: " & Err.Description, vbApplicationModal + vbCritical

    Resume ExitRoutine

End Function

Já no MS Excel (ou qualquer outro produto do MS Office), cole o código abaixo:Chame essa função com os parâmetros da mensagem.
No parâmetro TO (Para) e CC é só separar os e-mails com ;[ponto-e-vírgula], e os anexos precisarão estar numa matriz.

Function SendMail (para As String, cc As String, assunto As String, mensagem As String, Anexos) As Boolean
         'enviar e-mail via Outlook
         Dim objOutlook As Object ' Note: Must be late-binding.
         Dim objNameSpace As Object
         Dim objExplorer As Object
         Dim blnSuccessful As Boolean
         Dim blnNewInstance As Boolean 

         On Error Resume Next

         Set objOutlook = GetObject(, "Outlook.Application")

         On Error GoTo 0

         If objOutlook Is Nothing Then
             Set objOutlook = CreateObject("Outlook.Application")

             Let blnNewInstance = True

             Set objNameSpace = objOutlook.GetNamespace ("MAPI")
             Set objExplorer = objOutlook.Explorers.Add (objNameSpace.Folders(1), 0)

             objExplorer.CommandBars.FindControl(, 1695).Execute
                   
             objExplorer.Close
               
             Set objNameSpace = Nothing
             Set objExplorer = Nothing
         End If

         Let blnSuccessful = objOutlook.FnSendMailSafe (para, cc, "", assunto, mensagem, Anexos)

         If blnNewInstance = True Then objOutlook.Quit

         Set objOutlook = Nothing

         Let EnviarEmail = blnSuccessful
End Function


Tags: VBA, e-mail, send, Excel

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, 






diHITT - Notícias