Cannot save the attachment. The operation failed. An object cannot be found error in server - c#

I am trying of save attachment of outlook mail, i am able to save attachment when it have data. but for empty attachment its throws exception that Cannot save the attachment. The operation failed. An object cannot be found.
In my local i am able to save but this issue is coming in server.
void saveattachments(Outlook.Attachment attachment)
{
string currentTime = DateTime.Now.ToString("hh_MM_ss");
try
{
attachment.SaveAsFile(GetConfigSettings("attachmentPath") + "\\attachment_" + "_" + currentTime + "_" + attachment.FileName);
}
catch(exception e)
{}
}
why it throws error in server for blank file but not in local.

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 MAPI instead (a low-level API on which Outlook is based on).

Related

Getting OutOfMemoryException when load a document with Microsoft.Office.Interop from IIS website

I have a .NET Core 6 web api that use Office interop to open a ppt document and convert it to pdf.
The application does not have problems when i debug it or when i publish it as a standalone application and run the .exe manually.
I need to publish the web api on IIS on a windows server but when i do i obtain the following error when try to call the api endpoint: "System.OutOfMemoryException: Insufficient memory to continue the execution of the program".
This is the method that made the conversion, exception is thrown by "pptApplication.Presentations.Open(originalPptPath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse)"
public static bool PowerPointToPdf(string originalPptPath, string pdfPath)
{
PowerPoint.Application pptApplication = null;
PowerPoint.Presentation pptPresentation = null;
object unknownType = Type.Missing;
var result = false;
//start power point
pptApplication = new PowerPoint.Application();
//open powerpoint document
pptPresentation = pptApplication.Presentations.Open(originalPptPath, MsoTriState.msoTrue, MsoTriState.msoTrue, MsoTriState.msoFalse);
if (pptPresentation == null)
return false;
pptPresentation.ExportAsFixedFormat(pdfPath, PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF, PowerPoint.PpFixedFormatIntent.ppFixedFormatIntentPrint);
result = true;
// Close and release the Document object.
if (pptPresentation != null)
{
pptPresentation.Close();
ReleaseObject(pptPresentation);
pptPresentation = null;
}
pptApplication.Quit();
ReleaseObject(pptApplication);
pptApplication = null;
return result;
}
I already tried to change the application pool identity with an admin user but nothing changed. I am aware that microsoft discourages the use of server-side office automation, i have already evaluated several libraries that don't use office automation to make the conversion, but the final result is qualitatively inferior.
You are on the right avenue - 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.
Microsoft strongly recommends that developers find alternatives to Automation of Office if they need to develop server-side solutions. Because of the limitations to Office's design, changes to Office configuration are not enough to resolve all issues. Microsoft strongly recommends a number of alternatives that do not require Office to be installed server-side, and that can perform most common tasks more efficiently and more quickly than Automation. Before you involve Office as a server-side component in your project, consider alternatives.
If you are dealing only with open XML documents in PowerPoint you may consider using the Open XML DSK for dealing with documents or converting them to another file format, see Welcome to the Open XML SDK 2.5 for Office for more information.
Or just consider using any third-party components designed for the server-side execution.

System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (0x80004004 (E_ABORT))

