Not able to create Outlook item in server code - c#

I am trying to send meeting invites from user to a contact person using my chatbot. My solution is working fine when I run outlook in the background but when I close it, it throws an exception:
System.Runtime.InteropServices.COMException
When I tried to deploy this code on my server it showed me the same exception.
The code works on my local machine when I keep outlook running in the background.
Microsoft.Office.Interop.Outlook.Application outlookApplication = new Microsoft.Office.Interop.Outlook.Application();
// outlookApplication.Startup += new Microsoft.Office.Interop.Outlook.ApplicationEvents_11_StartupEventHandler(outlookApp_Startup);
Microsoft.Office.Interop.Outlook.AppointmentItem appointmentItem = (Microsoft.Office.Interop.Outlook.AppointmentItem)outlookApplication.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olAppointmentItem);
appointmentItem.Subject = "Dina need further assistance";
appointmentItem.Body = "Please Help me ";
appointmentItem.Location = "Room #1";
appointmentItem.Start = DateTime.Now;
foreach (string email in Recipients)
{
appointmentItem.Recipients.Add(email);
}
//appointmentItem.Recipients.Add("karmit.dhawan#accenture.com");
appointmentItem.End = DateTime.Now.AddHours(1);
appointmentItem.ReminderSet = true;
appointmentItem.ReminderMinutesBeforeStart = 15;
appointmentItem.Importance = Microsoft.Office.Interop.Outlook.OlImportance.olImportanceNormal;
appointmentItem.BusyStatus = Microsoft.Office.Interop.Outlook.OlBusyStatus.olBusy;
appointmentItem.MeetingStatus = Microsoft.Office.Interop.Outlook.OlMeetingStatus.olMeeting;
appointmentItem.Recipients.ResolveAll();
appointmentItem.Display(true);

Related

EWS query result wierdness

I've got a strange problem with EWS. I am writing a console app which queries my inbox for messages with a subject containing 'Ref:' which is absolutely fine, I get a connection no problem, run the query, get some results. but strangely it is only returning messages that are from internal senders, any messages sent from outside the exchange organisation do not appear in the results.
ultimately I am going to be using a service account to connect to various mailboxes and find various emails with certain references in the subject....
Does anyone have any idea what might be going on? I've gone over it and over it and can't find any reason why it's doing it.
It's Exchange 2010 SP2
ExchangeService exchService = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
exchService.Url = new System.Uri("https://xxx.xxxxxxxxx.co.uk/EWS/Exchange.asmx");
exchService.UseDefaultCredentials = true;
var userMailbox = new Mailbox("xxxx#xxxx.co.uk");
var inboxFolder = new FolderId(WellKnownFolderName.Inbox, userMailbox);
String qString = "subject:\"Ref:\"";
ItemView view = new ItemView(20);
view.PropertySet = new PropertySet(ItemSchema.Id);
try
{
FindItemsResults<Item> results = exchService.FindItems(inboxFolder, qString, view);
if (results.Items.Count > 0)
{
foreach (Item item in results.Items)
{
Console.WriteLine(item.Id);
if (item is EmailMessage)
{
EmailMessage bindMessage = EmailMessage.Bind(exchService, item.Id.ToString());
String sender = bindMessage.Sender.Address.ToString();
String Body = bindMessage.Body.Text.ToString();
Console.WriteLine("Sender: " + sender);
}
}
}
}

Delete Emails from Outlook Folder Using C#

I can't seem to get this working. I am trying to iterate through all the mail items in a folder I created named 'SlaughterPDFs' and delete the emails.
Below is the code I am using. In this code I was just trying to delete the mail items out of the outlook 'Drafts' folder.
public void deleteMails()
{
Application tempApp = new Application();
MAPIFolder tempInbox = default(MAPIFolder);
Items JunkItems = default(Items);
tempInbox = tempApp.GetNamespace("MAPI").
GetDefaultFolder(OlDefaultFolders.olFolderDrafts);
JunkItems = tempInbox.Items;
MailItem DeleteMail = default(MailItem);
foreach (object newMail_loopVariable in JunkItems)
{
DeleteMail = (MailItem)newMail_loopVariable;
DeleteMail.Delete();
}
JunkItems = null;
tempInbox = null;
tempApp = null;
}
Anyone have any idea what I am doing wrong? Or should I be moving these emails to a new folder.
I'm not sure where you are having an issue.
If you replace your for loop with the below while loop it should delete all emails in the folder.
while (tempInbox.Items.Count > 0)
{
DeleteMail = (MailItem)tempInbox.Items.GetFirst();
DeleteMail.Delete();
}
If you are having trouble accessing the folder I would use (assuming SlaughterPDFs is a sub folder of inbox):
tempInbox = tempApp.GetNamespace("MAPI").
GetDefaultFolder(OlDefaultFolders.olFolderInbox);
tempInbox = tempInbox.Folders["SlaughterPDFs"];

