AD Email Address is inaccessible in ASP.NET website on Server ONLY - asp.net

I currently have an intranet website set up using IIS. It uses Windows authentication. It looks to Active Directory to get a user's email address through the following two lines of code :
Dim userStr, userEmail As String
userStr = Page.User.Identity.Name.ToString
userEmail = System.DirectoryServices.AccountManagement.UserPrincipal.Current.EmailAddress
Then, this email is used to send an email via SMTP client. My problem is that, when my website is hosted on our server, the email address seems to be inaccessible. This code works perfectly on my localhost. I have my page set up to show the email address once it is accessed, and it just remains blank on the server.
Can anyone tell me what could be going on? It also seems that some of my events are not firing, but I think that is due to the empty email address.
Thank you

I ended up using the following code, which works:
Dim userStr, userEmail As String
userStr = Page.User.Identity.Name.ToString
Using HostingEnvironment.Impersonate()
Dim ctx As PrincipalContext = New PrincipalContext(ContextType.Domain)
Dim xUser As UserPrincipal = UserPrincipal.FindByIdentity(ctx, userStr)
userEmail = xUser.EmailAddress
End Using
It turns out the the code in the original question was trying to return the email address for the identity I am using in IIS. By using this code instead, I am able to return the current user's email address.

Related

CDO.Message To and From Fields Changed to "Friendly Name" and Email Address

