|
Above is what I have for the above code to send an email. And it works fine, but how can you grab the current logged on users email address to put into the from field. Right now I know you can hardcode it in, or as I have it now I put it in the app.config. But you do not know who will use this application nor their email address to hard code it in.
|
But I want to do is deploy an application with the email code in it and it automatically gets the current users email address and puts it into the "From" part of the email. The recipient will always be the same so no need to set anything up for that.
Roei BarPosted Sep 24, 2009, 3:40 PM
string userName = Environment.UserName;
string domainName = Environment.UserDomainName;
//Set the correct format for the AD query and filter
string ldapQueryFormat = @"LDAP://{0}.com/DC={0},DC=com";
string queryFilterFormat = @"(&(samAccountName={0})(objectCategory=person)(objectClass=user))";
SearchResult result = null;
using(DirectoryEntry root = newDirectoryEntry(rootQuery))
{
using(DirectorySearcher searcher = new DirectorySearcher(root))
{
searcher.Filter = searchFilter;
SearchResultCollection results = searcher.FindAll();
result = (results.Count != 0) ? results[0] : null;
}
}
string primaryEmail = result.Properties["mail"][0] as string;
StringCollection emails = new StringCollection();
try
{
foreach(string proxyAddr in dirResult.Properties["proxyaddresses"])
{
//Make it 'case-insensative'
if(proxyAddr.ToLower().StartsWith("smtp:"))
//Get the email string from AD
email.Add(proxyAddr.Substring(5));
}
}
//Do nothing for any errors, make the collection null
catch
{
emails = null;
}
Nir BarPosted Sep 24, 2009, 3:34 PM
Then you should use Microsoft.Office.Interop.Outlook
I haven't used it myself (though I've used Word's and Excel's Primary Interop Assemblies)
At a first glance I think you should use MailItem interface
Prepare yourself for some digging in documentation...
Perhaps you'll be able to find a sample code which will make it easier...
Please mark this post as an anser if it helps you
Nir
Anthony LinhardtPosted Sep 24, 2009, 3:10 PM
thanks.
Nir BarPosted Sep 24, 2009, 2:54 PM
You can't get the email address of the user because it isn't stored anywhere
If there's outlook installed and configured (not trivial) then you may be able to get it using Primary Interop Assemblied, which is quite hard to do, and also it isn't trivial that these assemblies are installed on your user's computer (it isn't automaticaly installed with the .NET framework)
Also it might be that the user is using a browser based email account, or a different application (such as thunderbird)
All in all - I think you should ask the user to enter his/hers email address
Please mark this post as an answer if it helps you
Nir