Interop Outlook - Sending Appointment from another mailbox

I have two mailboxes setup in Outlook.
I'll refer to them as "email1#mail.com" and "email2#mail.com".
I would like to use Interop to create and send an appointment to a specific email address calender, not just to the default outlook account.
using System;
using System.Diagnostics;
using System.Reflection;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace Program
{
class Program
{
public static void Main(string[] args)
{
// Create the Outlook application.
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Outlook.Account account = oApp.Session.Accounts["email2#mail.com"];
// Get the NameSpace and Logon information.
Microsoft.Office.Interop.Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
// Log on by using a dialog box to choose the profile.
oNS.Logon(Missing.Value, Missing.Value, true, true);
// Create a new mail item.
Microsoft.Office.Interop.Outlook.MailItem oMsg =(Microsoft.Office.Interop.Outlook.MailItem) oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
// Set the subject.
oMsg.Subject = "test";
// Set HTMLBody.
oMsg.HTMLBody = "test";
oMsg.To = "test#gmail.com";
//oMsg.CC = _cc;
//oMsg.BCC = _bcc;
oMsg.Save();
oMsg.SendUsingAccount = account;
// Add a recipient.
//Microsoft.Office.Interop.Outlook.Recipients oRecips = (Microsoft.Office.Interop.Outlook.Recipients)oMsg.Recipients;
// TODO: Change the recipient in the next line if necessary.
//Microsoft.Office.Interop.Outlook.Recipient oRecip = (Microsoft.Office.Interop.Outlook.Recipient)oRecips.Add(_recipient);
//oRecip.Resolve();
// Send.
(oMsg as Microsoft.Office.Interop.Outlook._MailItem).Send();
// Log off.
oNS.Logoff();
// Clean up.
//oRecip = null;
//oRecips = null;
oMsg = null;
oNS = null;
oApp = null;
}
}
}
This code works flawlessly in sending an email automatically to "test#gmail.com" from my email "email2#mail.com".
However, I would like to automatically create an appointment/meeting for a specific email address.
This is my current attempt:
using System;
using System.Diagnostics;
using System.Reflection;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace SendEventToOutlook
{
class Program
{
public static void Main(string[] args)
{
try
{
// Create the Outlook application.
Microsoft.Office.Interop.Outlook.Application oApp = new Microsoft.Office.Interop.Outlook.Application();
Outlook.Account account = oApp.Session.Accounts["email2#mail.com"];
// Get the nameSpace and logon information.
Microsoft.Office.Interop.Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
// Log on by using a dialog box to choose the profile.
oNS.Logon(Missing.Value, Missing.Value, true, true);
// Create a new Appointment item.
Microsoft.Office.Interop.Outlook.AppointmentItem appt =
(Microsoft.Office.Interop.Outlook.AppointmentItem)
oApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olAppointmentItem);
appt.Start = DateTime.Now;
appt.End = DateTime.Now.AddDays(7);
appt.Location = "Test";
appt.Body = "Test";
appt.AllDayEvent = false;
appt.Subject = "Test";
appt.Save();
appt.SendUsingAccount = account;
// Log off.
oNS.Logoff();
appt = null;
oNS = null;
oApp = null;
}
catch (Exception ex)
{
Debug.WriteLine("The following error occurred: " + ex.Message);
}
}
}
}
This code does create an appointment successfully, but it keeps creating an appointment for "email1#mail.com" instead of "email2#mail.com", which shouldn't happen as I've specified the sending account to be "email2#mail.com" from the lines:
Outlook.Account account = oApp.Session.Accounts["email2#mail.com"];
and then
appt.SendUsingAccount = account;
This is how my two email addresses are set up in Outlook: http://i.imgur.com/0eopV8A.png
Both the email addresses have different user names and are from different domains/mail servers, as shown in that screenshot.
Would anyone be able to see the problem I'm making or if there's a different solution?
Thank you.
It is not clear whether you have got two accounts set up in the single Mail profile or separate profiles.
The SendUsingAccount property of the AppointmentItem class allows to set an Account object that represents the account under which the AppointmentItem is to be sent. So, The SendUsingAccount property can be used to specify the account that should be used to send the AppointmentItem when the Send method is called. It is not what you are looking for I suppose.
Anyway, you can use the GetDefaultFolder method of the Store class which returns a Folder object that represents the default folder in the store and that is of the type specified by the FolderType argument. This method is similar to the GetDefaultFolder method of the NameSpace object. The difference is that this method gets the default folder on the delivery store that is associated with the account, whereas NameSpace.GetDefaultFolder returns the default folder on the default store for the current profile.
Thus, you can get the Calendar folder for the required account and add a new appointment there.
You may find the following articles in MSDN helpful:
How to: Create a Sendable Item for a Specific Account Based on the Current Folder (Outlook)
Using Multiple Accounts for the Same Profile on Outlook

