Open Outlook & Send Email Using COM Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
PoorInRichfield
Posts: 5
Joined: 01 May 2018, 16:50

Open Outlook & Send Email Using COM

Post by PoorInRichfield » 01 May 2018, 16:57

AutoHotKey newbie here...

I'm creating a script that should run Outlook if the user doesn't already have it open, create an email, and send it... or just create the new email and send it if Outlook is already running. I'm stuck on the part of opening Outlook. The script below will open Outlook, but the call to ComObjActive fails as though it can't find the running version of Outlook. If I rerun the script with Outlook open, the new email is created. Any ideas?

Code: Select all

DetectHiddenWindows, On
Process, Exist, outlook.exe
If !ErrorLevel
{
    Run outlook.exe
    Sleep 15000
}
outlookApp := ComObjActive("Outlook.Application")
olMailItem := 0
MailItem := outlookApp.CreateItem(olMailItem)
MailItem.Display

Vh_
Posts: 203
Joined: 17 Mar 2017, 22:06

Re: Open Outlook & Send Email Using COM

Post by Vh_ » 01 May 2018, 17:16

PoorInRichfield, as a guess, try putting this line in after you create your object.

Code: Select all

;Untested, don't have outlook setup on this machine

outlookApp.visible := true
also, this may be more efficient

Code: Select all

If !ErrorLevel
{
    Run outlook.exe
    WinWaitExist, OutlookTitleName
}

Hope this helps! ;)

Vh

User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Open Outlook & Send Email Using COM  Topic is solved

Post by FanaticGuru » 01 May 2018, 18:08

PoorInRichfield wrote:AutoHotKey newbie here...

I'm creating a script that should run Outlook if the user doesn't already have it open, create an email, and send it... or just create the new email and send it if Outlook is already running. I'm stuck on the part of opening Outlook. The script below will open Outlook, but the call to ComObjActive fails as though it can't find the running version of Outlook. If I rerun the script with Outlook open, the new email is created. Any ideas?

Code: Select all

DetectHiddenWindows, On
Process, Exist, outlook.exe
If !ErrorLevel
{
    Run outlook.exe
    Sleep 15000
}
outlookApp := ComObjActive("Outlook.Application")
olMailItem := 0
MailItem := outlookApp.CreateItem(olMailItem)
MailItem.Display
It is easier to just try to hook on to an active Outlook and if it fails, create a new instance of Outlook.

Code: Select all

try
	outlookApp := ComObjActive("Outlook.Application")
catch
	outlookApp := ComObjCreate("Outlook.Application")
MailItem := outlookApp.CreateItem(0)
MailItem.Display
FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks

PoorInRichfield
Posts: 5
Joined: 01 May 2018, 16:50

Re: Open Outlook & Send Email Using COM

Post by PoorInRichfield » 02 May 2018, 09:02

Thanks for the replies...

The try/catch block by Fantastic Guru works perfectly. Unlike my code that fired-up the entire Outlook app, FG's solution just creates a new mail window, which is faster (and actually works!)

justlee

Re: Open Outlook & Send Email Using COM

Post by justlee » 17 Sep 2018, 13:39

Can this code always be running? Then trigger creating a new email when a shortcut key is pressed, something like ^+m::

User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Open Outlook & Send Email Using COM

Post by FanaticGuru » 17 Sep 2018, 18:20

justlee wrote:Can this code always be running? Then trigger creating a new email when a shortcut key is pressed, something like ^+m::
Yes, just pretty much like any other hotkey.

Code: Select all

+^m::
	try
		outlookApp := ComObjActive("Outlook.Application")
	catch
		outlookApp := ComObjCreate("Outlook.Application")
	MailItem := outlookApp.CreateItem(0)
	MailItem.Display
return
FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks

Guest

Re: Open Outlook & Send Email Using COM

Post by Guest » 18 Sep 2018, 06:37

I really apologize on that FG. Totally new to ahk. I didn't think it through. What I really wanted was slightly different once I thought this all the way through.

I'd like to be able to delay closing Outlook to send the email. I've found (once I did figure out how to keep the script running; apologies on wasting your time there) Outlook closes too quickly after the email is composed and alt+s is pressed to send. This results in the email sitting in the Outbox rather than sending. I'm thinking this is a timing issue. Not sure on that though.

