How to send an email using separate mailbox in Outlook 2013 - c#

I have a number of mailboxes set-up in Outlook, and I would like to use Interop to send an email, but not from the default Outlook account.
I have the following email boxes:
Main email mailbox (default)
support mailbox
info mailbox
accounts mailbox
How do I go about sending an email using the separate mailbox to send email?
The below code to send the email from the mail email box is as follows:
Outlook.Account account = GetAccountForEmailAddress(oApp, smtpaddress);
oMsg.SendUsingAccount = account;
oRecip.Resolve();
//oMsg.Send();
(oMsg as Microsoft.Office.Interop.Outlook._MailItem).Send();
public static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
{
try
{
Outlook.Accounts accounts = application.Session.Accounts;
foreach (Outlook.Account account in accounts)
{
// When the e-mail address matches, return the account.
if (account.SmtpAddress == smtpAddress)
{
return account;
}
}
}
catch (Exception ex)
{
WriteToErrorFile("GetAccountForEmailAddress Method Error on: {0} " + ex.Message);
}
}

If you have got multiple accounts configured in the single mail profile you need to use the SendUsingAccount property of the MailItem class which allows to set an Account object that represents the account under which the MailItem is to be sent.
But if you have separate profiles with Exchange accounts configured and want to send on behalf of another user consider using the SentOnBehalfOfName property of the MailItem class.
Note, 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.

Related

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

Construct Outlook Tasks and E-Mail Invites using C#

Our software supports using C# for scripting purposes.
We can add Using and Assembly references to the software interface.
Our software can send HTML Body Mails or normal E-Mails.
The scenario as follows:
A scheduled task on the server runs over night, calls our scripts and send e-mails automatically
I have added the assembly reference Microsoft.Office.Interop.Outlook but I am struggling to find a way to send a task or calendar invite.
Appreciate any help.
Thank you
Typically you create a new mail/task/meeting 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 you check whether the recipient was resolved or not and, finally, send the message, for example:
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);
}
}
You may find the following articles helpful:
How To: Create and send an Outlook message programmatically
How To: Fill TO,CC and BCC fields in Outlook programmatically
How To: Create a new Outlook Appointment item
How To: Create a new Task item in Outlook
How To: Create and send an Outlook message programmatically
Be aware, 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.

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

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).

How to overcome " Cannot open the mailbox for this user because the user does not have a server mailbox " COMException in outlook programming?

I have developed a WPF based tool in .NET 4.5 in which I am trying to fetch information from emails in one of the outlook accounts.
However I am getting runtime COMException with message "Cannot open the mailbox for this user because the user does not have a server mailbox".
I know this happens when email accounts have different exchange servers.
Is there any way we can overcome this & access account which is on different exchange server?
Below is the code block which I am using to select particular account from multiple ones. GetSharedDefaultFolder is the method that is raising the exception:
foreach (Microsoft.Office.Interop.Outlook.Account account in accounts)
{
// When the e-mail address matches, return the account.
if (account.SmtpAddress.Contains("ABC.com"))
{
mapiNameSpace = myApp.GetNamespace("MAPI");
//selecting Inbox folder
Microsoft.Office.Interop.Outlook.Recipient recipent =
mapiNameSpace.CreateRecipient(account.SmtpAddress);
recipent.Resolve();
if (recipent.Resolved)
{
return mapiNameSpace.GetSharedDefaultFolder(
recipent,
Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
}
}
}
I would be grateful if anyone could help.

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.

Categories