We have a Export Utility which exports all emails from Outlook to local directory. And our tools work perfectly fine. But now we are migrating to O365 and since then we are seeing issues with the tool.
Technically the does all the things like able to read all emails and its properties like Subject, From, To etc and also able to SAVE or MOVE to other folder within Outlook O365.
But I get an error "System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (0x80004004 (E_ABORT))" as soon I execute SAVEAS.
Below is the sample code
public static void ReadEmails()
{
try
{
Outlook.Application oApp = new();
// Get the MAPI namespace.
Outlook.NameSpace oNs = oApp.GetNamespace("MAPI");
oNs.Logon("*****#*****.com", System.Reflection.Missing.Value,
System.Reflection.Missing.Value, System.Reflection.Missing.Value);
Outlook.Folders fols = oNs.Folders;
Outlook.MAPIFolder inboxFolder = fols["****"].Folders["Inbox"];
foreach (Outlook.Folder fol in inboxFolder.Folders)
{
MessageBox.Show(fol.Name);
Outlook.Items items = fol.Items;
foreach(Outlook.MailItem mailItem in items)
{
MessageBox.Show(mailItem.Subject);
try
{
//mailItem.Move(inboxFolder); -- this works
mailItem.SaveAs("test.msg", Outlook.OlSaveAsType.olMSG);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
oNs.Logoff();
}
catch (System.Exception e)
{
Console.WriteLine("{0} Exception caught: ", e);
}
}
So do I have to do anything special?
FYI, the tool gets executed on user laptop as a user on his own email account.
The code looks good. I don't see anything strange there. But the following exception may indicate multiple issues:
System.Runtime.InteropServices.COMException (0x80004004): Operation aborted (0x80004004 (E_ABORT))
Most probably you have faced with a security issue in Outlook. "Security" in this context refers to the so-called "object model guard" that triggers security prompts and blocks access to certain features in an effort to prevent malicious programs from harvesting email addresses from Outlook data and using Outlook to propagate viruses and spam. These issues or prompts cannot simply be turned off, except in Outlook 2007 with an anti-virus application running.
The following strategies can be used for avoiding the security prompts/issues in Outlook:
A low-level API on which Outlook is based on - Extended MAPI (or any other third-party wrappers around that API, for example, Redemption).
Outlook Security Manager is a programming tool that allows you to suppress security alerts invoked by the code of your application or add-in that interacts with Microsoft Outlook 2000 - 2013.
In a corporate environment, the administrator may choose to loosen Outlook security for some or all users.
Develop a trusted COM add-in and call it for saving emails instead of using OOM directly. The add-in has access to a secure Application object which doesn't trigger security issues.
Another possible cause is that 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. Here is what MS states for such cases:
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.
I was able to fix the issue by changing following registry value to 2 (make sure to open registry as ADMIN)
HKEY_USERS > S-1-5-21-1132323721-62323254-1511918330-144209 > SOFTWARE > Policies > Microsoft > office > 16.0 > outlook > security
(Computer\HKEY_USERS\S-1-5-21-1132323721-62323254-1511918330-144209\SOFTWARE\Policies\Microsoft\office\16.0\outlook\security)
Dword: PromptOOMSaveAs
Value: 2
Note: Above BOLD value > you can get this by running whoami /user in command prompt

Issue launching Outlook using Office Interop

I am building an ASP webforms application in C# and I am trying to launch Outlook to send an email from the client computer.
I am using the following example, which I found online.
public void sendEmail(object sender, EventArgs e)
{
// Create the Outlook application.
Outlook.Application oApp = new Outlook.Application();
// Get the MAPI namespace.
Outlook.NameSpace oNS = oApp.GetNamespace("mapi");
// Log on by using the default profile or existing session (no dialog box).
oNS.Logon(Missing.Value, Missing.Value, false, true);
// Create a new mail item.
Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
// Set HTMLBody.
oMsg.HTMLBody = "Test";
//Subject line
oMsg.Subject = "Test Subject";
// Add a recipient.
Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
// Change the recipient in the next line if necessary.
Outlook.Recipient oRecip;
oRecip = (Outlook.Recipient)oRecips.Add("yyyyy#mydomain.co.uk");
oRecip.Resolve();
// Send.
oMsg.Send();
//Log off.
oNS.Logoff();
}
I am having issues at this line of code here:
oNS.Logon(Missing.Value, Missing.Value, false, true);
Even though I have an Outlook profile configured, when it runs this line of code, my app launches Outlook and displays the "Welcome to Outlook 2016" dialogue.
The expected behaviour is for it to launch Outlook, using the existing profile.
If Outlook is already open, I get an error stating:
System.Runtime.InteropServices.COMException: 'Retrieving the COM class
factory for component with CLSID
{0006F03A-0000-0000-C000-000000000046} failed due to the following
error: 80080005 Server execution failed (Exception from HRESULT:
0x80080005 (CO_E_SERVER_EXEC_FAILURE)).'
The expected behaviour is if Outlook is already open, is for my app to use the existing Outlook process.
Any help greatly appreciated.
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.
As a possible workaround, you may consider a low-level API on which Outlook is based on - Extended MAPI. Or just any wrapper around that API such as Redemption.
If you deal only with Exchange profiles you may consider using Exchange Web Services (EWS), see Start using web services in Exchange.

Programmatically generate Outlook email

I am creating a button in asp.net c# that when clicked will open up Outlook window.
I am referencing to the Microsoft.Office.Interop.Outlook dll, and using this in using statement:
using Outlook = Microsoft.Office.Interop.Outlook;
This the code.
private void CreateMailItem()
{
try
{
var outlookApp = new Outlook.Application();
var mailItem = (Outlook.MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
//var mailItem = (Outlook.MailItem)
// Application.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.Subject = "This is the subject";
mailItem.To = "someone#example.com";
mailItem.Body = "This is the message.";
mailItem.Importance = Outlook.OlImportance.olImportanceLow;
mailItem.Display(false);
}
catch (Exception)
{
throw;
}
}
I get error on the very first line, var outlookApp = new Outlook.Application();
The exception says:
{"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))."}
The exception you've posted is thrown when a referenced dll or depencies of this dll are not correctly installed.
In this case, it seems outlook or office is not with the correct version which you referenced, on your test machine?
Can't post this as comment.
I would like to know why you prefer the use of Outlook Interop?
I am using the mailto:// protocol if I wanted my program to send email on the user's current email client, though I use this on WinForms.
like http://www.rapidtables.com/web/html/mailto.htm
Outlook, just like any Office app, cannot be used from a service (such as IIS). Even if you did make it work, the new message window will be displayed on the server where the user will not see it anyway.
You can try to run a client-side JavaScritp code, but then you'd be limited IE only, Outlook would need to be locally installed, and your site must be trusted to be able to create COM objects in a script.
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 System.Net.Mail namespace for creating and sending emails in ASP.NET.

'Cannot create file' error while trying to send email with image from asp .net windows application using outllook

I am trying to send email from .net windows application using Microsoft.Office.Interop.Outlook. The mail is in html format and has an image embedded to it. Getting the following error when trying to attach the image,
"Cannot create file: XXX.jpg. Right-click the folder you want to create the file in, and then click Properties on the shortcut menu to check your permissions for the folder."
I dont have any issues with folder access. I am running the app on 64 bit computer with 32 bit outlook on it. When i dont embed image, i dont get any errors and it works fine.
string body = string.Empty;
using(StreamReader reader = new StreamReader(Environment.CurrentDirectory + #"/Mail Templates/XXX.txt"))
{
body = reader.ReadToEnd();
}
Outlook.Application oApp = new Outlook.Application();
Outlook._MailItem mailItem = (Outlook._MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
mailItem.To = "XXX";
string filename = Environment.CurrentDirectory + #"/Mail Templates/XXX.jpg";
mailItem.Attachments.Add(filename, (int)Outlook.OlAttachmentType.olEmbeddeditem, 1);
mailItem.HTMLbody = "true"
mailItem.Display(true);
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.
You can read more about that in the Considerations for server-side Automation of Office article.
You may consider using the EWS (Exchange Web Services) or BCL (Base Class Libraries from the .Net framework). See EWS Managed API, EWS, and web services in Exchange for more information.

Categories