I am new to C# and I am attempting to automate sending an email from Outlook through the following code and it works fine in the development environment. I would like it to use the default user as the sender even if outlook is not open.
private void EmailMessage(string recipient, string subject, string body)
{
Microsoft.Office.Interop.Outlook.Application application = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.MailItem email = (Outlook.MailItem)application.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem);
try
{
email.Subject = subject;
email.Body = body;
email.To = recipient;
((Outlook._MailItem)email).Send();
_emailConfirmation = true;
}
catch (System.Runtime.InteropServices.COMException ex)
{
Logging.LogError("Trip Email Failed", ExceptionHelper.GetInnerMostException(ex));
_emailConfirmation = false;
}
finally
{
//release the objects used to send email after message has been sent\\
if (email != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(email);
if (application != null)
System.Runtime.InteropServices.Marshal.ReleaseComObject(application);
}
}
All users are assigned an account and have Outlook installed with a valid anti-virus. My concern is when it goes live, it will fail on the creation of a new instance of outlook or something else I am just not seeing. Do you think this will work with what I intend to accomplish when it goes live?
There is no error in the code, however I am seeing a lot of posts from people saying that you should not create an instance of outlook.application directly.
https://msdn.microsoft.com/en-us/library/office/bb622502.aspx
I think I may just be paranoid because I've never used a PIA before
There can be two main reasons why your code fails:
You get a security issue. See Outlook "Object Model Guard" Security Issues for Developers for more information about the issue and possible ways to bridge the gap and suppress or avoid such issues. Be aware, in some cases the dialog window will not be shown to a user, you just got an exception in the code.
The Click2Run edition of Office 2010 doesn't support automation. See Office 2010 Click-to-Run compatibility with add-ins for more information. Also you may find the How to: Verify Whether Outlook Is a Click-to-Run Application on a Computer article.
Try to use the Recipients property instead of the To field. And then use the Resolve or ResolveAll methods. See How To: Fill TO,CC and BCC fields in Outlook programmatically for more information.
Also I'd recommend adding any logging mechanisms to the code. So, you can analyze the log files and understand what is going on under the hood. For example, consider using the log4net library.
Related
I'm currently experiencing some strange behavior when sending e-mails using Outlook (Office 365 Pro Plus).
Our software can generate e-mails and show a new mail compose to the user with attachments which they selected from our software. (We use both Redemption from our software as Outlook Object Model using an Outlook Add-in Express add-in)
Below you can find the code for generating the e-mail using Redemption:
bool createEmail = false;
RDOSession session = new RDOSession();
session.Logon("", "", false, false, null, false);
RDOFolder folder = session.GetDefaultFolder(rdoDefaultFolders.olFolderDrafts);
RDOMail mail = folder.Items.Add("IPM.Note");
... Code for selecting receivers (returns string with emailadresses) ...
... Code for converting word documents to PDF / Adding the attachments to the mailitem ...
RDOUserProperty userProp = mail.UserProperties.Add("DMS_AttachmentCount", rdoUserPropertyType.olInteger, false, false);
userProp.Value = mail.Attachments.Count;
mail.Display();
I noticed that I'm not using
mail.Save();
Could that be the issue?
When we show the user the generated e-mail all attachments are in place and the user is able to open the attachments.
So far so good...
Here comes the problem:
On sending the e-mail, sometimes (i mean really sometimes) some of the
attachments are deleted from the e-mail. When the user goes to it's
sent items and selects the e-mail, some of the attachments are
deleted.
Since this occurs randomly, I'm not able to debug this issue.
What have I tried already:
Turn off ESET Nod32 and all of it's e-mail components
Disabled Office Secured Mode
Exclude certain file extensions from being scanned.
Checked for third party add-ins, so far only the list below is installed
The rest of the add-ins are default by Outlook
My question(s):
Is there somebody out there that has experienced the same problem?
How can I determine what happens inside the Item Send event?
What else can I turn off or apply on the server that might prevent this issue from happening?
Thanks.
I have read several posts and got a solution that use Microsoft.Office.Interop.Outlook to work to create a task in Outlook. Here is the code that will create a task in outlook for my user.
public void CreateOutlookTask()
{
Application outlookApp = new Application();
TaskItem oTask = outlookApp.CreateItem(OlItemType.olTaskItem);
Inspector oInspector = oTask.GetInspector;
oTask.Subject = "This is my task subject";
oTask.DueDate = Convert.ToDateTime("06/25/2011");
oTask.StartDate = Convert.ToDateTime("06/20/2011");
oTask.ReminderSet = true;
oTask.ReminderTime = Convert.ToDateTime("06/28/2006 02:40:00 PM");
oTask.Body = "This is the task body";
oTask.Status =OlTaskStatus.olTaskInProgress;
oTask.Save();
}
I still have two issues with the above code.
1) It will only create tasks for the user that is running the application. I hope to create tasks from a web app, so I need to be able to log into each users account because the web app will not have an outlook account.
2) Using Microsoft.Office.Interop.Outlook requires that outlook is installed. I would really like a solution that doesn't require outlook to be installed on the machine, but haven't found one.
Any help on the above two issues would be greatly appreciated.
You can use exchange web services to create items such as this without the need of the interop libraries.
Get started with EWS client applications
If using OOM is still an option, you can use Application.Session.GetSharedDefaultFolder to retrieve the default Tasks folder of another Exchange user. You can then create a new task there using MAPIFolder.Items.Add.
I've been successfully sending out appointment invites with outlook through c# in an asp.net application. I'm using the following code:
//send out the outlook notification
Outlook.Application outlookApp = new Outlook.Application();
Outlook.AppointmentItem newMeeting = outlookApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olAppointmentItem) as Outlook.AppointmentItem;
if (newMeeting != null)
{
newMeeting.MeetingStatus = Microsoft.Office.Interop.Outlook.OlMeetingStatus.olMeeting;
newMeeting.Location = "TBD";
newMeeting.Subject = "New SEB Consult";
newMeeting.Body = "A new meeting has been scheduled. If you're a member of the team, please accept";
newMeeting.Start = meetingDate;
newMeeting.Duration = 60;
Outlook.Recipient recipient = newMeeting.Recipients.Add("Smith John");
recipient.Type = (int)Outlook.OlMeetingRecipientType.olRequired;
((Outlook._AppointmentItem)newMeeting).Send();
}
This works, but my problem is that it's sending them from my email which I'm logged into with outlook on the same computer. I'd like to send them from a different email, so that they appear more like system notifications coming from my application rather than a personal email. I do have the username and password for the account, but the application is eventually going to be run on a remote server, so I can't just log into outlook with another email. Nothing I've been able to find changes the sender. Does anyone have any more information on how to change these credentials, or where it looks for the credentials?
You can't use OLE if you would like to control the emails. OLE is just to control the local outlook instance which is tied to the running account.
You must use the exchange API instead. With it you can create an appointment like described in this MSDN article: How to: Create appointments and meetings by using EWS in Exchange 2013
Appointment appointment = new Appointment(service);
// Set the properties on the appointment object to create the appointment.
appointment.Subject = "Tennis lesson";
appointment.Body = "Focus on backhand this week.";
appointment.Start = DateTime.Now.AddDays(2);
appointment.End = appointment.Start.AddHours(1);
appointment.Location = "Tennis club";
appointment.ReminderDueBy = DateTime.Now;
// Save the appointment to your calendar.
appointment.Save(SendInvitationsMode.SendToNone);
// Verify that the appointment was created by using the appointment's item ID.
Item item = Item.Bind(service, appointment.Id, new PropertySet(ItemSchema.Subject));
Console.WriteLine("\nAppointment created: " + item.Subject + "\n");
The library is open source and available at github.
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution. Read more about that in the Considerations for server-side Automation of Office article.
You may consider using the EWS Managed API, EWS, and web services in Exchange instead.
I am using this link for open outlook new mail window.
How to open Outlook new mail window c#
But It is working fine On Local machine but when I deployed it on server it shows below error.
Retrieving the COM class factory for component with CLSID
{0006F03A-0000-0000-C000-000000000046} failed due to the following
error: 80040154 Class not registered (Exception from HRESULT:
0x80040154 (REGDB_E_CLASSNOTREG)).
Microoft office outlook is install on local machine not on server.It is required to install and configure outlook on server.
Plz help.
Thanks.
1. Using Outlook
To send an email using outlook, we need to add a reference to the dynamic link library for Outlook which is called Microsoft.Office.Interop.Outlook.dll
For the same follow the below steps:
Go to your solution explorer
Click on add a reference
Click on .Net Tab
Go through the DLL and select Microsoft.Office.Interop.Outlook.dll
correctly.
when you have selected the correct reference you select the “OK” button and this reference will be added to your project under references.
using Outlook = Microsoft.Office.Interop.Outlook;
//method to send email to outlook
public void sendEMailThroughOUTLOOK()
{
try
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody.
//add the body of the email
oMsg.HTMLBody = "Hello, Jawed your message body will go here!!";
//Add an attachment.
String sDisplayName = "MyAttachment";
int iPosition = (int)oMsg.Body.Length + 1;
int iAttachType = (int)Outlook.OlAttachmentType.olByValue;
//now attached the file
Outlook.Attachment oAttach = oMsg.Attachments.Add(#"C:\\fileName.jpg", iAttachType, iPosition, sDisplayName);
//Subject line
oMsg.Subject = "Your Subject will go here.";
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add("jawed.ace#gmail.com");
oRecip.Resolve();
// Send.
oMsg.Send();
// Clean up.
oRecip = null;
oRecips = null;
oMsg = null;
oApp = null;
}//end of try block
catch (Exception ex)
{
}//end of catch
}//end of Email Method
For more information Open outlook
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
Read more about that in the Considerations for server-side Automation of Office article.
Consider using standard .Net classes or any other components designed for the server-side execution. In case of Exchange Server account you can use EWS (Exchange Web Services), see EWS Managed API, EWS, and web services in Exchange .
If you run that code on the server, who will see the newly created message? Even if there is a user logged in locally to the server, IIS runs without a desktop session.
If you want the message to be displayed on the client, that is where your code needs to run. Why not use a mailto url? It will work in any browser and the default email client will be opened. If you need something more sophisticated than that, you need to write your code in JavaScript and create an instance of the Outlook.Application object using new ActiveXObject(). You can only do that in IE and your site must be trusted to do that.
I have created outlook addin in C# to storing mail subjects in SQLite database using redemption(background). Can we access redemption method/Class of outlook add in into the windows service.
Outlook Object Model cannot be used from a service.
Do not use Outlook Object Model in a service. Secondly, you are assuming that you only have ContactItem objects in the folder, your code will break if there is a distribution list there.
The RDO family of Redemption objects can be used in a service
You are right, you shouldn't use the Outlook object model from a windows service. The Considerations for server-side Automation of Office article states the following:
Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
Redemption is a wrapper around a low-level API (Extended MAPI). But add-ins is a feature of Office applications. Extended MAPI doesn't know wnything about them. So, any wrappers (Redemption in your case) around Extended MAPI don't provide access to add-ins.
Consider using any other communication methods with your add-in, for example - .NET Remoting (WCF). You may consider your managed add-in as a regular .Net application.
using Microsoft.Office.Interop.Outlook;
using OutLook = Microsoft.Office.Interop.Outlook;
and the code will be
object missing = System.Reflection.Missing.Value;
try
{
OutLook.MAPIFolder fldContacts = null;;
OutLook._Application outlookObj = new OutLook.Application();
string folderName = "Default";
fldContacts = (OutLook.MAPIFolder)outlookObj.Session.GetDefaultFolder(OutLook.OlDefaultFolders.olFolderContacts);
//LOOPIN G THROUGH CONTACTS IN THAT FOLDER.
foreach (Microsoft.Office.Interop.Outlook._ContactItem contactItem in fldContacts.Items)
{
StringBuilder strb = new StringBuilder();
strb.AppendLine((contactItem.FirstName == null) ? string.Empty : contactItem.FirstName);
strb.AppendLine((contactItem.LastName == null) ? string.Empty : contactItem.LastName);
strb.AppendLine(contactItem.Email1Address);
strb.AppendLine(contactItem.Business2TelephoneNumber);
strb.AppendLine(contactItem.BusinessAddress);
//write to text file
StreamWriter sw = null;
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\LogFile.txt", true);
sw.WriteLine(DateTime.Now.ToString() + ": " + strb.ToString());
sw.Flush();
sw.Close();
}
}
catch (System.Exception ex)
{
throw new ApplicationException(ex.Message);
}