Opening multiple Outlook Window Send Email with C# - c#

I need to open several Outlook windows previously populated with ticulo and email body for later user to inform the senders. I need to open several windows (I walk a grid to know how many windows).
I'm trying to do this with threads but an error message occurs saying: Outlook can not do this because the dialog box is open. Please close it and try again "
How to open multiple competing windows?
Test Call
private void button2_Click(object sender, EventArgs e)
{
int qtdEventos = dgvDescEvento.RowCount;
Thread[] Threads = new Thread[qtdEventos];
try
{
cEmail testeEmail = new cEmail();
for (int i = 0; i < qtdEventos; i++)
{
Threads[i] = new Thread(new ThreadStart(new cEmail().Monta));
}
foreach (Thread t in Threads)
{
t.Start();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Outlook = Microsoft.Office.Interop.Outlook;
namespace NavEventos.Class
{
class cEmail
{
private Outlook.Application outlookApp;
public cEmail()
{
outlookApp = new Outlook.Application();
}
public void Monta()
{
string pTitulo = "Title";
string pAssunto = "Body test";
Outlook._MailItem oMailItem = (Outlook._MailItem)outlookApp.CreateItem(Outlook.OlItemType.olMailItem);
Outlook.Inspector oInspector = oMailItem.GetInspector;
Outlook.Recipients oRecips = (Outlook.Recipients)oMailItem.Recipients;
#region MONTA ASSUNTO
oMailItem.Subject = pTitulo;
#endregion
#region MONTA CORPO DO E-MAIL
oMailItem.Body = pAssunto;
#endregion
oMailItem.Display(true);
}
}
}

You may not like this... but you shouldn't try. ;(
As you can see the Outlook COM interface is trying very hard to prevent you from doing this, it is one of the limitations of the outlook automation libraries that displaying a mail item is done in a modal kind of way.
There is good reason for this, your user is in your LOB application, then your code wants them to read an email in outlook, which you have done using the COM automation libraries for outlook. Now their outlook icon in the toolbar is flashing because a new email modal window has opened up, but this dialog may have opened up behind your current LOB app.
Now the user will need to switch context into Outlook to see the dialog and read the email.
If you can review your need to open these emails all at the same time then you and outlook com automation will get along just fine :)
Otherwise consider writing a plugin for Outlook and moving your email management routines into outlook itself. In there you can be very creative, sounds like you really need just a master - detail style of interface, like the main outlook browser, so you have a list of these emails and as the user clicks on them they are displayed in the preview inspector.
Maybe the solution is to use your logic to move these messages into a
specific folder in outlook, then use Outlook automation to make this
folder the current active window in outlook, then the user can decide
which emails they want to action or not.

Related

C# how to CC myself

I'm working on a VSTO project for Outlook. Very simple application with an icon on the ribbon. When user clicks on it, the selected email will be sent to the manager. It is working with the following code. But I want to add the sender as CC in the email. So whenever user clicks on it, the selected email will be sent to the manager and the user will be CC'd on it. So user will get a copy too. How can I CC the sender?
here is the code:
public partial class Ribbon1
{
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
}
private void button1_Click(object sender, RibbonControlEventArgs e)
{
Outlook.Application application = new Outlook.Application();
Outlook.NameSpace ns = application.GetNamespace("MAPI");
try
{
//get selected mail item
Object selectedObject = application.ActiveExplorer().Selection[1];
Outlook.MailItem selectedMail = (Outlook.MailItem)selectedObject;
//create message
Outlook.MailItem newMail = application.CreateItem(Outlook.OlItemType.olMailItem) as Outlook.MailItem;
newMail.To = "email#gmail.com";
newMail.CC = Outlook.Account;
newMail.Subject = "Subject Here";
newMail.Attachments.Add(selectedMail, Microsoft.Office.Interop.Outlook.OlAttachmentType.olEmbeddeditem);
newMail.Send();
selectedMail.Delete();
System.Windows.Forms.MessageBox.Show("Message has been sent! You have been CC'd.");
}
catch
{
System.Windows.Forms.MessageBox.Show("You must select a message to report.");
}
}
}
}
First of all, I've noticed the following line of code in the event handler:
Outlook.Application application = new Outlook.Application();
There is no need to create a new Outlook Application instance in the ribbon event handler if you develop VSTO based add-in for Outlook. Instead, you need to use the ThisAddIn.Application property. You can start writing your VSTO Add-in code in the ThisAddIn class. Visual Studio automatically generates this class in the ThisAddIn.vb (in Visual Basic) or ThisAddIn.cs (in C#) code file in your VSTO Add-in project. The Visual Studio Tools for Office runtime automatically instantiates this class for you when the Microsoft Office application loads your VSTO Add-in. To access the object model of the host application, use the Application field of the ThisAddIn class. This field returns an object that represents the current instance of the host application. See Program VSTO Add-ins for more information.
Use the Recipients.Add method to add new recipients to the email. For example, a raw sketch:
var recipient = Item.Recipients.Add(ThisAddIn.Application.GetNameSpace("MAPI").CurrentUser.Address);
recipient.Type = OlMailRecipientType.olCC;

Adding to Outlook Email Recipient using VSTO before sending email

Looking a bit of advise or direction in regards to VSTO Ribbons with Outlook in C#.
So far I’ve built an Outlook 2010 Ribbon (using TabMail), this Ribbon opens a WinForms window which allows my users to select contacts from a Custom Built Address Book from a SQL database, via a DataGridView.
The users basically select from a datagridview who they want to email, which then gets added to a toLine list.
Application app = new Microsoft.Office.Interop.Outlook.Application();
Mail item item = app.CreateItem((OlItemType.olMailItem));
item.To = toLine;
Item.Display();
This.close();
The downside of using this approach is the user has to build their To List before they actually compose their email.
I’m now trying to make use of TabMailNewMessage. This should allow the user to compose their email, then click the Ribbon icon within the new message and add to their To List from there.
I’ve got the icon showing okay in the TabMailNewMessage, and I’ve got it to open a 2nd Win Form [currently as a test].
I’m a little unsure how to add to the To List of an already open existing mailItem.
At present all I have on the 2nd Win Form is a button, can someone explain how I can click that button and simply add someone to the To List [of this already composed email]. (I don’t have any code behind the button click as I’m not sure what to do)
I also need to make sure that it doesn’t send the email, but simply adds the user to the To List.
Currently using Office 2010, and VS 2013 (with C#).
Hopefully I’m making some sense here.
Thanks
EDIT:
Not sure if its a simple as
Application app = Globals.ThisAddIn.Application;
MailItem mi = (Outlook.MailItem)app.ActiveInspector().CurrentItem;
Mi.Recipients.Add(“joe#email.com”);
This.Close();
The MailItem.Recipients.Add method allows creating a new recipient in the Recipients collection. The name of the recipient can be a string representing the display name, the alias, or the full SMTP email address of the recipient.
using System.Runtime.InteropServices;
// ...
private bool AddRecipients(Outlook.MailItem mail)
{
bool retValue = false;
Outlook.Recipients recipients = null;
Outlook.Recipient recipientTo = null;
Outlook.Recipient recipientCC = null;
Outlook.Recipient recipientBCC = null;
try
{
recipients = mail.Recipients;
// first, we remove all the recipients of the e-mail
while(recipients.Count != 0)
{
recipients.Remove(1);
}
// now we add new recipietns to the e-mail
recipientTo = recipients.Add("Eugene Astafiev");
recipientTo.Type = (int)Outlook.OlMailRecipientType.olTo;
recipientCC = recipients.Add("Somebody");
recipientCC.Type = (int)Outlook.OlMailRecipientType.olCC;
recipientBCC = recipients.Add("eugene.astafiev#somedomain.com");
recipientBCC.Type = (int)Outlook.OlMailRecipientType.olBCC;
retValue = recipients.ResolveAll();
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
finally
{
if (recipientBCC != null) Marshal.ReleaseComObject(recipientBCC);
if (recipientCC != null) Marshal.ReleaseComObject(recipientCC);
if (recipientTo != null) Marshal.ReleaseComObject(recipientTo);
if (recipients != null) Marshal.ReleaseComObject(recipients);
}
return retValue;
}
You may find the following articles helpful:
How To: Fill TO,CC and BCC fields in Outlook programmatically
How To: Create and send an Outlook message programmatically
Also, I'd suggest developing an Outlook form region which can be displayed on the same window instead of using a standalone window, see Create Outlook form regions for more information.
Yes, it is as simple as using Application.ActiveInspector.CurrentItem. But you can do better than that - your ribbon button event handler takes IRibbonControl object as a parameter. Cast the IRibbonControl.Context property to Inspector or Explorer (depending on where the button is hosted).
Also keep in mind that in a COM addin there is no reason to create a new instance of the Outlook.Application object (it will be crippled with the security prompts anyway) - use Globals.ThisAddIn.Application

How can I open new mail in outlook with different user?

I have user myuser that logged in in windows and I open the program with otheruser.
I need that then I open new mail in outlook it will open it with myuser. The code that I'm using is:
Outlook.Application App = new Outlook.Application();
Outlook._MailItem MailItem = (Outlook._MailItem)App.CreateItem(Outlook.OlItemType.olMailItem);
MailItem.To = BossName.Text;
MailItem.CC = ClientName.Text;
MailItem.Display(true);
Start your application in the context of the desired user, or
you may use Impersonation:
WindowsIdentity.Impersonate Method
Be sure that outlook doesn't run in your session already. Outlook can only run once in a session - so it's not possible to logon with different Outlook-MAPI-Sessions in one Windows-Session at the same time. You Always have to reopen outlook.
Multible Outlook-Profiles
Another way is to configure multible Outlook profiles and start outlook via .net and pass the Profilename. But this can be a little bit tricky, because you always have to check if outlook isnt already running in a different profilecontext - because the Profile-Parameter will be ignored if outlook has already been opened.
class Sample
{
Outlook.Application GetApplicationObject()
{
Outlook.Application application = null;
// Check whether there is an Outlook process running.
if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
// If so, use the GetActiveObject method to obtain the process and cast it to an Application object. Or close Outlook to open a new instance with a desired profile
application = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
//!! Check if the application is using the right profile - close & reopen if necessary
}
else
{
// If not, create a new instance of Outlook and log on to the default profile.;
application = new Outlook.Application();
Outlook.NameSpace nameSpace = application.GetNamespace("MAPI");
nameSpace.Logon("profilename", "", Missing.Value, Missing.Value);
nameSpace = null;
}
// Return the Outlook Application object.
return application;
}
}
If possible use EWS
Another approach would be to use EWS-API (Exchange WebServices-API) but this presupposes to have an Exchange or Office365 account. And is only usefull if you want to deal with outlook-items in the background (.Display() is not possible)
If you are using an Exchange-Account (Office365) i would prefer to do it that way...
Get started with EWS Managed API client applications

Parse Outlook email in Inbox which belongs to other account

I am trying to create a service which will run as a background service on a server. This service will parse email as soon as it enters the Inbox.
We have one email account abc#organization.com. We are using Outlook to check the emails. It is a service so Outlook won't be running all the time on the server. I want to parse the email automatically for this account. This account is not my email account. I am using Microsoft.Office.Interop.outlook in C# program.
This program is running but it is parsing email from my email inbox. I don't know how to specify specific email to parse the Inbox. Need to know the event which triggers as soon as new mail arrives. My program parsed half the emails from my inbox but after that it is throwing object null reference error.
static void Main(string[] args)
{
Microsoft.Office.Interop.Outlook.Application myApp=new Microsoft.Office.Interop.Outlook.Application();
try
{
String Subject, Body, Createdate, Sender = null;
Microsoft.Office.Interop.Outlook.NameSpace mapinamespace = myApp.GetNamespace("MAPI");
mapinamespace.Logon(null, null,true,true);
Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapinamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
Microsoft.Office.Interop.Outlook.Accounts accounts = myApp.Session.Accounts;
try
{
foreach (Microsoft.Office.Interop.Outlook.Account account in accounts)
{
if (account.SmtpAddress == "abc#organization.com")
{
Console.Write(account);
}
else
{
Console.Write("Not found ---");
}
}
}
catch{
throw new System.Exception(string.Format("No account with amtp:{0} exists!"));}
foreach (object item in myInbox.Items)
{
try
{
var mail = item as MailItem;
if (mail != null)
{
//Creation date
Createdate = mail.CreationTime.ToString();
Console.WriteLine("CreationTime---" + Createdate);
//Grab the senders address
Sender = mail.SenderEmailAddress.ToString();
Console.WriteLine("Sender's E-mail---" + Sender);
//grab the Subject
Subject = mail.Subject.ToString();
Console.WriteLine("Subject--" + Subject);
//Grab the body
Body = mail.Body.ToString();
Console.WriteLine("Body---" + Body);
//Grab the Attachment
}
else
{
Console.Write("Error in mail---");
}
}
catch (System.Runtime.InteropServices.COMException e)
{
Console.Write(e);
}
}
}
catch (System.Runtime.InteropServices.COMException e)
{
Console.Write(e);
}
}
I am trying to create a service which will run as a background service on server.
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.
Anyway, it looks like you are interested in the NewMailEx event of the Application class. Also I'd suggest reading the following series of articles:
Outlook NewMail event unleashed: the challenge (NewMail, NewMailEx, ItemAdd)
Outlook NewMail event: solution options
Outlook NewMail event and Extended MAPI: C# example
Outlook NewMail unleashed: writing a working solution (C# example)

How to Program Outlook 2007 Add-In with Multiple Mailboxes

I'm trying to figure how to write a simple add-in for Excel 2007, but one that only interacts with one of my mailboxes. Currently I have two email addresses coming into my outlook, each in a specific 'mailbox'. I was wondering, how would I specify a NewMail event for a specific mailbox?
Or, perhaps not as clean, but how could I write an if function that specifies which mailbox / email any new item is addressed to...
Hopefully this makes sense. Thanks
To catch new mail event, add this code to addin startup method:
this.Application.NewMailEx +=
new Outlook.ApplicationEvents_11_NewMailExEventHandler(Application_NewMailEx);
Then add method to handle NewMailEx event:
void Application_NewMailEx(string EntryID)
{
// get MailItem for this new mail
Outlook.Explorers explorers = this.Application.Explorers;
Outlook.MailItem newMail =
(Outlook.MailItem)explorers.Application.Session.GetItemFromID(EntryID, System.Reflection.Missing.Value);
// check SendUsingAccount to see if it came in mailbox we are interested in
if (newMail.SendUsingAccount.DisplayName == "your.name#your.domain.com")
{
// do whatever You like
}
}
Add using statement also:
using Outlook = Microsoft.Office.Interop.Outlook;

Categories