Create multiple Outlook emails from C#

I'm new to C#. I've found how to create an outlook email from C#:
// Create a new MailItem.
Outlook._MailItem oMsg1;
oMsg1 = oApp.CreateItem(Outlook.OlItemType.olMailItem);
oMsg1.To = "amine#gmail.com";
oMsg1.Subject = "Test Subject";
oMsg1.Body = "test Body";
Outlook.Attachments oAttachs1 = oMsg1.Attachments;
// Add an attachment
string sSource1 = "C:\\testFile.xls";
Outlook.Attachment oAttach1;
oAttach1 = oAttachs1.Add(sSource1);
oMsg1.Display(true);
oApp = null;
oMsg1 = null;
oAttach1 = null;
oAttachs1 = null;
But I want to create multiple emails at the same time. So Outlook will display multiple email windows.
I tried a for loop to create multiple mailItem but this didn't work. Outlook displays only the first email.
Any idea ? Thanks!
Use oMsg1.Display(false);
When set to True, oMsg1.Display(true) means Outlook creates a 'Modal' window, meaning it freezes that particular email until it is sent or discarded.

Sharepoint 2010 SPImport.Run security exception

I want to use SPExport (which is working OK) and SPImport to copy one web to another location. I am using Application Page in Sharepoint Foundation 2010. This code is executed on a Button click event.
using (SPWeb web = site.OpenWeb(sourceWebUrl))
{
SPExportSettings exportSettings = new SPExportSettings();
exportSettings.FileLocation = exportPath;
exportSettings.BaseFileName = exportFileName;
exportSettings.SiteUrl = site.Url;
exportSettings.ExportMethod = SPExportMethodType.ExportAll;
exportSettings.FileCompression = true;
exportSettings.IncludeVersions = SPIncludeVersions.All;
exportSettings.IncludeSecurity = SPIncludeSecurity.All;
exportSettings.ExcludeDependencies = false;
exportSettings.ExportFrontEndFileStreams = true;
exportSettings.OverwriteExistingDataFile = true;
SPExportObject expObj = new SPExportObject();
expObj.IncludeDescendants = SPIncludeDescendants.All;
expObj.Id = web.ID;
expObj.Type = SPDeploymentObjectType.Web;
exportSettings.ExportObjects.Add(expObj);
SPExport export = new SPExport(exportSettings);
export.Run();
}
using (SPWeb web = site.OpenWeb(destinationWebUrl))
{
web.AllowUnsafeUpdates = true;
SPImportSettings importSettings = new SPImportSettings();
web.FileLocation = exportPath;
web.BaseFileName = exportFileName;
web.IncludeSecurity = SPIncludeSecurity.All;
web.UpdateVersions = SPUpdateVersions.Overwrite;
web.RetainObjectIdentity = false;
web.SiteUrl = site.Url;
web.WebUrl = web.Url;
web.Validate();
SPImport import = new SPImport(importSettings);
import.Run();
web.AllowUnsafeUpdates = false;
}
Exception "The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again. " is thrown when SPImport.Run() is called.
I haven't been able to find a solution for this problem neither adding FormDigest control on application page nor Allowing Unsafe Updates on the destination web.
Also, running this code from Console Application works OK, but if code runs from Application Page it is not working (even with elevated security).
Any help would be appreciated. Thanks.
Managed to do this by adding
SPUtility.ValidateFormDigest();
at line 1.

Categories

Resources