How To: Create and send an Outlook message programmatically
Today I want to tell you the story about sending messages in Outlook programmatically. In one of my recent posts I showed two possible ways of creating and showing a new Outlook message. And now I want to make an addition to that: demonstrate how you can send a message programmatically. So, let’s start!
The Outlook Object Model has the Send method. The MailItem, AppointmentItem, MeetingItem, MobileItem, SharingItem and TaskItem classes provide this method to the programmer. It doesn’t accept or return any value (or object). It just does its job – sends a message. However, in order to send a message Outlook needs to know whom to deliver it to. The Recipients property is used for such a task. It returns an instance of the Recipients class. The Recipients class contains all recipients of your message, i.e. instances of the Recipient class in Outlook.
The Recipients collection provides you the Add method that adds new recipients to the collection. The method accepts a string which contains the name of a recipient or a full SMTP e-mail address and returns a new instance of the Recipient class. Please pay special attention to the fact that the recipient’s name must be valid: it should have a corresponding entry in your address book .The collection also provides you the ResolveAll method, which doesn’t accept any parameters and returns a Boolean value indicating whether all recipients in the collection were resolved or not (false – if one or more entries were not resolved, i.e. don’t have corresponding entries in the address book). The Recipient class also provides the Resolved property which can be used instead of the ResolveAll method of the Recipients class. Note, if you specified an SMTP e-mail address, you don’t need to have a “mapped” entry in the address book – one-off entry will be created.
In the code below, I create a new mail object, set the Subject property in order to identify it in my Inbox and then add the recipient to the Recipients collection of the item. Then I check whether the recipient was resolved or not and, finally, send the message. Please note that you will need to replace the recipient’s name with a valid one from your Outlook address book to get the code running correctly. The CreateSendItem method accepts an instance of the Application class in Outlook and then does its job!
C# and Add-in Express:
private void CreateSendItem(Outlook._Application OutlookApp) { Outlook.MailItem mail = null; Outlook.Recipients mailRecipients = null; Outlook.Recipient mailRecipient = null; try { mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; mail.Subject = "A programatically generated e-mail"; mailRecipients = mail.Recipients; mailRecipient = mailRecipients.Add("Eugene Astafiev"); mailRecipient.Resolve(); if (mailRecipient.Resolved) { mail.Send(); } else { System.Windows.Forms.MessageBox.Show( "There is no such record in your address book."); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, "An exception is occured in the code of add-in."); } finally { if (mailRecipient != null) Marshal.ReleaseComObject(mailRecipient); if (mailRecipients != null) Marshal.ReleaseComObject(mailRecipients); if (mail != null) Marshal.ReleaseComObject(mail); } }
VB.NET and Add-in Express:
Private Sub CreateSendItem(OutlookApp As Outlook._Application) Dim mail As Outlook.MailItem = Nothing Dim mailRecipients As Outlook.Recipients = Nothing Dim mailRecipient As Outlook.Recipient = Nothing Try mail = OutlookApp.CreateItem(Outlook.OlItemType.olMailItem) mail.Subject = "A programatically generated e-mail" mailRecipients = mail.Recipients mailRecipient = mailRecipients.Add("Eugene Astafiev") mailRecipient.Resolve() If (mailRecipient.Resolved) Then mail.Send() Else System.Windows.Forms.MessageBox.Show( "There is no such record in your address book.") End If Catch ex As Exception System.Windows.Forms.MessageBox.Show(ex.Message, "An exception is occured in the code of add-in.") Finally If Not IsNothing(mailRecipient) Then Marshal.ReleaseComObject(mailRecipient) If Not IsNothing(mailRecipients) Then Marshal.ReleaseComObject(mailRecipients) If Not IsNothing(mail) Then Marshal.ReleaseComObject(mail) End Try End Sub
C# and VSTO:
using System.Runtime.InteropServices; // ... private void CreateSendItem(Outlook.Application Application) { Outlook.MailItem mail = null; Outlook.Recipients mailRecipients = null; Outlook.Recipient mailRecipient = null; try { mail = Application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem; mail.Subject = "A programatically generated e-mail"; mailRecipients = mail.Recipients; mailRecipient = mailRecipients.Add("Eugene Astafiev"); mailRecipient.Resolve(); if (mailRecipient.Resolved) { mail.Send(); } else { System.Windows.Forms.MessageBox.Show( "There is no such record in your address book."); } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message, "An exception is occured in the code of add-in."); } finally { if (mailRecipient != null) Marshal.ReleaseComObject(mailRecipient); if (mailRecipients != null) Marshal.ReleaseComObject(mailRecipients); if (mail != null) Marshal.ReleaseComObject(mail); } }
VB.NET and VSTO:
Imports System.Runtime.InteropServices ' ... Private Sub CreateSendItem(Application As Outlook.Application) Dim mail As Outlook.MailItem = Nothing Dim mailRecipients As Outlook.Recipients = Nothing Dim mailRecipient As Outlook.Recipient = Nothing Try mail = Application.CreateItem(Outlook.OlItemType.olMailItem) mail.Subject = "A programatically generated e-mail" mailRecipients = mail.Recipients mailRecipient = mailRecipients.Add("Eugene Astafiev") mailRecipient.Resolve() If (mailRecipient.Resolved) Then mail.Send() Else System.Windows.Forms.MessageBox.Show( "There is no such record in your address book.") End If Catch ex As Exception System.Windows.Forms.MessageBox.Show(ex.Message, "An exception is occured in the code of add-in.") Finally If Not IsNothing(mailRecipient) Then Marshal.ReleaseComObject(mailRecipient) If Not IsNothing(mailRecipients) Then Marshal.ReleaseComObject(mailRecipients) If Not IsNothing(mail) Then Marshal.ReleaseComObject(mail) End Try End Sub
See you on our forums and in the e-mail support!
57 Comments
How do we do the above in MS 365 Outlook ?
Hi Brian,
Please take a look at the Office 365 – Exchange Online examples article on our technical blog.
I am a .net/c# developer. I am very new to Add-In-Express and VB. I am trying to send an email programatically from a button. I’ve copied the method for vb and Add-in-Express. How do i call CreateSendItem from the button click event, meaning what do i pass in?
Hello Candice,
First of all, thank you for choosing Add-in Express!
If you develop an Add-in Express based Outlook COM add-in, the AddinModule class provides you with the OutlookApp property which returns an instance of the Application class. You can pass that instance to the CreateSendItem method.
If you have any questions or need further assistance don’t hesitate to contact our support team via our forums or e-mail.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agencySubmit.Click
CreateSendItem(OutlookApp)
End Sub
Gives me error.. “OutlookApp is not declared. It may be inaccessible due to its protection level”
I did a search for OutlookApp and found it in AddinModule.vb
Public ReadOnly Property OutlookApp() As Outlook._Application
Get
Return CType(HostApplication, Outlook._Application)
End Get
End Property
Candice,
Where do you handle the Click event of the button?
Anyway, please try to use the static AddinExpress.MSO.ADXAddinModule.CurrentInstance property to get an instance of the AddinModule class. Then you can cast it to your actual module type which provides the OutlookApp property.
that helped me getting passed a successful build…
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles agencySubmit.Click
CreateSendItem(AddinExpress.MSO.ADXAddinModule.CurrentInstance)
End Sub
but when i run it and click the button, it gives me a runtime error…
“Unable to cast object of type ‘SalesOutlookAddin.AddinModule’ to type ‘Microsoft.Office.Interop.Outlook._Application’
Hi Candice,
Note, you need to cast an instance of the AddinModule class to your actual module type which provides the OutlookApp property. Please try the following code:
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim app As Outlook.Application = CType(Me.AddinModule, MyAddin49.AddinModule).OutlookApp
CreateSendItem(app)
End Sub
i tried this
Dim app As Outlook.Application = CType(Me.AddinModule, MyAddin49.AddinModule).OutlookApp
CreateSendItem(app)
it gave me these errors 1.AddinModule is not a member of my form
2.type “myaddin49.addmodule” is not defined
is there a way to declare it
Hi Ebuka,
Where this code is being executed? Do you develop an Outlook add-in or a standalone application?
I created a module in vb.net VSTO,and when I use the call createSendItem() how do I pass an argument to it
Hi Ebuka,
Thank you for the details. I think you can use the Globals.ThisAddIn.Application variable:
CreateSendItem(Globals.ThisAddIn.Application)
i hav this code to call my module:
Globals.ThisAddIn.Application.CreateSendItem()
CreateSendItem(Globals.ThisAddIn.Application)
i assume variable is the name of my module
but i get a line under global telling me that name ‘globals’ is not declared
Hi Ebuka,
When you create a VSTO project, Visual Studio automatically generates a class named Globals in the project. So, you should have access to the Globals class. Could you please send me your project for testing?
i created an infopath form,and will add the values of the fields to an excel work sheet the code below does that in vb.net:
N:B reference the COM microsoft excel 14.0 object and microsoft outlook 14.0 object for the module im using VSTO vb.net 2010
Imports Microsoft.Office.InfoPath
Imports System
Imports System.Xml
Imports excel = Microsoft.Office.Interop.Excel
Imports office = Microsoft.Office.core
Imports Outlook = Microsoft.Office.interop.Outlook
Imports Microsoft.Office.Interop.Outlook
Imports System.Windows.forms
Imports System.Xml.XPath
Namespace newblank
Public Class FormCode
‘ Member variables are not supported in browser-enabled forms.
‘ Instead, write and read these values from the FormState
‘ dictionary using code such as the following:
‘
‘ Private Property _memberVariable() As Object
‘ Get
‘ _memberVariable = FormState(“_memberVariable”)
‘ End Get
‘ Set
‘ FormState(“_memberVariable”) = value
‘ End Set
‘ End Property
‘ NOTE: The following procedure is required by Microsoft InfoPath.
‘ It can be modified using Microsoft InfoPath.
Private Sub InternalStartup(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Startup
AddHandler DirectCast(EventManager.ControlEvents(“CTRL4_5”), ButtonEvent).Clicked, AddressOf CTRL4_5_Clicked
End Sub
Public Sub CTRL4_5_Clicked(ByVal sender As Object, ByVal e As ClickedEventArgs)
‘ Write your code here.
Dim xlApp As New excel.Application
Dim xlWb As excel.Workbook
Dim xlsheet As excel.Worksheet
Dim rs As excel.Range
Dim lRow As Long = 0
With xlApp
.Visible = True
xlWb = .Workbooks.Open(“\\NIGLAGFN001\einwach$\Sync\ebuka.xlsx”)
xlsheet = xlWb.Sheets(“Sheet1″)
With xlsheet
If xlApp.WorksheetFunction.CountA(.Cells) 0 Then
lRow = .Cells.Find(What:=”*”, _
After:=.Range(“A1”), _
LookAt:=excel.XlLookAt.xlPart, _
LookIn:=excel.XlFindLookIn.xlFormulas, _
SearchOrder:=excel.XlSearchOrder.xlByRows, _
SearchDirection:=excel.XlSearchDirection.xlPrevious, _
MatchCase:=False).Row + 1
Else
lRow = 1
End If
End With
Dim fieldValue As String = MainDataSource.CreateNavigator().SelectSingleNode( _
“/my:myFields/my:field1”, NamespaceManager).Value
Dim fieldValue1 As String = MainDataSource.CreateNavigator().SelectSingleNode( _
“/my:myFields/my:field2”, NamespaceManager).Value
With xlsheet
.Range(“A” & lRow).Value = fieldValue
.Range(“B” & lRow).Value = fieldValue1
System.Windows.Forms.MessageBox.Show(“inputed”)
Dim lblUserName As String
lblUserName = SystemInformation.UserName
System.Windows.Forms.MessageBox.Show(lblUserName)
End With
call createSendItem()’the module is called here
End With
releaseObject(xlsheet)
releaseObject(xlWb)
releaseObject(xlApp)
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As System.Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
End Class
End Namespace
then a module to send mail when the excel worksheet has been updated
Imports Outlook = Microsoft.Office.interop.Outlook
Imports Microsoft.Office.Interop.Outlook
Imports System.Net.Mail
Imports System.Windows.forms
Imports System.Runtime.InteropServices
Module Module1
Public Sub CreateSendItem(ByVal Application As Outlook.Application)
Dim mail As Outlook.MailItem = Nothing
Dim mailRecipients As Outlook.Recipients = Nothing
Dim mailRecipient As Outlook.Recipient = Nothing
Try
mail = Application.CreateItem(Outlook.OlItemType.olMailItem)
mail.Subject = “A programatically generated e-mail”
mailRecipients = mail.Recipients
mailRecipient = mailRecipients.Add(“aliyu ishaku”)
mailRecipient.Resolve()
If (mailRecipient.Resolved) Then
mail.Send()
Else
System.Windows.Forms.MessageBox.Show(“There is no such record in your address book.”)
End If
Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show(ex.Message, “An exception is occured in the code of add-in.”)
Finally
If Not mailRecipient Is Nothing Then Marshal.ReleaseComObject(mailRecipient)
If Not mailRecipients Is Nothing Then Marshal.ReleaseComObject(mailRecipients)
If Not mail Is Nothing Then Marshal.ReleaseComObject(mail)
End Try
End Sub
End Module
then the it gives me the error name ‘globals’ is not declared
Hi Ebuka,
You can try this code:
Dim olApp As New Outlook.Application
Dim ns As Outlook._NameSpace = olApp.GetNamespace(“MAPI”)
ns.Logon()
CreateSendItem(olApp)
Marshal.ReleaseComObject(ns)
Marshal.ReleaseComObject(olApp)
Thanks, i had a successful build but a run time error that “An exception is occured in the code of add-in”
wud appreciate ur help
Ebuka,
Please debug your code. What code line throws the exception?
This is the line Catch ex As System.Exception
System.Windows.Forms.MessageBox.Show
(ex.Message, “An exception is occured in the code of
add-in.”)
keeps giving me the error:operations aborted(exception from HRESULT:00×80004004 (E_ABORT)
Hi Ebuka,
That provides me with no information at all to provide help. I need to know which exactly code line throws the exception. Is it possible for you to send me the whole project (or some demo project with the same behavior) for testing?
Hi Eugene,
What the best away to save email as msg in send event?
I’ve no problems to save it to temp file, but when i open the file (*.msg) the email is in unsent state. Add-in express have any event before send event?
Hello Mauro,
The email isn’t sent yet when in the ItemSend event. And if you intercept the MailItem.Send event, the it occurs even before the ItemSend event.
The email has MailItem.Sent set to true when its copy is saved to the Sent Items folder (or to the folder specified in the MailItem.SaveSentMessageFolder property). Try intercepting the ItemAdd event of the Items collection of that folder and use MailItem.SavesAs. In Add-in Express the ItemAdd event is mapped to the ProcessItemAdd method of the Outlook Items (not Item!) Events class, see the Add New Item dialog of your add-in project.
A couple questions:
Is the addin or stand alone application using the Outlook installed on the users computer? That is, is it sending thru his Outlook on his behalf?
If yes, how do I use is signature when sending?
Thank you,
Paul
Hello Paul,
The code above can be used in an add-in or standalone application that automates Outlook. The email is created and sent using the permissions of the user who starts Outlook. If a signature is defined for that account, it is inserted when the email is created. Before the email is sent, you can find the signature wrapped in a hidden bookmark called “_MailAutoSig”; you access it using the Word object model.
Hello.
I want to send mail to multi recipients individually.
So, I get the recipients’ smtp address from current Outlook item as below.
and then I want to send mail one person by one person using ‘foreach’ sentence.
But I think that the current mailitem may be expired after performing mail.send().
Just one mail is sent successfully, and then the outlook new item window is closed.
How can I modify this?
public void button1_Click(Office.IRibbonControl control)
{
Outlook.MailItem mail = Globals.ThisAddIn.Application.ActiveInspector().CurrentItem as Outlook.MailItem;
System.Windows.Forms.MessageBox.Show(“your ribbon button work!”);
GetSMTPAddressForRecipients(mail);
}
private void GetSMTPAddressForRecipients(Outlook.MailItem mail)
{
MessageBox.Show(“In GetSMTP!”);
const string PR_SMTP_ADDRESS = “https://schemas.microsoft.com/mapi/proptag/0x39FE001E”;
Outlook.Recipients recips = mail.Recipients;
foreach (Outlook.Recipient recip in recips)
{
Outlook.PropertyAccessor pa = recip.PropertyAccessor;
string smtpAddress = pa.GetProperty(PR_SMTP_ADDRESS).ToString();
mail.To = smtpAddress;
((Outlook._MailItem)mail).Send();
}
}
Hello,
You need to create and send a new email for every recipient (set of recipients).
Thank you for your reply.
I did do that you say as below.
private void mysend(string[] ToAddress, string Subject, string Body)
{
int length = ToAddress.Length;
//System.Windows.Forms.MessageBox.Show(length);
for (int i = 0; i < length; i++)
{
if(ToAddress[i] == null)
{
break;
}else {
Outlook.MailItem eMail = (Outlook.MailItem)
Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
eMail.Subject = Subject;
eMail.To = ToAddress[i];
eMail.Body = Body;
eMail.Importance = Outlook.OlImportance.olImportanceLow;
((Outlook._MailItem)eMail).Send();
System.Windows.Forms.MessageBox.Show("mysend!");
}
}
}
But there is a problem.
Image & excel format in mail body is destroyed.
because body of new item is string.
How can I fix it??
Thank you.
If the text is in the HTML format set MailItem.BodyFormat=Outlook.OlBodyFormat.olFormatHTML and assign the MailItem.HTMLBody property. See also https://www.pcreview.co.uk/threads/plain-text-with-bodyformat-html-not-showing-correctly.3756803/
Thank you for your reply.
It was successful to use HTMLBody. but images of body was not represented.
Is there a way to prevent to close the current mailitem after sending.
I think if I could do that, whole problem will be solved.
Hello,
> It was successful to use HTMLBody. but images of body was not represented.
Please check https://social.msdn.microsoft.com/Forums/vstudio/en-US/6c063b27-7e8a-4963-ad5f-ce7e5ffb2c64/how-to-embed-image-in-html-body-in-c-into-outlook-mail?forum=vsto.
> Is there a way to prevent to close the current mailitem after sending.
An item is almost a physical entity. To send it, you need to close it.
I’m having an issue with the actual sending of the email. The actual mail.send() always causes the error:
System.Runtime.InteropServices.COMException
Exception from HRESULT: 0x80004004 (E_ABORT)
and then it crashes. Does anyone know why this is happening and a potential fix to it? I have heard the issue could come from Microsoft’s permissions to automatically send emails but I can’t confirm that nor find a solution to it.
Hello Michael,
Could you please send me some code (use the contact form at https://www.add-in-express.com/support/askus.php) so that I could test it?
Hello,
I wonder how can I resolve Group Name in my outlook contact.
I tried to resolve group name using your sample code.
try
{
mail.Subject = “A programatically generated e-mail”;
mailRecipients = mail.Recipients;
mailRecipient = mailRecipients.Add(“MyGroup2”);
mailRecipient.Resolve();
if (mailRecipient.Resolved)
{
System.Windows.Forms.MessageBox.Show(
“There is a record in your address book.”);
}
else
{
System.Windows.Forms.MessageBox.Show(
“There is no such record in your address book.”);
}
}
But the result is failed. “There is no such record in your address book”.
Check if the group name is spelled correctly. Check if other recipient names get resolved.
hi .
How can I trigger ‘BeforeCheckNames’ Event.
I want to check validation about recipients’ email addess when I click my custom ‘Send’ button in my addin.
And I want to display ‘check names’ dialog in Outlook.
Hello,
You can call Recipients.ResolveAll(). I believe you talk about the Select Names dialog. If so, you call Namespace.GetSelectNamesDialog(), see https://msdn.microsoft.com/en-us/library/office/ff867382%28v=office.15%29.aspx.
Hi sir,
i want to send a mail on behalf of some other employee . how can i do it (it should not come like “myname onbehalf of someother name”).
can you please help me out??
hi
my question is similar to malla’s.
how do i controll the sender of the email if i want it to be someone else?
do i just use MailItem.Sender = “other sender”?
Hello Malla and Dror,
There are two ways to control the sender: 1) send an email on behalf of another user or 2) send an email using an account defined in the current profile.
Regarding #2, you set the MailItem.SendUsingAccount property in the ItemSend event; see https://msdn.microsoft.com/en-us/library/office/ff869311%28v=office.15%29.aspx.
As to #1, it looks like you need to set MailItem.Sender in the ItemSend event. The code I test is as follows:
private void adxOutlookAppEvents1_ItemSend(object sender, ADXOlItemSendEventArgs e) {
if (e.Item is Outlook._MailItem) {
Outlook._MailItem mail = e.Item as Outlook._MailItem;
Outlook.Recipient recipient = OutlookApp.Session.CreateRecipient(“UserName”);
mail.Sender = recipient.AddressEntry;
Marshal.ReleaseComObject(recipient);
}
}
Currently I have a problem though: Outlook (Exchange?) sends me an email informing that “The email system had a problem processing this message. It won’t try to deliver this message again.” I try to find what causes this. I’m afraid this may take some time.
Note that you must have permissions to send emails on behalf of that user.
Hi,
On ItemSend event, I am setting custom properties to Outlook.MailItem and sending it over. When I receive it, I am not finding the custom properties I set. I am sending the TNEF property (“https://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/8582000B”) = true before sending but still the custom properties are missed in the received item.
Can you please tell me what I am missing?
Thanks,
Lawrence.
Hello Lawrence,
Please check https://support.microsoft.com/en-us/help/907985/changes-to-custom-properties-in-outlook.
Hi Andrei,
I referred the above link and tried to send a RTF format email.
When I receive the mail even after setting the body format to RTF, I receive HTML email with no custom property added by me.
FYI, I have set below properties:
SetProperty(“MyCustomProperty”, value, mailItem);//Setting the custom property
mailItem.PropertyAccessor.SetProperty(BlackbirdConstants.SendCustomProerty, true);//Setting the TNEF to true
mailItem.BodyFormat = Microsoft.Office.Interop.Outlook.OlBodyFormat.olFormatRichText;
After receiving the email, I dont see my custom property. Also, there is no Winmail.dat file attached. Can you please help me on this?
Please let me know if you need any other info.
Thanks,
Lawrence.
Hello Lawrence,
At https://support.microsoft.com/en-us/help/907985/changes-to-custom-properties-in-outlook, they do *not* state that sending an email in the RTF format will preserve custom properties. On the contrary, they say:
===
By default, Outlook no longer enables Internet mail to create new custom properties. <...> This change mostly affects messages that are sent in encapsulated TNEF (Winmail.dat), where the sender has used the Send using Outlook Rich Text Format option. <...>
===
Here’s a citation showing what custom properties persist:
===
Only properties that are already created in the default mail delivery store are preserved for incoming e-mail messages.
===
Hi,i am able to send email via outlook using vb.net in my local machine. but its not working in server. my question is do i need to install outlook in server also to work this? please help me.Thanks in advanced.
I am not sure whether only referring outlook dll to the application will do?
I add the DLL reference and executed the application on my local PC where outlook is installed..It worked..But as soon as I deployed the same to hosted web server, it failed since the Outlook interop is looking for outlook instance on the hosted server..
Any alternative??
Hello Anjaneya,
Microsoft doesn’t recommended installing Outlook on the server side. You can google for a non-Outlook based solution.
Hi, i have a requirement to open attachments in outlook once the email button is clicked in DotNet web application.
I add the outlook Interop DLL reference and executed the application on my local PC where outlook is installed..It worked..But as soon as I deployed the same to hosted web server, it failed since the Outlook interop is looking for outlook instance on the hosted server. is there Any alternative solution for above requirement without installing the MS office in my web server??
Hello Anjaneya,
I suppose you are expected to open the attachment on the client, not on the server.
In my C# code I am using Outlook dll to send a meeting request through a web application. It was working fine on my system (Dev) but when I published the code on QA server it gives error. Is outlook needs to configure on that server also? As on Dev it uses my credentials to send the meeting request. Is there any work around rather than configuring the Outlook on QA server.
Below is the code :-
private static void ScheduleInterview(string StartDate, string EndDate, string TechTrackId, string EmailId)
{
Microsoft.Office.Interop.Outlook.AppointmentItem appointment = null;
Microsoft.Office.Interop.Outlook.Recipients recipients = null;
Microsoft.Office.Interop.Outlook.Recipient recipient = null;
try
{
EmailId = “testmail@test.com”;
Microsoft.Office.Interop.Outlook.Application OutlookApp = new Microsoft.Office.Interop.Outlook.Application();
appointment = (Microsoft.Office.Interop.Outlook.AppointmentItem)OutlookApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olAppointmentItem);
appointment.Subject = “eMee – Dev – Tech Track ID ” + TechTrackId + “: Interview Scheduled”;
//appointment.Start = DateTime.Now.AddHours(1);
//appointment.Duration = 60;
appointment.Body = “Your Interview is Scheduled”;
appointment.Location = “To Be Decided”;
appointment.Start = Convert.ToDateTime(StartDate);
appointment.Recipients.Add(EmailId);
appointment.End = Convert.ToDateTime(EndDate);
appointment.ReminderSet = true;
appointment.ReminderMinutesBeforeStart = 15;
appointment.MeetingStatus = Microsoft.Office.Interop.Outlook.OlMeetingStatus.olMeeting;
appointment.Respond(Microsoft.Office.Interop.Outlook.OlMeetingResponse.olMeetingTentative, false, false);
//recipient.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
// if (recipient.Resolve())
appointment.Send();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
if (recipient != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(recipient);
if (recipients != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(recipients);
if (appointment != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(appointment);
}
}
Hi Piyush,
I am afraid there cannot be any workaround. Your code uses the Outlook Object Model and Outlook must be installed for the code to work properly.
I installed the Outlook Application on QA server but I am getting access denied error while creating Outlook item from web application as follows :-
The web application is running under ApplicationPool identity.
Exception Message: Retrieving the COM class factory for component with CLSID {0006F03A-0000-0000-C000-000000000046}
failed due to the following error: 80070005 Access is denied.
(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Can you please help me in this case ?
Hello Piyush,
As far as I understand, your web application does not have appropriate rights. Sorry, I am not an expert in ASP.NET and therefore cannot suggest anything of value.
hai
how to sent calender event through Outlook.MailItem from specifi email id using c#
Hello Anji,
See the SendUsingAccount property.
I assume that a meeting request is sent via a MeetingItem object, not MailItem. I suggest that you verify this by preventing Outlook from sending emails (use UI options it provides) and studying the Outlook item(s) created when you create a meeting request.
HI,
I would like to automate “Out Of Office” automated emails from VB.net. I am using Outlook 365.
Can anyone suggest how to do this? I am very new to VB.net coding. Eager to learn more.
Kindly help.
Regards,
Ritesh Hegde
Hello Ritesh,
The Outlook object model doesn’t provide a means to achieve this.
There’s Outlook Redemption; see https://www.dimastr.com/redemption/home.htm. It provides classes/members that seemeingly allow you to have some (or, maybe, full) control over that feature. We don’t have any relation to that product so you’ll need to find your way yourself.