Outlook.ItemsEvents_ItemAddEventHandler(items_ItemAdd) invoking on all folders - c#

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?

Related

Outlook C# move an email into a mailbox associated with a MS365 Group

I am writing a C# VSTO addin to provide some email filing helper functions. I am stuck as to how can programmatically move an email I have received into the conversations mailbox associated with an MS365 Group. The group itself is created as part of a sharepoint modern team site.
I can manually drag emails over to the group mailbox, but I cannot find a way to obtain the folder object in C#.
Microsoft® Outlook® for Microsoft 365 MSO (Version 2111 Build 16.0.14701.20254) 64-bit.
You can use the Move method of Outlook items.
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
this.Application.NewMail += new Microsoft.Office.Interop.Outlook.
ApplicationEvents_11_NewMailEventHandler
(ThisAddIn_NewMail);
}
private void ThisAddIn_NewMail()
{
Outlook.MAPIFolder inBox = (Outlook.MAPIFolder)this.Application.
ActiveExplorer().Session.GetDefaultFolder
(Outlook.OlDefaultFolders.olFolderInbox);
Outlook.Items items = (Outlook.Items)inBox.Items;
Outlook.MailItem moveMail = null;
items.Restrict("[UnRead] = true");
Outlook.MAPIFolder destFolder = inBox.Folders["Test"];
foreach (object eMail in items)
{
try
{
moveMail = eMail as Outlook.MailItem;
if (moveMail != null)
{
string titleSubject = (string)moveMail.Subject;
if (titleSubject.IndexOf("Test") > 0)
{
moveMail.Move(destFolder);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
I suppose the destination folder is listed in Outlook in an additional store. So, you can use the Stores property of the Namespace class to find the target folder.

Outlook VSTO Add-In: Can not resolve recipientname

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();

How to auto respond to email in outlook C# Code

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();
}
}
}

Microsoft Office Interop Outlook w/ C# - Why does Items.GetNext() return null?

I'm trying to fetch attachments from a particular folder in Outlook 2010 in a C# Windows Forms app. I have a class called MailInbox that contains the Outlook namespace, inbox, and message objects.
Here is the code for that class and its methods:
public class mailInbox
{
//declare needed variables for outlook office interop
public Outlook.Application oApp = new Outlook.Application();
//public Outlook.MAPIFolder oInbox;
public Outlook.MAPIFolder idFolder;
public Outlook.NameSpace oNS;
public Outlook.Items oItems;
public Outlook.MailItem oMsg;
public Outlook.MAPIFolder subFolder;
public string subFolderName;
public mailInbox()
{
//read the subfoldername from a text file
using (StreamReader subFolderNameRead = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\SuperVerify\config\subfoldername.txt"))
{
subFolderName = subFolderNameRead.ReadLine().Trim();
}
oNS = oApp.GetNamespace("mapi");
//oInbox = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox);
idFolder = oNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox).Folders[subFolderName]; // use the subFolderName string, read from the config text file, to get the folder from outlook
oItems = idFolder.Items;
//oMsg = (Outlook.MailItem)oItems.GetNext();
}
public void FetchEmail() // fetches the next email in the inbox and saves the attachments to the superverify folder
{
oNS.Logon(Missing.Value, Missing.Value, false, true); //login using default profile. This might need to be changed.
oMsg = (Outlook.MailItem) oItems.GetNext(); //fetch the next mail item in the inbox
if(oMsg.Attachments.Count > 0) // make sure message contains attachments **This is where the error occurs**
{
for (int i =0; i< oMsg.Attachments.Count; i++)
{
oMsg.Attachments[i].SaveAsFile(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\SuperVerify\images\" + oMsg.Attachments[i].FileName); //save each attachment to the specified folder
}
} else //if no attachments, display error
{
MessageBox.Show("The inbox folder has no messages.", "TB ID Verification Tool", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
public void changeSubFolderName(string newSubFolderName)
{
subFolderName = newSubFolderName;
}
}
When I click the button that invokes the FetchEmail method, I get the error
System.NullReferenceException: 'Object reference not set to an instance of an object.'
oMsg was null. I thought that
public Outlook.MailItem oMsg;
instantiated the object and that
oMsg = (Outlook.MailItem) oItems.GetNext();
assigned it an Outlook MailItem, but it seems I don't understand what's going on here.
From the documentation which curiously references VB.NET's Nothing instead of null,
It returns Nothing if no next object exists, for example, if already positioned at the end of the collection.To ensure correct operation of the GetFirst, GetLast, GetNext, and GetPrevious methods in a large collection, call GetFirst before calling GetNext on that collection, and call GetLast before calling GetPrevious. To ensure that you are always making the calls on the same collection, create an explicit variable that refers to that collection before entering the loop.
So GetNext will return null if you're at the end of the folder. You'd have to check it for null before attempting to use it.
You can also use oItems.Count to determine that there are no items when you initially access the folder's items. But if Count is one or more you'd still have to check for null, because you're dealing with a collection that can change. Hypothetically someone could remove items from the folder while you're reading it, so you can't get the count up front and then rely on it.

Aenetmail office 365 move message

I'm using AENetMail imap library with an office 365 account. I have a big problem, I can't move messages to another folder without duplicate it. I can move the message to the another folder, but I have to delete it from its original location (or delete the original flag).
private void button1_Click(object sender, EventArgs e)
{
using (ImapClient ic = new ImapClient("imap server name", "username", "pass", ImapClient.AuthMethods.Login, 993,true))
{
ic.SelectMailbox("INBOX/Teszt");
Lazy<MailMessage>[] messages = ic.SearchMessages(SearchCondition.Unseen(), false);
foreach (Lazy<MailMessage> message in messages)
{
MailMessage m = message.Value;
ic.MoveMessage(m.Uid, "probamappa");
ic.DeleteMessage(m.Uid);
}
}
}
How can I delete the message from the original folder?

Categories

Resources