473,625 Members | 3,111 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating email in outlook

Hi

I am trying to find the way to create an email in outlook. I am using the
code given at the end. It works fine the first time but calling the code
second time gives the following error;

Unhandled Exception: System.Reflecti on.TargetInvoca tionException: Exception
has been thrown by the target of an invocation. --->
System.Runtime. InteropServices .InvalidComObje ctException: COM object that
has been separated from its underlying RCW can not be used.
at Outlook.Applica tionEvents_Even tProvider..ctor (Object )

The error comes on the 'OutlookApp = New Outlook.Applica tion' line. Any
ideas what I am missing?

Thanks

Regards

= Code Follows =============== ========

Imports System.Runtime. InteropServices

Public Class clsOfficeWrappe r
Private WithEvents OutlookApp As Outlook.Applica tion
Private WithEvents em As Outlook.MailIte m

Public Sub NewEmail(ByVal EmailTemplate As String, ByVal SendTo As String)
Dim ns As Outlook.NameSpa ce

OutlookApp = New Outlook.Applica tion ' <=== This lines give the
exception second time round
ns = OutlookApp.GetN amespace("MAPI" )
ns.Logon()

em = DirectCast(Outl ookApp.CreateIt emFromTemplate( EmailTemplate),
Outlook.MailIte m)
.To = SendTo
.Display(False)

Marshal.Release ComObject(em)
ns.Logoff()
Marshal.Release ComObject(ns)
Marshal.Release ComObject(Outlo okApp)
End Sub
....

End Class
Nov 20 '05 #1
2 2229
John,
Marshal.Release ComObject(Outlo okApp)
Do not use ReleaseComObjec t if you are using WithEvents! ReleaseComObjec t
will release the com object, which means the com object itself is no longer
valid. WithEvents will try to remove the event handlers on the previous
object (the one you just destroyed) when you create a new instance of it.
The previous object is a .NET object, that had its com object destroyed,
WithEvents is not able to remove the COM event handlers, hence the
exception!
Public Class clsOfficeWrappe r
Private WithEvents OutlookApp As Outlook.Applica tion
Private WithEvents em As Outlook.MailIte m
Seeing as OutlookApp & em are class level variables you should create them
in the class's constructor (Sub New) and destroy them (ReleaseComObje ct)
using the Disposable/Finalization pattern.

For info on implementing Dispose along with Finalize (you really should
implement both!) see:

http://msdn.microsoft.com/library/de...izeDispose.asp

If you truly need to handle the events in the NewEmail method I would
suggest you use AddHandler & RemoveHandler and move the variables local to
the Subroutine.
Public Sub NewEmail(ByVal EmailTemplate As String, ByVal SendTo As String) Dim OutlookApp As Outlook.Applica tion
AddHandler OutlookApp...
Dim em As Outlook.MailIte m
AddHandler em... Dim ns As Outlook.NameSpa ce

OutlookApp = New Outlook.Applica tion ' <=== This lines give the
exception second time round
ns = OutlookApp.GetN amespace("MAPI" )
ns.Logon()

em = DirectCast(Outl ookApp.CreateIt emFromTemplate( EmailTemplate),
Outlook.MailIte m)
.To = SendTo
.Display(False)
RemoveHandler em... Marshal.Release ComObject(em)
ns.Logoff()
Marshal.Release ComObject(ns) RemoveHandler OutlookApp... Marshal.Release ComObject(Outlo okApp)
End Sub
Of course if you are not handling any events then the AddHandler &
RemoveHandler are not needed...

Hope this helps
Jay

"John" <jo**@nospam.in fovis.co.uk> wrote in message
news:O%******** ********@TK2MSF TNGP10.phx.gbl. .. Hi

I am trying to find the way to create an email in outlook. I am using the
code given at the end. It works fine the first time but calling the code
second time gives the following error;

Unhandled Exception: System.Reflecti on.TargetInvoca tionException: Exception has been thrown by the target of an invocation. --->
System.Runtime. InteropServices .InvalidComObje ctException: COM object that
has been separated from its underlying RCW can not be used.
at Outlook.Applica tionEvents_Even tProvider..ctor (Object )

