• Code to change default email account (Word 2000 / VBA)

    Home » Forums » AskWoody support » Productivity software by function » Visual Basic for Applications » Code to change default email account (Word 2000 / VBA)

    Author
    Topic
    #435890

    I am creating a Word MailMerge to Email program using VBA controls. I have the main core set up (With ActiveDocument.Mailmerge….) but before the merge is initiated I want to change the email account to be used when the merge creates the outgoing messages, and then restore the default account once finished. Is there a VB/VBA command or similar that can read the computer’s default email account name, change the account, and then restore the original? Or is there a registry key that can be changed using the Windows Script ‘RegWrite’ method to accomplish this?

    Viewing 0 reply threads
    Author
    Replies
    • #1031668

      The default profile name is stored in HKEY_CURRENT_USERSoftwareMicrosoftWindowsNTCurrentVersionWindows Messaging SubsystemProfilesDefaultProfile.

      In Outlook, you can use the Logon method of the NameSpace object to log on under a specific profile. The following is the example in the Outlook VBA help:

      Set myOlApp = CreateObject(“Outlook.Application”)
      Set myNameSpace = myOlApp.GetNameSpace(“MAPI”)
      myNameSpace.Logon “myProfile”, “myPassword”, True, True

      • #1031710

        Thanks. Found a workable solution myself though, using WshShell.RegWrite. I had tried using this previously without success – I could manipulate a registry key but Outlook wouldn’t recognize the change. Today I found the key to the puzzle: close Outlook before changing the registry keys, and when Outlook is re-opened the changed values are recognized.

        The mostly-finished code (I’d love a variable subject line, using data pulled from the mailmerge source file):

        Code:
        Dim WshShell
        
        Sub macStartMerge()
            
        On Error GoTo Errors
        
        
        'Create the Shell object
            Set WshShell = CreateObject("WScript.Shell")
        
        
        'Close Outlook before manipulating the system default email account
                Shell "C:Program FilesAccessoriesTaskill.exe outlook.exe"
        
        
        'Change the default email account to the desired sending account
            WshShell.RegWrite "HKCUSoftwareMicrosoftOfficeOutlookOMI Account Manager" _
                & "Default Mail Account", "00000002", "REG_SZ"
        
        
        'Run the mail merge
            With ActiveDocument.MailMerge
                .Destination = wdSendToEmail
                .MailAsAttachment = False
                .MailAddressFieldName = "EMAIL"
                .MailSubject = "Subject"
                .SuppressBlankLines = False
                With .DataSource
                    .FirstRecord = wdDefaultFirstRecord
                    .LastRecord = wdDefaultLastRecord
                End With
                .Execute Pause:=True
            End With
        
        
        'Restore the default email account
            WshShell.RegWrite "HKCUSoftwareMicrosoftOfficeOutlookOMI Account Manager" _
                & "Default Mail Account", "00000001", "REG_SZ"
        
        
        'Open Outlook to send the messages
            Shell "C:Program FilesMicrosoft OfficeOfficeoutlook.exe"
        
        
        'Everything complete, finish program
            GoTo Done
        
        
        Errors:
        
        'Display a message box with the error encountered
            MsgBox ("The program encountered the following error:" & Chr(13) & Chr(10) & _
                Chr(10) & Err.Description)
            Exit Sub
        
        
        Done:
        
        End Sub

        Taskill is a stand-alone program that can end a running process. http://www.ozemail.com.au/~nulifetv/freezip/freeware%5B/url%5D

        • #1031788

          Is this running in Word? If so, you might be able to change the registry key using the System.PrivateProfileString property. Cribbing from the help file a bit:

          Code:
          varOldValue = System.PrivateProfileString("", _
          	"HKEY_CURRENT_USERSoftwareMicrosoft" _
          	& "WindowsCurrentVersionInternet Settings", "EmailName")
          System.PrivateProfileString("", _
          	"HKEY_CURRENT_USERSoftwareMicrosoft" _
          	& "WindowsCurrentVersionInternet Settings", "EmailName") = varNewValue

          One less external library to invoke.

          • #1031793

            Unfortunately, I have to admit that the code is not working as intended. I was hoping that the MailMerge-generated messages would use the changed default email account as the sending account, but they actually used the default account at time they were being sent. The default account was being changed to the alternate account as intended and the messages generated, but by the time they were being sent the default had been changed back — and that was the account being used when Outlook’s ‘send’ took effect. One, maybe two, messages went out using the changed account, but the rest go out with the ‘restored’ default account.

            Word doesn’t support a ‘Wait’ command, but Excel’s VBA library does (and the ‘Help’ file gives an excellent example of how to use this code) so I added Excel’s library to the standard ‘Word’ library list and was able to use it to build in a delay before executing the code to restore the original default account. What would have been a 10-second ‘Wait’ delay in Excel ran much longer in Word and still left open the possibility for Outlook to begin sending with the wrong account.

            It looks like I may have to use MailMerge to generate the messages and then find a way to determine when Outlook’s ‘Outbox’ folder empties before restoring the default account back to the original value (ie, If count of outgoing messages = 0 then continue with change to default email account).

            UNLESS — Would your code example allow the created outgoing messages to use the changed email account as the outgoing account regardless of the default account set at the time the messages are actually sent?

            It might help to clarify why these changes are necessary. The MailMerge will be processed and sent out from our IT department but the replies need to be received through a different account. The recipients of the outgoing messages need to be able to ‘Reply’ and have their message go to the desired email account (100% chance the reply would be sent to the correct receiving account, no margin for error allowable). This could easily be accomplished by using a separate PC to create the outgoing messages but there’s no way to reasonably justify the cost of setting up a single-purpose PC just for what is expected to be a temporary (weeks/months vs years) situation.

            • #1031794

              The properties I listed do not change your overall process at all.

              Is this a frequent task? Would it be too much to ask the user to manually change the default back after completing the merge/send process?

              How about setting a Reply To address? Actually, it doesn’t appear that the MailMerge object provides access to this option. Because it’s a property of the default “form” for email messages, I don’t suggest making a global change.

              Does the Application_ItemSend event fire when you send messages using mail merge? If so, you could rig a procedure to recognize your merged messages (perhaps by a repetitive subject line?), and switch the account on the fly at the time of sending. Perhaps similar to the thread Prompt for Account (2003), although maybe that won’t work because there is no visible message compose window…

              Well, after all that, I endorse the “two profiles” method described above.

            • #1031836

              Is this a frequent task? Would it be too much to ask the user to manually change the default back after completing the merge/send process?

              This program would be run every couple of days, in a busy computer room with a history of not following procedures explicitly — past experience tells me that anything more complicated than a button-click leaves the process open to too many human-induced errors.

              Perhaps an application-modal messagebox to halt the code’s execution immediately after completing the merge: “Merge complete. Now go to Outlook and make sure the messages get sent before you click this ‘OK’ button.” If they actually wait until the outbox is empty before switching back to Word and clicking the messagebox button, that might be good enough to do the trick. scratch

            • #1031911

              I’m not sure you need user intervention. Let’s say you close Outlook and either change the default account and restart without specifying a profile, or restart with an alternate profile locked to the “special” account. You run the merge and Outlook sends. Your procedure in Word watches for all of the messages in the Outbox to be gone. Then it close Outlook, switches the account back and restarts, or restarts with the default profile.

              The “trick,” such as it is, is to take control over the Outlook session you start. If you use the automation code in Hans’ post, then you have an application object reference you can use to examine the contents of the Outbox. Use the API function Sleep to space your Outbox checks to decent intervals (e.g., every 2000 milliseconds) and then close Outlook once sending is complete (e.g., using the .Quit method of your Outlook application object).

              It might be a good idea to display a non-modal userform that says “Please Wait, Generating Messages” so the user doesn’t try to slip around and play with Outlook while you are sending…

            • #1031918

              What, precisely, do you mean by loading a profile for Outlook? All of our installations are set up as Internet Mode Only, and I’ve never seen an option for selecting a profile to use.

              I would like to have a procedure in Word to watch Outlook’s Outbox and pause Word until the outgoing message count = 0 and thereby eliminate the need for an artificial pause, but for now I don’t know how to access the folder’s information.

            • #1031924

              Outlook Properties (or Control Panel > Mail) will take you to this dialog box.

              StuartR

            • #1031928

              What I get from Control Panel > Mail is the dialog box for Internet Accounts.

            • #1031931

              I’m running Outllook 2003, I guess you must be running Outlook Express?

              StuartR

            • #1031932

              Sounds as though you will have to continue using the Registry key change option. Or upgrade to a version of Outlook that is less than 5 years old. grin

            • #1031938

              Hmmmm….. The 2cents 2cents 2cents solution of having an extra button-click in the program versus money money money to update a lot of computers and train-up? Which way would you go?

              Maybe when we upgrade the PC’s to Vista… cloud9 rofl

              Anyhow, I’m going to consider my initial questions solved. thankyou I’ve got code that works (maybe not the best but good enough nonetheless), and I’ve learned a good deal in the process.

            • #1032102

              Here’s an example that puts together the two ideas I described above: using Word’s System.PrivateProfileString method to change the registry, and automating the shut down and restart of Outlook and monitoring of the Outbox using VBA. I can’t test this very well on my system, as I don’t have the merge document and I don’t have a default account. Perhaps, though, it will help you somehow.

              The attached is an exported .BAS module, renamed to a .txt extension. To import it into your template or document, rename it to .BAS and use the VBE’s File>Import feature.

            • #1032116

              I tested your code and couldn’t get all of it to work. Beginning with your first group of code to change the account, strUsersAccount = … equated to “” and then errored on the System.PrivateProfileString command. Perhaps it still doesn’t like IMO-setups?

              The next oddity was Set olApp = CreateObject(“Outlook.Application”) – other than a pause nothing visible happened to indicate Outlook started; no splash screen, no taskbar button. I went to the Task Manager and there it was. Not a problem if Outlook is left closed at the end of the program.

              The code to check the outgoing item count worked perfectly joy and I’ll use that instead of my messagebox solution.

            • #1032143

              Hmmm, well, that’s what happens when it’s not possible to test that it works. It doesn’t. grin Reminds me of the professor who said there is no good writing, only good rewriting.

            • #1032300

              Have you investigated any other methods of attacking this problem? This post 590,463 shows a method for sending emails with attachments where you can set the return address as a string.

    Viewing 0 reply threads
    Reply To: Code to change default email account (Word 2000 / VBA)

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: