I am using visual studio 2017 installed office development pack,want to create a plugin which responds based on incoming email.
Basically I am tying to monitor an Infra support mailbox ,which forwards the email to concerned team based on the incoming message content.
Any suggestion on how this can be done
There are several ways for implementing the required functionality:
Use rules for setting up forward rules. You can do that manually in Outlook and programmatically as well. The Outlook object model provides all the required classes for that, see How to: Create a Rule to Assign Categories to Mail Items Based on Multiple Words in the Subject for more information.
Use the NewMailEx event for handling incoming emails. The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. You can use the Entry ID represented by the EntryIDCollection parameter passed to call the NameSpace.GetItemFromID method and process the item. In the event handler, you may check the email received and forward the email programmatically. The Forward method of the MailItem class executes the Forward action for an item and returns the resulting copy as a MailItem object.
Sub RemoveAttachmentBeforeForwarding()
Dim myinspector As Outlook.Inspector
Dim myItem As Outlook.MailItem
Dim myattachments As Outlook.Attachments
Set myinspector = Application.ActiveInspector
If Not TypeName(myinspector) = "Nothing" Then
Set myItem = myinspector.CurrentItem.Forward
Set myattachments = myItem.Attachments
While myattachments.Count > 0
myattachments.Remove 1
Wend
myItem.Display
myItem.Recipients.Add "Dan Wilson"
myItem.Send
Else
MsgBox "There is no active inspector."
End If
End Sub
You may find the How To: Respond to an Outlook email programmatically article helpful.
This code using a event to incoming mails to the default inbox
using Outlook = Microsoft.Office.Interop.Outlook;
public partial class ThisAddIn
{
Outlook.NameSpace outlookNameSpace;
Outlook.MAPIFolder inbox;
Outlook.Items items;
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
outlookNameSpace = this.Application.GetNamespace("MAPI");
inbox = outlookNameSpace.GetDefaultFolder(
Microsoft.Office.Interop.Outlook.
OlDefaultFolders.olFolderInbox);
items = inbox.Items;
items.ItemAdd +=
new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);
}
void items_ItemAdd(object Item)
{
Outlook.MailItem mail = (Outlook.MailItem)Item;
if (Item != null)
{
Outlook.MailItem replyMail = mail.Reply();
//Do your response
mail.Send();
}
}
}
Related
Based on some condition, I am trying to copy a new email(only in inbox) to another folder. The folder is at same level as other default folders like Inbox, Outbox, Drafts.
Below is my code:
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
Debug.WriteLine(ThisAddIn.isAddInOn);
outlookNameSpace = this.Application.GetNamespace("MAPI");
inbox = outlookNameSpace.GetDefaultFolder(
Microsoft.Office.Interop.Outlook.
OlDefaultFolders.olFolderInbox);
items = inbox.Items;
items.ItemAdd += new Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd);
}
Below is code for items_ItemAdd:
void items_ItemAdd(object Item)
{
Outlook.MailItem mail = (Outlook.MailItem)Item;
Debug.WriteLine("mail");
Debug.WriteLine(mail == null);
if (mail!= null)
{#code to move mail to particular folder}
I have not written full code of the function. Because this function is not my problem.
My issue is items_ItemAdd is called multiple times. For example:
When a new email will come
When a email will be moved to a another folder.
I don't want EventHandler to get invoked on the above second example. And when it is invoked second time, function items_ItemAdd receives and empty mail object. So I get below exception:
Exception thrown:
'System.Runtime.InteropServices.COMException' in OutlookAddIn2.dll
System.Runtime.InteropServices.COMException (0xBDD40107): The operation failed.
at Microsoft.Office.Interop.Outlook._MailItem.get_Body()
at OutlookAddIn2.ThisAddIn.items_ItemAdd(Object Item)
is this
inbox = outlookNameSpace.GetDefaultFolder(
Microsoft.Office.Interop.Outlook.
OlDefaultFolders.olFolderInbox);
pointing to all the folders?
I'm programming an outlook add-in.
I want to modify the mail before it gets sent. Therefore I have registered me for an event before the email gets sent. I can modify it but when I m trying to change the recipient of the mail (so mail.To) it gives me an error (not while my code is running but when outlook tries to sent the mail).
Error says: '...Can not resolve the receivername' (i have translated it so it is not the real error text but close to it)
Here is my code:
void Application_ItemSend(object item, ref bool cancel)
{
if (item is Outlook.MailItem mail)
{
var to = mail.To;
var body = mail.Body;
var editedBody = to + "#" + body;
mail.Body = editedBody;
mail.To = #"<another email>";
}
}
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
//Register the new event
Globals.ThisAddIn.Application.ItemSend += Application_ItemSend;
}
You are resetting all To recipients. Is that what you really want to do? Try to use MailItem.Recipients.Add (retuns Recipient object) followed by Recipient.Resolve.
You are also setting the plain text Body property wiping out all formatting. Consider using HTMLBody instead, just keep in mind that two HTML strings must be merged rather than concatenated to produce valid HTML.
You need to cancel the action by setting the cancel parameter to true and schedule re-sending operation with a new email address. A timer which fires the Tick event on the main thread can help with that task.
Also you may consider making a copy of the email, changing recipients (do any changes on the copy) and submit it. In that case you will have to differentiate such messages and skip them in the ItemSend event handler. To get that working you may use UserProperties.
Got it working:
var to = string.Empty;
mail.Recipients.ResolveAll();
foreach (Outlook.Recipient r in mail.Recipients)
{
to += r.Address + ";";
}
if (to.Length > 0)
to = to.Substring(0, to.Length - 1);
mail.Body = to + "#" + mail.Body;
//Modify receiver
mail.To = string.Empty;
Outlook.Recipient recipient = mail.Recipients.Add("<email>");
recipient.Resolve();
I want to forward an existing Email from my Outlook inbox folder. On recent research I found some different solutions:
get the current mail item and copy it to a new message
move method to move in a different folder
forward method...
My goal is to find a simple way to forward an existing Email to another E-Mail adress.
My code enclosed does not have access to send!
private void buttonExplorer_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Interop.Outlook.Selection mySelection = Globals.ThisAddIn.Application.ActiveExplorer().Selection;
Microsoft.Office.Interop.Outlook.MailItem mailItem = null;
foreach (Object obj in mySelection)
{
if (obj is Microsoft.Office.Interop.Outlook.MailItem)
{
mailItem = (Microsoft.Office.Interop.Outlook.MailItem)obj;
mailItem.Forward();
mailItem.Recipients.Add("test#web.com");
mailItem.Send();
}
}
}
Would be nice if there is a simple way to solve the forwarding event issue.
Forward() creates a new item, as stated here.
So you'll need to use that new item from then on:
var newItem = mailItem.Forward();
newItem.Recipients.Add("to.alt#web.de");
newItem.Send();
Try using Microsoft Exchange Web Service (EWS) to forward the email messages. EWS provides api for the commonly used events.
A sample code would like this,
// Connect to Exchange Web Services as user1 at contoso.com.
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("user1#contoso.com", "password ");
service.AutodiscoverUrl("user1#contoso.com");
// Create the e-mail message, set its properties, and send it to user2#contoso.com, saving a copy to the Sent Items folder.
EmailMessage message = new EmailMessage(service);
message.Subject = "Interesting";
message.Body = "The proposition has been considered.";
message.ToRecipients.Add("user2#contoso.com");
message.SendAndSaveCopy();
For more info, refer https://msdn.microsoft.com/en-us/library/office/dd633681(v=exchg.80).aspx
I have written code for outllok addon such that when ever email arrives in inbox it should download , but the curret code is such that if it arrives into specific folder also it not getting get downloaded. Can some one guide me on this?
private void ThisApplication_NewMail()
{
const string destinationDirectory = #"C:\TestFileSave";
if (!Directory.Exists(destinationDirectory))
{
Directory.CreateDirectory(destinationDirectory);
}
MAPIFolder sentMail = Application.ActiveExplorer().Session.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
Items sentMailItems = sentMail.Items;
try
{
foreach (object collectionItem in sentMailItems)
{
MailItem newEmail = collectionItem as MailItem;
if (newEmail == null) continue;
if (newEmail.Attachments.Count > 0)
{
for (int i = 1; i <= newEmail.Attachments.Count; i++)
{
if (newEmail.Attachments[i].FileName.Contains("Logic"))
{
string filePath = Path.Combine(destinationDirectory, newEmail.Attachments[i].FileName);
newEmail.Attachments[i].SaveAsFile(filePath);
}
}
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex);
}
You can handle the NewMailEx event to get notified when a new mail arrives. Then you can get an instace of the just arrived item using the EntryID value passed to the NewMailEx event handler. The GetItemFromID method of the Namespace class returns a Microsoft Outlook item identified by the specified entry ID (if valid).
Also you may consider handling the ItemAdd event of the Items class. It is fired when one or more items are added to the specified collection. Be aware, this event does not run when a large number of items are added to the folder at once.
You can read more about that in the 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)
The MarkForDownload property of Outlook items returns an OlRemoteStatus constant that determines the status of an item once it is received by a remote user. For example, the following example searches through the user's Inbox for items that have not yet been fully downloaded. If any items are found that are not fully downloaded, a message is displayed and the item is marked for download.
Sub DownloadItems()
Dim mpfInbox As Outlook.Folder
Dim obj As Object
Dim i As Integer
Set mpfInbox = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
'Loop all items in the Inbox folder
For i = 1 To mpfInbox.Items.Count
Set obj = mpfInbox.Items.Item(i)
'Verify if the state of the item is olHeaderOnly
If obj.DownloadState = olHeaderOnly Then
MsgBox ("This item has not been fully downloaded.")
'Mark the item to be downloaded.
obj.MarkForDownload = olMarkedForDownload
End If
Next
End Sub
Finally, you can use the Start method of the SyncObject class to begin synchronizing a user's folders using the specified Send\Receive group.
Public Sub Sync()
Dim nsp As Outlook.NameSpace
Dim sycs As Outlook.SyncObjects
Dim syc As Outlook.SyncObject
Dim i As Integer
Dim strPrompt As Integer
Set nsp = Application.GetNamespace("MAPI")
Set sycs = nsp.SyncObjects
For i = 1 To sycs.Count
Set syc = sycs.Item(i)
strPrompt = MsgBox( _
"Do you wish to synchronize " & syc.Name &"?", vbYesNo)
If strPrompt = vbYes Then
syc.Start
End If
Next
End Sub
I am setting the property (for making them As Read and with High Importance) of the mail those are coming to the MS Outlook 2010 inbox using below code -
Microsoft.Office.Interop.Outlook.Application myApp = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace mapiNameSpace = myApp.GetNamespace("MAPI");
Microsoft.Office.Interop.Outlook.MAPIFolder myInbox = mapiNameSpace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderInbox);
int i = myInbox.Items.Count;
((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i]).UnRead = false;
((Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i]).Importance = OlImportance.olImportanceHigh;
This works fine when only one mail comes at a time (I can see the mail as Read and with High Importance) after the code execution but when three or four mails coming at a time then it set the property of only one mail not for all the three or four mails.
Please suggest.
Remember to save the message after setting any property.
Most importantly, your code uses multiple dot notation - for each ".", you get back a brand new COM object, so you end up setting Importance property on an object different from the one used to set the UnRead property.
int i = myInbox.Items.Count;
MailItem msg = (Microsoft.Office.Interop.Outlook.MailItem)myInbox.Items[i];
msg.UnRead = false;
msg.Importance = OlImportance.
msg.Save();
Another problem is that you assume that the last item in the Items collection is the latest one. This is not generally true. As cremor suggested, use Items.ItemAdd event, but still do not forget to save the message.
You can use the ItemAdd event of the Items property of the folder:
Items inboxItems = myInbox.Items;
inboxItems.ItemAdd += HandleItemAdded;
private void HandleItemAdded(object item)
{
MailItem mail = item as MailItem;
if (mail == null) { return; }
mail.UnRead = false;
mail.Importance = OlImportance.olImportanceHigh;
}