The error comes on the 'OutlookApp = New Outlook.Applica tion' line. Any
ideas what I am missing?

Thanks

Regards

= Code Follows =============== ========

Imports System.Runtime. InteropServices

Public Class clsOfficeWrappe r
Private WithEvents OutlookApp As Outlook.Applica tion
Private WithEvents em As Outlook.MailIte m

Public Sub NewEmail(ByVal EmailTemplate As String, ByVal SendTo As String)
Dim ns As Outlook.NameSpa ce

OutlookApp = New Outlook.Applica tion ' <=== This lines give the
exception second time round
ns = OutlookApp.GetN amespace("MAPI" )
ns.Logon()

em = DirectCast(Outl ookApp.CreateIt emFromTemplate( EmailTemplate),
Outlook.MailIte m)
.To = SendTo
.Display(False)

Marshal.Release ComObject(em)
ns.Logoff()
Marshal.Release ComObject(ns)
Marshal.Release ComObject(Outlo okApp)
End Sub
...

End Class

Nov 20 '05 #2
Thanks. Great. That has worked nicely.

Regards
"Jay B. Harlow [MVP - Outlook]" <Ja************ @msn.com> wrote in message
news:uu******** ******@TK2MSFTN GP11.phx.gbl...
John,
Marshal.Release ComObject(Outlo okApp)
Do not use ReleaseComObjec t if you are using WithEvents! ReleaseComObjec t
will release the com object, which means the com object itself is no

longer valid. WithEvents will try to remove the event handlers on the previous
object (the one you just destroyed) when you create a new instance of it.
The previous object is a .NET object, that had its com object destroyed,
WithEvents is not able to remove the COM event handlers, hence the
exception!
Public Class clsOfficeWrappe r
Private WithEvents OutlookApp As Outlook.Applica tion
Private WithEvents em As Outlook.MailIte m
Seeing as OutlookApp & em are class level variables you should create them
in the class's constructor (Sub New) and destroy them (ReleaseComObje ct)
using the Disposable/Finalization pattern.

For info on implementing Dispose along with Finalize (you really should
implement both!) see:

http://msdn.microsoft.com/library/de...izeDispose.asp
If you truly need to handle the events in the NewEmail method I would
suggest you use AddHandler & RemoveHandler and move the variables local to
the Subroutine.
Public Sub NewEmail(ByVal EmailTemplate As String, ByVal SendTo As String)
Dim OutlookApp As Outlook.Applica tion
AddHandler OutlookApp...
Dim em As Outlook.MailIte m
AddHandler em...
Dim ns As Outlook.NameSpa ce

OutlookApp = New Outlook.Applica tion ' <=== This lines give the
exception second time round
ns = OutlookApp.GetN amespace("MAPI" )
ns.Logon()

em = DirectCast(Outl ookApp.CreateIt emFromTemplate( EmailTemplate),
Outlook.MailIte m)
.To = SendTo
.Display(False)

RemoveHandler em...
Marshal.Release ComObject(em)
ns.Logoff()
Marshal.Release ComObject(ns)

RemoveHandler OutlookApp...
Marshal.Release ComObject(Outlo okApp)
End Sub


Of course if you are not handling any events then the AddHandler &
RemoveHandler are not needed...

Hope this helps
Jay

"John" <jo**@nospam.in fovis.co.uk> wrote in message
news:O%******** ********@TK2MSF TNGP10.phx.gbl. ..
Hi

I am trying to find the way to create an email in outlook. I am using

the code given at the end. It works fine the first time but calling the code
second time gives the following error;

Unhandled Exception: System.Reflecti on.TargetInvoca tionException:

Exception
has been thrown by the target of an invocation. --->
System.Runtime. InteropServices .InvalidComObje ctException: COM object that has been separated from its underlying RCW can not be used.
at Outlook.Applica tionEvents_Even tProvider..ctor (Object )

The error comes on the 'OutlookApp = New Outlook.Applica tion' line. Any
ideas what I am missing?