When I first created this Classic ASP script, with the help of W3Schools, to send email, it worked fine. Now I'm having issues with sending the actual email; it appears to hang on the .Send method.
I noticed that when I set the To and From email address to just the email address, it reformats it to a "Friendly Name"/Email Address format:
myMail.From="Support#myDomain.com"
Response.Write myMail.From
The output of the Response Write is:
"Support#myDomain.com" <Support#myDomain.com>
I don't know if this was happening before, or if I should be setting the To and From fields in this format. Just to check if this is causing my problem, is there anyway to prevent these fields from being changed from just the email address?
Maybe the e-mail sending from the server now needs some kind of authentication such as setting these fields:
' Outgoing SMTP server.
objCDO.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.mydomain.com"
objCDO.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objCDO.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objCDO.Configuration.Fields("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60
' Type of authentication, 0=NONE, 1-Basic (Base64 encoded), and 2=NTLM.
objCDO.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
' UserID on the SMTP server
objCDO.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "support#mydomain.com"
' Password on the SMTP server
objCDO.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "myemailpassword"
' Update config.
objCDO.Configuration.Fields.Update
The issue stemmed from the fact that the "From" email address was actually a distribution list and the account credentials used to login to the email server were not authorized to "Send As". Once that was rectified emails sent without further problems.
Thanks for the response.

Classic ASP - Sending Email To Own Domain with CDOSYS fails

I have a classic asp email script that uses authenticated CDOSYS to send to emails from a database. It's running on a Parallels Plesk Windows 2008 server.
This works fine for all email addresses except for any addresses that belong to sites on the server I am sending from.
I could authenticate using a Google Apps email account (the domain is set up using Google Apps for email) BUT I would run up against Google' 24 hour sending limits each time the client ran the script.
Can anyone point out where I'm going wrong or explain why email to sites on the sending server causes an error? The error is
error '8004020f'
/admin/send-group-email.asp, line 128
which is the objCDO.Send line
The Code :
(primarydomain.com is the domain name of the primary account the site lives under in Parallels. The SenderEmail value would be, for example, id#secondarydomain.com)
Set cdoConfig = CreateObject("CDO.Configuration")
With cdoConfig.Fields
.Item(cdoSendUsingMethod) = cdoSendUsingPort
.Item(cdoSMTPServer) = "localhost"
.Item(cdoSMTPAuthenticate) = 1
.Item(cdoSendUsername) = "authenticate#primarydomain.com"
.Item(cdoSendPassword) = "thepassword"
.Update
End With
while (NOT RS_Emails.EOF)
Dim objCDO
set objCDO = Server.CreateObject("CDO.Message")
objCDO.Configuration = cdoConfig
objCDO.From = CStr(Request.Form("SenderEmail")) & " (" & CStr(Request.Form("SenderName")) & ")"
objCDO.To = RS_Emails.Fields.Item("email").Value
objCDO.Subject = CStr(Request.Form("Subject"))
objCDO.HTMLBody = message
objCDO.Send
set objCDO = Nothing
RS_Emails.MoveNext
Wend
set cdoConfig=Nothing
This is most likely a server issues which can be solved with Plesk.
Please look at the following link:
http://mkb-training.com/index.php?option=com_content&view=article&id=1:setting-up-google-apps-with-plesk&catid=1:google-tutorial&Itemid=2
Pay attention to the following:
"Uncheck the MX1: "Domain IP also used for mail server"" (there are screenshots there on how to do this). I am not 100% sure about Plesk, but in H-Sphere (another Parallels control panel) doing this is essential for being able to send from the server to your own domain when you have a remote mail exchanger.
Also make sure that no MX records point to your server (even if the Google Apps ones are configured correctly).

Email goes to spam instead of inbox

We have a domain name "www.mycloudcctv.com" at godaddy.com and we have created a sub domain cam.mycloudcctv.com which points to 212.78.237.157
We have an application running on third party server (212.78.237.157). This application wants to send an email on our behalf using the email address “alerts# mycloudcctv.com ". Following code snippet (ASP.NET) is being used to send the email from (212.78.237.157)
var mailClient = new SmtpClient();
mailClient.Credentials = new NetworkCredential { UserName = "alerts#mycloudcctv.com", Password = "xyz" };
mailClient.Port = 25;
mailClient.Host = "smtpout.secureserver.net";
mailClient.EnableSsl = false;
var mail = new MailMessage("alerts#mycloudcctv.com", "azharmalik3#hotmail.com", "Test Smtp server", "Testing mycloudcctv server") { IsBodyHtml = true };
//Now Send the message
mailClient.Send(mail);
Everything works fine and emails are being sent however they end up in SPAM/JUNK folders of gmail/hotmail/yahoo. Could you please provide us necessary information so that our emails go to inbox instead of spam folders?
this is a BIG question with lots of complex issues, but it really boils down to three main areas:
Does the email come from a server which has be delegated the authority to deliver emails for the specified domain?
Is the content of the email just hyperlinks and does it contain text which would trigger spam assassin to mark as spam.
Is your server blacklisted for spam
For point 1 look into how to setup SPF records for send authority. http://www.mydigitallife.info/how-to-set-up-and-create-sender-policy-framework-spf-domain-dns-txt-record-with-wizard/
For point 2 get a copy of spam assassin and run your emails through it to see the score.
http://spamassassin.apache.org/
For point 3 http://whatismyipaddress.com/blacklist-check
This is not that easy. There are fair few things you have to do. For example SendGrid has some guidelines:
http://support.sendgrid.com/entries/21194967-deliverability-101
I found this blog-posting extremely useful! Give it a good read, it covers a lot of the points already mentioned here thus far:
http://www.codinghorror.com/blog/2010/04/so-youd-like-to-send-some-email-through-code.html

How to pass HostingEnvironment.Impersonate credentials to ExchangeService EWS?

Is it possible to pass the credentials of the user browsing my asp.net web application to the EWS FindAppointments call?
I'm only trying to return calendar details for the active browsing user, who will without doubt have permission to read their own calendar, so the issue should not relate to Exchange impersonation with the EWS api discussed here.
The code below works just fine when running localhost, but running from the web server, despite Windows Authentication and Identity Impersonation being configured it throws an access denied error.
using (HostingEnvironment.Impersonate())
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.UseDefaultCredentials = true;
service.AutodiscoverUrl(UserEmailAddress);
Mailbox mb = new Mailbox(UserEmailAddress);
FolderId cfCalendarFolderID = new FolderId(WellKnownFolderName.Calendar, mb);
CalendarView cvCalendarView = new CalendarView(DateTime.Now, DateTime.Now.AddDays(30), 1000);
cvCalendarView.MaxItemsReturned = 3;
Perhaps I'm missing a simple way to pass the HostingEnvironment credentials to my ExchangeService object?
Is there a way to check what the service.UseDefaultCredentials are?
I'm not able to use the following as there isn't a way to get the password from the windows authenticated impersonated user.
service.Credentials = new System.Net.NetworkCredential(username, password, domain);
I've also tried the following, but get the same ServiceResponseException access denied errot.
service.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
service.PreAuthenticate = true;
Thanks in advance of your kind assistance.
Additional info which may or may not be relevant:
The Application Pool Identity for the website is NetworkService.
The UserEmailAddress variable is set from an AD lookup based on System.Security.Principal.WindowsIdentity.GetCurrent().Name
EDIT (14th Aug 2012)
To achieve what I'd like to do above, I believe the HostingEnvironment.Impersonate isn't required.
Instead I need to use the ExchangeService's ImpersonatedUserId property.
More details on that here
Only problem though is we're running Exchange 2007 and the power shell command for enabling a service account to impersonate all users (that you would use pass in to the .Credentials parameter) only appears to be compatible with Exchange 2010.
You should try using WebCredentials instead of NetworkCredential - see related SO post. There seems to be an issue with EWS and AutoDiscover + NetworkCredentials

Active Directory Query ASP VB .Net only works in Trusted Sites

I have a ASP .Net web appliaction written in Visual Basic .Net running on Windows Server 2003 (IIS 6) that works like the one described in How to grab AD credentials from client machine in a web application?
A user access our Intranet page and it uses Windows Authentication to identify the user. The application then looks up that user in Active Directory and grabs the attribute value for that user's IpPhone. This number is what we use for Employee ID's.
In IE8 I can access the site and Windows Auth prompts me and it appears to work but the application is unable to get my Active Directory user "IP Phone" value (AKA my Employee Number). If I add the URL to Trusted Sites, the application works grabs my Employee ID successfully.
That wouldn't be a big deal except it does this in every browser (FireFox, Safari, and Chrome). I found a workaround for Firefox (ntlm-authenticate, google 'about config' for firefox). However this app shouldn't need to be in Trusted Sites, and I believe if I can get this to work without being in Trusted Sites it will work in all browsers.
Does anyone have any idea whats going on? Thanks in advance.
Take a look at the setting in the screenshot below. The automatic logon refers to using your Windows authentication as you access resources via Internet Explorer. In other words, if you access a web page on a server in your directory, the credentials that you logged in on your machine with are automatically passed to the server you're accessing.
The credentials are generally, for some reason unknown to me, passed along to trusted sites as well. I don't know why this is, but I've seen this behavior enough to be confident stating it.
This feature is only available in IE, except for the workaround you found for Firefox, and will not work in other browsers, unless you find similar workarounds.
A better solution would be to specify the username and password in code as shown here:
http://msdn.microsoft.com/en-us/library/wh2h7eed.aspx
This performs a search and passes along a username and password, rather than relying on the Windows Integrated security.
I have a working snippet of code here for getting an email based on username in our domain, that you can modify for your needs:
Public Function GetEmailFromUserName(ByVal UserID As String) As String
Dim ReturnValue As String = ""
Dim myAD As New System.DirectoryServices.DirectoryEntry("LDAP://mydomain", System.Configuration.ConfigurationManager.AppSettings("adsearchname"), System.Configuration.ConfigurationManager.AppSettings("adsearchpwd"))
Dim searcher As New System.DirectoryServices.DirectorySearcher(myAD)
searcher.Filter = ("(anr= " & UserID & ")")
searcher.PropertiesToLoad.Add("mail")
For Each myResult As System.DirectoryServices.SearchResult In searcher.FindAll()
For Each Key As String In myResult.Properties.PropertyNames
If InStr(myResult.Properties.Item(Key).Item(0), "#") Then
ReturnValue = myResult.Properties.Item(Key).Item(0)
End If
Next
Next
Return ReturnValue
End Function

Resources