Is there a way to delay the closing so the email sends instead of sitting in the Outbox?

Also, FG, I have to 2nd everyone here: you're what makes the WWW a great place to be. I've shared stuff over the years in answers and blogs and other stuff. But, I've felt that my answers, were not, all that unique or helpful. Yours are.

Ahk_fan
Posts: 237
Joined: 31 Aug 2018, 14:34
Contact:

Re: Open Outlook & Send Email Using COM

Post by Ahk_fan » 18 Sep 2018, 15:33

Hello,

for me are this one of best versions to send Email :
See this post: https://autohotkey.com/board/topic/6081 ... ery-ahk-l/

through COM-CDO without opening Outlook --> Credits to Sean and shajul:

Code: Select all

pmsg 			:= ComObjCreate("CDO.Message")
pmsg.From 		:= """AHKUser"" <[email protected]>"
pmsg.To 		:= "[email protected]"
pmsg.BCC 		:= ""   ; Blind Carbon Copy, Invisable for all, same syntax as CC
pmsg.CC 		:= "[email protected], [email protected]"
pmsg.Subject 	:= "Message_Subject"

;You can use either Text or HTML body like
pmsg.TextBody 	:= "Message_Body"
;OR
;pmsg.HtmlBody := "<html><head><title>Hello</title></head><body><h2>Hello</h2><p>Testing!</p></body></html>"


sAttach   		:= "Path_Of_Attachment" ; can add multiple attachments, the delimiter is |

fields := Object()
fields.smtpserver   := "smtp.gmail.com" ; specify your SMTP server
fields.smtpserverport     := 465 ; 25
fields.smtpusessl      := True ; False
fields.sendusing     := 2   ; cdoSendUsingPort
fields.smtpauthenticate     := 1   ; cdoBasic
fields.sendusername := "[email protected]"
fields.sendpassword := "your_password_here"
fields.smtpconnectiontimeout := 60
schema := "http://schemas.microsoft.com/cdo/configuration/"


pfld :=   pmsg.Configuration.Fields

For field,value in fields
	pfld.Item(schema . field) := value
pfld.Update()

Loop, Parse, sAttach, |, %A_Space%%A_Tab%
  pmsg.AddAttachment(A_LoopField)
pmsg.Send()
an other version:

Code: Select all

run, mailto:[email protected]?subject=This ist my subject&body=bodytext&attachment="c:\temp\test.txt"
an other version:

Code: Select all

run, Outlook.exe /c ipm.note /a `"c:\temp\test.txt`"
next version:

Code: Select all

	
	path := "C:\temp\test.txt"
	olMailItem := 0
	MailItem := ComObjActive("Outlook.Application").CreateItem(olMailItem)
	MailItem.SentOnBehalfOfName := "[email protected]"
	MailItem.To := "[email protected]"
	olFormatHTML := 2
	MailItem.Subject := "Subjecttext"
	MailItem.BodyFormat := olFormatHTML
	;Text HTLM
	MailItem.HTMLBody := "
	<HTML>
	<H2>Head</H2><BODY>text1<br>link: <a href=`'" . A_ScriptDir . "`'>Link</a><br>text2</BODY></HTML>"
	MailItem.Attachments.Add(path)
	MailItem.Send           ; or MailItem.Display if you wnt only display
regards,
AHK_fan :)
https://hr-anwendungen.de

User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Open Outlook & Send Email Using COM

Post by FanaticGuru » 18 Sep 2018, 20:19

Guest wrote:I'd like to be able to delay closing Outlook to send the email. I've found (once I did figure out how to keep the script running; apologies on wasting your time there) Outlook closes too quickly after the email is composed and alt+s is pressed to send. This results in the email sitting in the Outbox rather than sending. I'm thinking this is a timing issue. Not sure on that though.

Is there a way to delay the closing so the email sends instead of sitting in the Outbox?
Yes, that is a quandary. I always have Outlook running so have not fooled around much with these timing issues of opening and closing Outlook. And it does appear to be a timing issue.

When Outlook is running already and will continue running, no problem.

I can also send an email completely by COM where the script is opening, composing, sending and then closing Outlook. Usually completely in the background without displaying anything.

But when you start Outlook and just display a new email dialog and then put it into the hands of the user to hit the Send button it is out of the control of the script. When that Send button is click, Outlook just puts it in the Outbox where then it is scheduled and sent at a later time. When Outlook is running normally that later time is usually a few seconds later. But in this case Outlook closes down immediatly, leaving the email in the Outbox unsent.

I will have to think about this abit. There is probably a solution but it is a pretty trick problem for such a simple seeming task as a shortcut to bring up the Outlook new email panel (when Outlook is closed).

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks

justlee

Re: Open Outlook & Send Email Using COM

Post by justlee » 20 Sep 2018, 11:14

FG: I'm reading the documentation and messing around now. It's highly unlikely I'll create a solution before you. If I do solve this quandary (so appropriate), I will post back.

jsong55
Posts: 219
Joined: 30 Mar 2021, 22:02

Re: Open Outlook & Send Email Using COM

Post by jsong55 » 07 Apr 2021, 01:39

Need help trying to retrieve formatted text from a word document and put it in the body of an email.

Would like to know 2 ways to do it. 1. Via CreateItem in Outlook and 2. Via Active window

Code I used to copy out formatted word content

Code: Select all

	dir := "E:\Documents\"
		wordfile := dir "\test.docx"
		;wD := ComObjActive("Word.Application")
		wD := ComObjGet(wordfile)
		wD.Range.FormattedText.Copy
		
And code for possibly putting it in outlook?

Code: Select all

oL := ComObjActive("Outlook.Application")
em := oL.Application.CreateItem(0)
em.Display()
em.to := "[email protected]"
em.Subject := "Just An Email"
em.BodyFormat := 2 ; 1 plain 2 HTML 3, rtf 0 unspecified
em.Body := "Hi`nHow are you" 

User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Open Outlook & Send Email Using COM

Post by FanaticGuru » 07 Apr 2021, 15:43

jsong55 wrote:
07 Apr 2021, 01:39
Need help trying to retrieve formatted text from a word document and put it in the body of an email.

This is the basics of creating a new Outlook email and pasting a Word document into the body.

Code: Select all

; Copy Whole Story from Word
wdApp := ComObjActive("Word.Application")
wdApp.Selection.WholeStory
wdApp.Selection.Copy
wdApp.Selection.End := True

; Create Email and Paste Clipboard to Email Body
olApp := ComObjActive("Outlook.Application")
olMailItem := olApp.CreateItem(0) ; 0 = Mail Item
wdDoc := olMailItem.GetInspector.WordEditor
wdDoc.Range(0,0).Paste
olMailItem.Display
This example requires both Outlook and the Word document to already be open but that could all be done programmatically if needed. Everything including sending the email could also be done in the background.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks

jsong55
Posts: 219
Joined: 30 Mar 2021, 22:02

Re: Open Outlook & Send Email Using COM

Post by jsong55 » 08 Apr 2021, 23:37

Awesome works! Thanks @FanaticGuru

Jakobus
Posts: 56
Joined: 01 Jul 2019, 13:26

Re: Open Outlook & Send Email Using COM

Post by Jakobus » 10 Jun 2022, 08:21

Dear Friends of AHK-Scripts,

I'm astonished about the nice solution by @FanaticGuru's code above.

See:
"This is the basics of creating a new Outlook email and pasting a Word document into the body."

Kind question:
Is there any solution available to add the WORD document in an open email above - as an answer of an existing mail?

Thanks in advance

User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Open Outlook & Send Email Using COM

Post by FanaticGuru » 28 Jun 2022, 17:31

Jakobus wrote:
10 Jun 2022, 08:21
See:
"This is the basics of creating a new Outlook email and pasting a Word document into the body."

Kind question:
Is there any solution available to add the WORD document in an open email above - as an answer of an existing mail?

How or which email you link to for adding the Word document does not change the process.

Here is an example of getting the olMailItem for the currently open email window.

Code: Select all

; Copy Whole Story from Word
wdApp := ComObjActive("Word.Application")
wdApp.Selection.WholeStory
wdApp.Selection.Copy
wdApp.Selection.End := True

; Create Email and Paste Clipboard to Email Body
olApp := ComObjActive("Outlook.Application")
olMailItem := olApp.ActiveWindow.CurrentItem
wdDoc := olMailItem.GetInspector.WordEditor
wdDoc.Range(0,0).Paste
olMailItem.Display

Word has to be open and an email window must be open.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks

User avatar
FanaticGuru
Posts: 1906
Joined: 30 Sep 2013, 22:25

Re: Open Outlook & Send Email Using COM

Post by FanaticGuru » 09 Aug 2022, 18:51

FanaticGuru wrote:
18 Sep 2018, 20:19
Guest wrote:I'd like to be able to delay closing Outlook to send the email. I've found (once I did figure out how to keep the script running; apologies on wasting your time there) Outlook closes too quickly after the email is composed and alt+s is pressed to send. This results in the email sitting in the Outbox rather than sending. I'm thinking this is a timing issue. Not sure on that though.

Is there a way to delay the closing so the email sends instead of sitting in the Outbox?
Yes, that is a quandary. I always have Outlook running so have not fooled around much with these timing issues of opening and closing Outlook. And it does appear to be a timing issue.

When Outlook is running already and will continue running, no problem.

I can also send an email completely by COM where the script is opening, composing, sending and then closing Outlook. Usually completely in the background without displaying anything.

But when you start Outlook and just display a new email dialog and then put it into the hands of the user to hit the Send button it is out of the control of the script. When that Send button is click, Outlook just puts it in the Outbox where then it is scheduled and sent at a later time. When Outlook is running normally that later time is usually a few seconds later. But in this case Outlook closes down immediatly, leaving the email in the Outbox unsent.

I will have to think about this abit. There is probably a solution but it is a pretty trick problem for such a simple seeming task as a shortcut to bring up the Outlook new email panel (when Outlook is closed).

FG

Here is a solution to the email ending up sitting in the outbox when the new email dialog is brought up without Outlook being open to start with:

Code: Select all

; Data
Account := "[email protected]"
To := "[email protected]"
Subject := "Test"
Body =
(Join
This is HTML body of email.
<a href="http://www.ahkscript.org/">http://www.ahkscript.org/</a><br>
)

; Create Email with Data
olApp := ComObjCreate("Outlook.Application")
olNameSpace := olApp.GetNamespace("MAPI")
olEmail := olApp.CreateItem(0)	; olMailItem := 0
olEmail.SendUsingAccount := olNameSpace.Accounts.Item(Account)
olEmail.To := To
olEmail.BodyFormat := 2	; olFormatHTML := 2
olEmail.Subject := Subject
olEmail.HTMLBody := Body
olEmail.Display

; ^^^^^ Above is standard stuff to start a new email and display it for the user to finish ^^^^^
; vvvvv Below is the part that waits for the user to finish and then make sure the email is actually sent and not just sitting in Outbox vvvvv

; Wait for olEmail dialog to be closed which will then trigger an error as olEmail will not exist anymore
Loop
{
    Sleep 500
    try
        olEmail.Sent ; check any property
    catch
        break
}

; Closing the olEmail dialog will close Outlook so must restart
olApp := ComObjCreate("Outlook.Application")
olNameSpace := olApp.GetNamespace("MAPI")
for olSync in olNameSpace.SyncObjects
    olSync.Start  ; Send/Receive

Basically the key is to wait for the user to finish composing the email and send it manually (which closes Outlook), then reopen Outlook and do a Send/Receive for all groups.

FG
Hotkey Help - Help Dialog for Currently Running AHK Scripts
AHK Startup - Consolidate Multiply AHK Scripts with one Tray Icon
Hotstring Manager - Create and Manage Hotstrings
[Class] WinHook - Create Window Shell Hooks and Window Event Hooks

Jakobus
Posts: 56
Joined: 01 Jul 2019, 13:26

Re: Open Outlook & Send Email Using COM

Post by Jakobus » 19 Aug 2022, 08:00

Dear FantasticGuru,

Thanks a lot for your help!

Regarding
"Here is an example of getting the olMailItem for the currently open email window."

Your solution is a really really good.
It's like magic how good it works.

It makes the user happy.
More than I can give back.

Thanks once more.

Post Reply

Return to “Ask for Help (v1)”