Thanks

Regards

= Code Follows =============== ========

Imports System.Runtime. InteropServices

Public Class clsOfficeWrappe r
Private WithEvents OutlookApp As Outlook.Applica tion
Private WithEvents em As Outlook.MailIte m

Public Sub NewEmail(ByVal EmailTemplate As String, ByVal SendTo As String) Dim ns As Outlook.NameSpa ce

OutlookApp = New Outlook.Applica tion ' <=== This lines give the
exception second time round
ns = OutlookApp.GetN amespace("MAPI" )
ns.Logon()

em = DirectCast(Outl ookApp.CreateIt emFromTemplate( EmailTemplate),
Outlook.MailIte m)
.To = SendTo
.Display(False)

Marshal.Release ComObject(em)
ns.Logoff()
Marshal.Release ComObject(ns)
Marshal.Release ComObject(Outlo okApp)
End Sub
...

End Class



Nov 20 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
7511
by: Sam | last post by:
My db looks after the hiring and lending of equipment, the form which books out equipment hired prints a signout sheet and automatically inserts an appointment into outlook advising the operator on the due date that a particular hire is due. I have used microsoft's automated appointment code to do this, what I would also like the code to do is to email an appointment to the person hiring the gear. Knowing that you can email an...
2
7625
by: Susan Bricker | last post by:
I know that it is possible to generate an email letter and send it from VBA behind a form. I've done that. However, is it possible to create a DRAFT email letter and leave it in the Drafts folder (in Microsoft Outlook)? If it is possible, would you share the source code with me? Thanks. Regards, SueB
3
2342
by: W Akthar | last post by:
Hi I am trying to create a windows service which queries SQL Server on timed intervals and depending on the results send appointments to Outlook. The problem lies when I try to create an outlook application object.
5
2272
by: | last post by:
Trying to learn about manipulating collections of objects, and populating these objects dynamically from datasources. Could someone post a code sample that shows the following: Instantiating a collection object -- say, a dictionary. Populating that collection object with custom objects, say, Person. What I really want to see is how to populate the properties of those Person objects from a datasource: instantiate one Person, fill...
0
1736
by: Jason James | last post by:
Hi all, does anyone have any suggestions as to the steps involved in creating a DL using VB.Net. I have some Outlook automation experience but I'm not sure what the objects are that I should be creating. There is a distribution list item object, but no dsitribution list object to contain the items!
9
3010
by: RedMoosh | last post by:
is it possible to rn a client side vbscript to send messages using cdo.message and cdo.configuration? what are the requirements to do this? my wks are xp and 2000 and all have cdosys.dll registered. do i have to have outlook express loaded. i have workstations that don't have outlook but rather lotus notes and want to send email to an smtp server. these emails have local attachment thus the need to run client script versus server...
9
2240
by: ARC | last post by:
In case anyone has ran into this yet. The following code used to work with older versions of the MS Outlook library, but would error out in 2007: Dim objOutlook As Outlook.Application Dim objOutlookMsg As Outlook.MailItem Dim objOutlookRecip As Outlook.Recipient Dim objOutlookAttach As Outlook.Attachment Set objOutlook = CreateObject("Outlook.Application") ' Create the message. Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
1
3965
by: rmarek | last post by:
I need to create an Outlook email from within Access that adds all the contents of a specific file folder as attachments. I have been able to get the email created and drop it into the Outlook drafts folder using VBA, although only one (1) file attachment from the specified folder is added to the email. How do I iterate through the contents of the file folder and get them all to be added as attachments ?? Any sample code would be GREATLY...
3
2053
by: ITrishGuru | last post by:
Hi all, For my IT final year project I have to access mail items in outlook 2003 and parse them. I have read and researched on the net and library for about a week now. I have to do the project in c# using visualc# 2005 Express Edition. I know this may limit me to manully coding a little more but I dont mind that. So far I think I have to create a COM adddin and communicate via
0
8189
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8692
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8635
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8354
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7182
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6116
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5570
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4192
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2621
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.