Email Automation from Access Problem

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • tdw
    New Member
    • Mar 2007
    • 206

    Email Automation from Access Problem

    Hi all,

    I am trying to add a feature to our database that automates sending emails.
    When entering a new order, I want the option to send an email to the company the order came from, attaching a copy of our work order.

    The file that I want to attach is a rich text document created by Access and stored on our server. The creation of this document is not the problem.

    The problem is getting the email option to work. It does not seem to work. In fact, it just does nothing at all, not even an error message.

    The following code is just part of the VBA for an On Click event for a command button on my Add New Orders form. The button click does several things, all of which work fine. I tried to add the email option to the list of events that occur on that button click.

    Code:
    '   Email New Order to Recipient
    
    '   Yes No Box
        Msg = "Do you want to EMAIL a confirmation of this order?"    ' Define message.
        Style = vbYesNo   ' Define buttons.
        Title = "Email Confirmation"    ' Define title.
        Response = MsgBox(Msg, Style, Title)
    If Response = vbYes Then    ' User chose Yes
        
        Dim objOutlook As Outlook.Application
        Dim objOutlookMsg As Outlook.MailItem
        Dim objOutlookRecip As Outlook.Recipient
        Dim objOutlookAttach As Outlook.Attachment
        Dim stRecip As String
        
        If DCount("*", "cust", "[cusname]='" & Me!ORDER & "'") = 0 Then
        stRecip = ""
        Else
        stRecip = DLookup("email", "cust", "[cusname]='" & Me!ORDER & "'")
        End If
    
       ' Create the Outlook session.
       Set objOutlook = CreateObject("Outlook.Application")
       ' Create the message.
       Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
       With objOutlookMsg
          ' Add the To recipient(s) to the message.
         Set objOutlookRecip = .Recipients.Add(stRecip)
          objOutlookRecip.Type = olTo
          ' Set the Subject and Body of the message.
          .Subject = "Survey Order Receipt Confirmation (" & Me.CASE_N & ")"
          .Body = "This email is to confirm that we have entered your recent survey request into our system. Please review the attached work order, and let us know if you find any errors. Thank you!" & vbCrLf & vbCrLf
          ' Add attachments to the message.
          If Not IsMissing("O:\Orders_" & yr & "\" & [FILE_NO] & "\" & [FILE_NO] & ".rtf") Then
             Set objOutlookAttach = .Attachments.Add("O:\Orders_" & yr & "\" & [FILE_NO] & "\" & [FILE_NO] & ".rtf")
          End If
          ' Display email
          objOutlookMsg.Display
    
       End With
       Set objOutlookMsg = Nothing
       Set objOutlook = Nothing
       Set objOutlookRecip = Nothing
       Set objOutlookAttach = Nothing
    
    End If
    Let me know if you will need to see the entire code for that button click.

    "SC_NEW" is control source table for the "Add New Orders" form
    "ORDER" is the field on that table where we enter the company that sent us an order
    "CASE_N" is the field on that table where we enter the ordering company's case number.
    "FILE_NO" is a field for an automatically generated File Number (not the same as the case number)

    "cust" is a table where we store contact information for regular customers
    "cusname" is the field that stores the company's name
    "email" is the field (hyperlink field) that stores an email address for that company (is the fact that it's a hyperlink field the problem, maybe?)

    The File Number has already been generated, and the files on the server have already been created as a part of the On Click event, prior to reaching this part of the code.

    I think I have covered everything. Let me know if I forgot to define anything.

    Note: I want the email to open up for editing before sending.

    Thanks!
  • emsik1001
    New Member
    • Dec 2007
    • 93

    #2
    Hi

    I normally put STOP before the code I want to check then run it and use F8 to check the code step by step in majority of cases it resolves my issues straight away.

    Hope it helps
    Emil

    Comment

    • NeoPa
      Recognized Expert Moderator MVP
      • Oct 2006
      • 32633

      #3
      I don't have much experience with Outlook automation, but I can give links to some concepts. Debugging through the code to enable you to tell us what is not working does sound like a good idea. This level of code is not so easy to look through and spot problems, especially without specific experience in the relevant area.

      When debugging Application Automation it helps to set the Application object to visible first. It starts off invisible but adding this code after line #24 should help :
      Code:
      objOutlook.Visible = True
      Helpful resources :
      (Debugging in VBA).
      (Application Automation).

      Comment

      • Bugran
        New Member
        • Oct 2008
        • 6

        #4
        Hi there,

        I believe - at least part of your problem - may reside in the DLOOKUP ...

        stRecip = DLookup("email" , "cust", "[cusname]='" & Me!ORDER & "'")

        Where "email" should be in brackets "[email]" ...

        You may also want to be very careful in name comparisons and use the Trim$ to be certain niether the server name or form name contains any extra spaces.

        (The rest looks good to me ... )

        Hope that helps a bit.

        Bugran

        Comment

        • tdw
          New Member
          • Mar 2007
          • 206

          #5
          Thanks for the help. I changed the "email" to "[email]". I now have it working, but only when an email address is in the "email" field.

          I tried to write the code to also pop up an outgoing email, but leave the To: field blank, when there is nothing in the "email" field. That still isn't working.

          The way I tried to do that can be seen in the code I posted (lines 16 & 17). I tried to make the string value be "" when the "email" field is blank. That is apparently not the trick. When the "email" field is blank, all it does is... nothing at all. In fact it interrupts and ends all the code running from the OnClick event.

          Do you have a suggestion as to how I might accomplish this? Maybe some kind of Nz or IsNull? Again I do want it to open up an outgoing message, and just leave the To: blank if the "email" field is blank.

          Thanks

          Comment

          • tdw
            New Member
            • Mar 2007
            • 206

            #6
            Hi again,

            I have one remaining issue with the email automation thing.
            When Access tries to send an email through outlook, the Outlook warning appears saying "another program is trying to send an email, do you want to allow it?" or something to that effect. Everything I've read says that there is no way to eliminate that message.

            The problem is that if I click on "no" (don't allow), the remaining code that is supposed to run in my form after the email automation just stops. It does not complete the rest of the code. Apparently clicking "no" tricks Access into thinking an error occurred.

            I need for it to continue running the code, regardless of if the Send Email portion of it is successful or not. Is there a way to do this?

            Comment

            • NeoPa
              Recognized Expert Moderator MVP
              • Oct 2006
              • 32633

              #7
              Have you tried any error handling commands like :
              Code:
              On Error Resume Next

              Comment

              • tdw
                New Member
                • Mar 2007
                • 206

                #8
                Originally posted by NeoPa
                Have you tried any error handling commands like :
                Code:
                On Error Resume Next
                No, I hadn't done that. Shows how much I know!

                I had tried something similar, but in the form of On Error Goto.....
                with the the Goto referencing to the next step.

                One question: If the beginning of the code that runs (it does several things back to back) has an On Error Goto command that sends it to the end of the code, will putting On Error Resume Next in the email portion of the code supercede the original On Error command (assuming that no errors occured prior)?

                This is the code from the email portion on to the end.
                Is my placement correct?
                Code:
                '   Email New Order to Recipient
                
                On Error Resume Next
                
                '   Yes No Box
                    Msg = "Do you want to EMAIL a confirmation of this order?"    ' Define message.
                    Style = vbYesNo   ' Define buttons.
                    Title = "Email Confirmation"    ' Define title.
                    Response = MsgBox(Msg, Style, Title)
                If Response = vbYes Then    ' User chose Yes
                    
                    Dim objOutlook As Outlook.Application
                    Dim objOutlookMsg As Outlook.MailItem
                    Dim objOutlookRecip As Outlook.Recipient
                    Dim objOutlookAttach As Outlook.Attachment
                    Dim stRecip As String
                    
                    If DCount("*", "cust", "[cusname]='" & Me!ORDER & "'") = 0 Then
                    stRecip = "email_address_unknown"
                    Else
                    stRecip = DLookup("[email]", "cust", "[cusname]='" & Me!ORDER & "'")
                    End If
                
                   ' Create the Outlook session.
                   Set objOutlook = CreateObject("Outlook.Application")
                   ' Create the message.
                   Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
                   With objOutlookMsg
                      ' Add the To recipient(s) to the message.
                     Set objOutlookRecip = .Recipients.Add(stRecip)
                      objOutlookRecip.Type = olTo
                      ' Set the Subject and Body of the message.
                      .Subject = "Survey Order Receipt Confirmation (" & Me.CASENO & ")"
                      .Body = "***Confirmation of Receipt of New Survey Request***" & Chr(13) & Chr(13) & "This email is to notify you that we have created a work order for your recent survey request for " & Me.ADDRESS & "." & Chr(13) & "Our Job Number for this survey is " & Me.FILE_NO & "." & Chr(13) & "Please review the attached copy of our work order and let us know if you find any errors or have any questions." & Chr(13) & "Thank you!" & Chr(13) & Chr(13) & "Larry N. Scartz, LTD." & Chr(13) & "703-494-4181" & vbCrLf & vbCrLf
                      ' Add attachments to the message.
                      If Not IsMissing("O:\Orders_" & yr & "\" & [FILE_NO] & "\" & [FILE_NO] & ".rtf") Then
                         Set objOutlookAttach = .Attachments.Add("O:\Orders_" & yr & "\" & [FILE_NO] & "\" & [FILE_NO] & ".rtf")
                      End If
                      ' Display email
                      objOutlookMsg.Display
                
                   End With
                   Set objOutlookMsg = Nothing
                   Set objOutlook = Nothing
                   Set objOutlookRecip = Nothing
                   Set objOutlookAttach = Nothing
                
                End If
                
                '   Delete New Order from Add New Orders
                
                    DoCmd.SetWarnings False
                    DoCmd.DoMenuItem acFormBar, acEditMenu, 8, , acMenuVer70
                    DoCmd.DoMenuItem acFormBar, acEditMenu, 6, , acMenuVer70
                    DoCmd.SetWarnings True
                   
                    Me.lblPrintOrder.Visible = False
                    Me.ProgressBar.Visible = False
                    Me.Form.Repaint
                    
                    DoCmd.RunMacro "Goto New Record"
                
                Exit_Create_Order_File_Structure_Click:
                    Exit Sub
                
                Err_Create_Order_File_Structure_Click:
                    DoCmd.SetWarnings True
                    MsgBox Err.Description
                    Resume Exit_Create_Order_File_Structure_Click
                End Sub

                Comment

                • NeoPa
                  Recognized Expert Moderator MVP
                  • Oct 2006
                  • 32633

                  #9
                  Here's a related post I made earlier in a completely separate thread.
                  Originally posted by NeoPa
                  I always feel the On Error ... commands in VBA are a bit of a bodge. They don't nest properly and are procedure relative.

                  When using such code it is often necessary to separate out functionality into logical procedures as you have done. It's nearly always the better design anyway mind you, having separate concepts in their own procedures, so it may be a bonus in disguise.
                  It is complicated handling this in one long procedure. I strongly recommend you look at splittting your code up into logical procedures.

                  Comment

                  • FishVal
                    Recognized Expert Specialist
                    • Jun 2007
                    • 2656

                    #10
                    Hello, tdw.

                    Outlook security is a well known and annoying issue.
                    Would you like to use CDO instead of Outlook automation?

                    Regards,
                    Fish.

                    Comment

                    • tdw
                      New Member
                      • Mar 2007
                      • 206

                      #11
                      Originally posted by FishVal
                      Hello, tdw.

                      Outlook security is a well known and annoying issue.
                      Would you like to use CDO instead of Outlook automation?

                      Regards,
                      Fish.
                      The Outlook security doesn't cause me a problem, other than when it interrupts my code if the user clicks "no" when Outlook asks if they want to "allow" Access to send the email.

                      I really don't know anything about CDO, but I like for the email to show up in the "Sent Mail" folder in Outlook, and if CDO wouldn't do that then I would prefer to stick with Outlook.

                      NeoPa, thanks for the advice, I will study up on separating my code into logical procedures (which right now I know nothing about). I'll post a new question if I run into problems with that.

                      As always, I really appreciate your kind help.

                      Comment

                      • NeoPa
                        Recognized Expert Moderator MVP
                        • Oct 2006
                        • 32633

                        #12
                        CDO (or CDONTS) won't integrate with Outlook that way I'm afraid. It's becoming more common to use though nowadays due to the restrictions of coding with Outlook.
                        Originally posted by tdw
                        As always, I really appreciate your kind help.
                        Not a problem. We like to help if we can :)

                        Comment

                        • mshmyob
                          Recognized Expert Contributor
                          • Jan 2008
                          • 903

                          #13
                          You could use an addon DLL called Redemption. The Redemption DLL uses Extended MAPI instead of Simple MAPI and bypasses the Outlook error messages. You can download it for free and try it. If you decide to use it I believe it is a one time $199 fee with unlimited royalty rights.

                          I have used it and it works great. I am still debating if I will incorporate it in my final app since I am working on another extended MAPI solution for free. Anyways good luck.

                          Link to redemption

                          cheers,

                          Comment

                          • topher23
                            Recognized Expert New Member
                            • Oct 2008
                            • 234

                            #14
                            I was checking out the Express ClickYes program (as it is free), which led me to the original paper from a couple of professors at the Air Force Academy about using a vb script to bypass the dialog by using sendkeys, which is what the ClickYes program does. Working from their paper, I developed this code in VBA. Put it in a module and call it from your automated email routine - it will click the "Yes" button for your users.
                            Code:
                            Public Sub BypassOutlookSecurity()
                            Dim fName As String, fs As Object, f As Object
                                Set fs = CreateObject("Scripting.FileSystemObject")
                                fName = "c:\DATABASES\Bypass.vbs"
                                Set f = fs.CreateTextFile(fName, True)
                                f.writeline "Set fso = CreateObject(""WScript.Shell"")"
                                f.writeline "While fso.AppActivate(""Microsoft Office Outlook"") = FALSE"
                                f.writeline "wscript.sleep 1000"
                                f.writeline "Wend"
                                f.writeline "wscript.sleep 7000"
                                f.writeline "fso.SendKeys ""{LEFT}"", True"
                                f.writeline "fso.SendKeys ""{ENTER}"", True"
                                f.Close
                                Shell ("WScript.exe " & fName)
                            End Sub
                            You have to have the ability to run scripts on your machine, but most administrators don't have that option disabled.

                            I've also made a custom form that displays while my email automation code is running that says "Sending automated email - DO NOT click 'No' on the dialog pop-up." This is a just-in-case, as my automation runs overnight in most cases.

                            Comment

                            • GazMathias
                              Recognized Expert New Member
                              • Oct 2008
                              • 228

                              #15
                              Hi,

                              This automation issue has annoyed me in the past, too. I now don't even bother trying to do the work in Access, but instead have Access call an ASP page using InternetExplore r.Application, which loads the info into itself from the database and emails it using CDONTS.

                              One major benefit of this approach is the ability to easily send HTML email (Your Company branding, tabular CSS styled order data, etc) using .HTMLBody and the Microsoft.XMLHT TP object.

                              Let me know if this appeals to you and I'll post more.

                              Gaz

                              Comment

                              Working...