I'm attempting to get the email address typed into the To field of a compose mail window.
I try to get the Address property of a Recipient, which according to VS, should give me the email.
I am instead receiving a string that looks like this:
"/c=US/a=att/p=Microsoft/o=Finance/ou=Purchasing/s=Furthur/g=Joe"
How can I get the email address in the recipient field?
My code so far:
List <string> emails = new List<string>();
if (thisMailItem.Recipients.Count > 0)
{
foreach (Recipient rec in thisMailItem.Recipients)
{
emails.Add(rec.Address);
}
}
return emails;
Can you try this ?
emails.Add(rec.AddressEntry.Address);
Reference link
EDIT:
I don't have the right environment to test so I'm just guessing all this, but how about
string email1Address = rec.AddressEntry.GetContact().Email1Address;
or .Email2Adress or .Email3Address
Also there is,
rec.AddressEntry.GetExchangeUser().Address
that you might want to try.
Try this
private string GetSMTPAddressForRecipients(Recipient recip)
{
const string PR_SMTP_ADDRESS =
"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
PropertyAccessor pa = recip.PropertyAccessor;
string smtpAddress = pa.GetProperty(PR_SMTP_ADDRESS).ToString();
return smtpAddress;
}
This is available on MSDN here
I have used the same way to get email addresses in my application and its working.
the AddressEntry also has an SMTPAddress property that exposes the primary smtp adress of the user.
I don't know if this helps or how accurate
it is, a sample
private string GetSmtp(Outlook.MailItem item)
{
try
{
if (item == null || item.Recipients == null || item.Recipients[1] == null) return "";
var outlook = new Outlook.Application();
var session = outlook.GetNamespace("MAPI");
session.Logon("", "", false, false);
var entryId = item.Recipients[1].EntryID;
string address = session.GetAddressEntryFromID(entryId).GetExchangeUser().PrimarySmtpAddress;
if (string.IsNullOrEmpty(address))
{
var rec = item.Recipients[1];
var contact = rec.AddressEntry.GetExchangeUser();
if (contact != null)
address = contact.PrimarySmtpAddress;
}
if (string.IsNullOrEmpty(address))
{
var rec = item.Recipients[1];
var contact = rec.AddressEntry.GetContact();
if (contact != null)
address = contact.Email1Address;
}
return address;
}
finally
{
}
}
Related
I have following requirement :
Allow the user to drag & drop an email from outlook to a datagrid
Prepare a reply mail, and show it so the user can review and send
After sending, also fetch the send mail and put it into the datagrid
The drag/drop I have working
Preparing the replay email and showing it to the user I also have working, with this code :
MailItem mail = GetMailBySubject(dateReceived, subject);
if (mail != null)
{
MailItem mailReply = mail.ReplyAll();
// add text and stuff to mailReply...
mailReply.Display();
}
This will open a window in outlook, as if the user clicked reply in outlook.
Now I am stuck with the 3th requirement,
after the user send the reply email, I need somehow to find this email in outlook to add it to my datagrid.
But I have no clue on how to do that.
All I have is the original mail that is been used to prepare the reply.
Is there a way to find the reply with only this, or is this maybe a complete wrong approach ?
To make it more difficult is that I have to show the reply email NON Modal, so I have no trigger when the user clicked on send in outlook.
for reference, here is the code for GetMailBySubject
private MailItem GetMailBySubject(DateTime dateReceived, string subject)
{
MailItem Result = null;
Microsoft.Office.Interop.Outlook.Application OutlookIns = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace olNamespace = OutlookIns.GetNamespace("MAPI");
MAPIFolder myInbox = olNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Items items = myInbox.Items;
int count = items.Count;
MailItem mail = null;
int i = 1; //DO NOT START ON 0
while ((i < count) && (Result == null))
{
if (items[i] is MailItem)
{
mail = (MailItem)items[i];
if ((mail.ReceivedTime.ToString("yyyyMMdd hh:mm:ss") == dateReceived.ToString("yyyyMMdd hh:mm:ss")) && (mail.Subject == subject))
{
Result = mail;
}
}
i++;
}
return Result;
}
EDIT
I tried this code as suggested, but the Items.ItemAdd event is not firing.
So I must still be doing something wrong but I cant see it
this is my code now
MailItem mail = GetMailBySubject((DateTime)sentOn, msg.Subject);
if (mail != null)
{
MailItem mailReply = mail.ReplyAll();
mailReply.HTMLBody = GetDefaultReplyText() + Environment.NewLine + mailReply.HTMLBody;
Guid guid = Guid.NewGuid();
UserProperties mailUserProperties = null;
UserProperty mailUserProperty = null;
mailUserProperties = mailReply.UserProperties;
mailUserProperty = mailUserProperties.Add("myproperty", OlUserPropertyType.olText);
mailUserProperty.Value = guid.ToString(); ;
// the code below gives error "The property cannot be parsed or has an invalid format"
//mailReply.PropertyAccessor.SetProperty("myproperty", guid.ToString());
mailReply.Display();
}
private MailItem GetMailBySubject(DateTime dateReceived, string subject)
{
MailItem Result = null;
Microsoft.Office.Interop.Outlook.Application OutlookIns = new Microsoft.Office.Interop.Outlook.Application();
Microsoft.Office.Interop.Outlook.NameSpace olNamespace = OutlookIns.GetNamespace("MAPI");
MAPIFolder myInbox = olNamespace.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
Items items = myInbox.Items;
int count = items.Count;
MailItem mail = null;
int i = 1; //DO NOT START ON 0
while ((i < count) && (Result == null))
{
if (items[i] is MailItem)
{
mail = (MailItem)items[i];
if ((mail.ReceivedTime.ToString("yyyyMMdd hh:mm:ss") == dateReceived.ToString("yyyyMMdd hh:mm:ss")) && (mail.Subject == subject))
{
Result = mail;
MAPIFolder mySent = olNamespace.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
mySent.Items.ItemAdd += Items_SentMailItemAdd;
}
}
i++;
}
return Result;
}
and finally
private void Items_SentMailItemAdd(object Item)
{
//throw new NotImplementedException();
; // this event is never fired
}
You can use the Items.ItemAdd event on the Sent Items folder. To check if that is your message, set a custom property on the message that you create and display. You can use MailItem.UserProperties.Add, but that can force the message to be sent in the TNEF format. To prevent that from happening, you can use MailItem.PropertyAccessro.SetProperty to set a named MAPI property without using the UserProperties collection. You can set a test user property and look at its DASL name (to be used by SetProperty) with OutlookSpy (I am its author - select the message, click IMessage button, select your custom property, see the DASL edit box).
I'm trying to get the e-mail adresses of all user's in our company domain.
99% work but sometimes there is y NullReferenceException in my Output.
Code:
string dom = "mydomain";
System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry("LDAP://" + dom); //domain, user, password
System.DirectoryServices.DirectorySearcher ds = new System.DirectoryServices.DirectorySearcher(entry);
ds.Filter = ("(objectClass=User)");
int count = 1;
foreach (System.DirectoryServices.SearchResult resEnt in ds.FindAll())
{
try
{
System.DirectoryServices.DirectoryEntry de = resEnt.GetDirectoryEntry();
String email = de.Properties["mail"].Value.ToString();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
There might be a NullReferenceException in the line
String email = de.Properties["mail"].Value.ToString();
If in the Properties["mail"] returns a null value or its Value property is null, then the attempt to call ToString() will lead to an exception.
This will help in this case (C# 6 syntax)
String email = de.Properties["mail"]?.Value?.ToString();
or
String email = null;
if (de.Properties["mail"] != null && de.Properties["mail"].Value != null)
{
email = de.Properties["mail"].Value.ToString();
}
I have in my Outlook 2010-Add-In (c#) many folders. They are in my private post box or in one of my shared post boxes.
Now I am looking for a solution to find out, how to get the right email address (sender / recipient) associated with a dedicated folder. It could be any folder from my private or anyone of my shared post boxes.
I think, maybe I could use the EntryId / StoreId from the folder item to identify the corresponding email address.
I know already, that I could get the email address from any mail item but I'm not looking for this solution.
I like to answer my own questions: I think that I've found a plausible solution.
I do not treat any exceptions inside the function, I do that from outside.
private string GetSMTPAddressByFolderItem(Outlook.MAPIFolder mapiFolder)
{
string PR_MAILBOX_OWNER_ENTRYID = #"http://schemas.microsoft.com/mapi/proptag/0x661B0102";
string PR_SMTP_ADDRESS = #"http://schemas.microsoft.com/mapi/proptag/0x39FE001E";
Outlook.Store store = null;
Outlook.NameSpace ns = null;
Outlook.AddressEntry sender = null;
Outlook._ExchangeUser exchUser = null;
try
{
if (mapiFolder == null)
{
return null;
}
// Get the parent store.
store = mapiFolder.Store;
string storeOwnerEntryId = store.PropertyAccessor.BinaryToString(store.PropertyAccessor.GetProperty(PR_MAILBOX_OWNER_ENTRYID)) as string;
ns = Application.GetNamespace(Constants.OL_NAMESPACE); // i.e. "MAPI"
sender = ns.GetAddressEntryFromID(storeOwnerEntryId);
if (sender != null)
{
if (sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeUserAddressEntry ||
sender.AddressEntryUserType == Outlook.OlAddressEntryUserType.olExchangeRemoteUserAddressEntry)
{
exchUser = sender.GetExchangeUser();
if (exchUser != null)
{
return exchUser.PrimarySmtpAddress;
}
else
{
return null;
}
}
else
{
return sender.PropertyAccessor.GetProperty(PR_SMTP_ADDRESS) as string;
}
}
return null;
}
finally
{
if (ns != null)
{
Marshal.ReleaseComObject(ns);
ns = null;
}
if (store != null)
{
Marshal.ReleaseComObject(store);
store = null;
}
if (sender != null)
{
Marshal.ReleaseComObject(sender);
sender = null;
}
if (exchUser != null)
{
Marshal.ReleaseComObject(exchUser);
exchUser = null;
}
}
}
I'm totally new to the asp.net mvc stack and i was wondering what happened to the Request.Header object?
Basically what I want to do is to pull out the Device(PC) IP address, but I fail to retrieve the desired output. I also tried Request.ServerVariables object but result always remain NULL.
I am using asp.net MVC. is there any change in this function required:
public static string GetIP()
{
string functionReturnValue = null;
//Gets IP of actual device versus the proxy (WAP Gateway)
functionReturnValue = HttpContext.Current.Request.Headers["X-FORWARDED-FOR"]; //functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
functionReturnValue = HttpContext.Current.Request.Headers["X-Forwarded-For"];//functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
// GetIP = Context.Request.ServerVariables("REMOTE_ADDR")
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
functionReturnValue = HttpContext.Current.Request.Headers["X-CLIENT-IP"];//functionReturnValue = null
if (string.IsNullOrEmpty(functionReturnValue))
{
//If not using a proxy then get the device IP
functionReturnValue = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];//functionReturnValue = "::1"
}
}
}
}
System.Text.RegularExpressions.Regex regex = new System.Text.RegularExpressions.Regex("(\\d{1,3}\\.){3}\\d{0,3}");
if (functionReturnValue != null)
{
if (regex.IsMatch(functionReturnValue))
{
functionReturnValue = regex.Match(functionReturnValue).Value.ToString();
}
else
{
functionReturnValue = "";
}
regex = null;
}
if (functionReturnValue == null)
{
return "";
}
else
{
return functionReturnValue;
}
}
In X-Forwarded-For you will get client ip,proxy1 & proxy2. By taking first item you will get client/user ip.
HttpContext.Current.Request.Headers["X-Forwarded-For"].Split(new char[] { ',' }).FirstOrDefault()
Hope it helps!
I need to extract/export the lotus notes email attachment into file system. for that I wrote following method but each time I am receiving an error at line foreach (NotesItem nItem in items).. Can anybody please tell me what I am doing wrong ..
Thanks
Jwalin
public void GetAttachments()
{
NotesSession session = new NotesSession();
//NotesDocument notesDoc = new NotesDocument();
session.Initialize("");
NotesDatabase NotesDb = session.GetDatabase("", "C:\\temps\\lotus\\sss11.nsf", false); //Open Notes Database
NotesView inbox = NotesDb.GetView("By _Author");
NotesDocument docInbox = inbox.GetFirstDocument();
object[] items = (object[])docInbox.Items;
**foreach (NotesItem nItem in items)**
{
//NotesItem nItem = (NotesItem)o1;
if (nItem.Name == "$FILE")
{
NotesItem file = docInbox.GetFirstItem("$File");
string fileName = ((object[])nItem.Values)[0].ToString();
NotesEmbeddedObject attachfile = (NotesEmbeddedObject)docInbox.GetAttachment(fileName);
if (attachfile != null)
{
attachfile.ExtractFile("C:\\temps\\export\\" + fileName);
}
}
}
You don't need to use the $File item to get the attachment name(s). Rather, you can use the HasEmbedded and EmbeddedObject properties of the NotesDocument class.
public void GetAttachments()
{
NotesSession session = new NotesSession();
//NotesDocument notesDoc = new NotesDocument();
session.Initialize("");
NotesDatabase NotesDb = session.GetDatabase("", "C:\\temps\\lotus\\sss11.nsf", false); //Open Notes Database
NotesView inbox = NotesDb.GetView("By _Author");
NotesDocument docInbox = inbox.GetFirstDocument();
// Check if any attachments
if (docInbox.hasEmbedded)
{
NotesEmbeddedObject attachfile = (NotesEmbeddedObject)docInbox.embeddedObjects[0];
if (attachfile != null)
{
attachfile.ExtractFile("C:\\temps\\export\\" + attachfile.name);
}
}
Ed's solution didn't work for me. Something about my Notes db design seems to have left the EmbeddedObjects property null even when the HasEmbedded flag is true. So I sort of combined the Ed's and Jwalin's solutions, modifying them to fetch all attachments from a Notes document.
NotesDocument doc = viewItems.GetNthEntry(rowCount).Document;
if (doc.HasEmbedded)
{
object[] items = (object[])doc.Items;
foreach (NotesItem item in items)
{
if(item.Name.Equals("$FILE"))
{
object[] values = (object[])item.Values;
doc.GetAttachment(values[0].ToString()).ExtractFile(fileSavePath + values[0].ToString());
}
}