Validating Email Using System.Net.Mail.MailAddress Fails - asp.net

I'm trying to validate a list of email addresses using the following code:
Public Function ValidateEmailAddressField() As Boolean
Dim isValid As Boolean = True
Try
txtServiceEmails.Text = txtServiceEmails.Text.Trim.Replace(",", ";")
Dim validateMailAddress = New MailAddress(txtServiceEmails.Text.Trim)
Return isValid
Catch ex As Exception
isValid = False
Return isValid
End Try
End Function
When I enter "johndoe#amce" or "johndoe#acme, janedoe#acme.org" the code validates true. Is entering an email address without an extension, such as ".com", actually considered a valid email address?
Thanks,
crjunk

In an cooperation environment, a domain does not have to have .com/net/org... 'acme' could be a valid domain, so, the email me#acme could be a valid email address internally.
usually, people use regular expression to valid email address. there are lots of examples.

Yes, it is valid. The domain part of email address must match the requirements for a hostname and depending of local configurations the "extension" may be optative.
A hostname is considered to be a fully qualified domain name (FQDN) if all the labels up to and including the top-level domain name (TLD) are specified. The hostname en.wikipedia.org terminates with the top-level domain org and is thus fully qualified. Depending on the operating system DNS software implementation, an unqualified hostname such as csail or wikipedia may be automatically combined with default domain names configured into the system, in order to determine the fully qualified domain name. As an example, a student at MIT may be able to send mail to "joe#csail" and have it automatically qualified by the mail system to be sent to joe#csail.mit.edu.
Source: Wikipedia

Settled for a Regular Expression Validator solution.
Public Function ValidateEmailAddressField() As Boolean
Dim isValid As Boolean = True
Dim emailExpression As New Regex("^((\s*[a-zA-Z0-9\._%-]+#[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4}\s*[,;:]){1,100}?)?(\s*[a-zA-Z0-9\._%-]+#[a-zA-Z0-9\.-]+\.[a-zA-Z]{2,4})*$")
Try
txtServiceEmails.Text = txtServiceEmails.Text.Trim.Replace(",", ";")
txtServiceEmails.Text = txtServiceEmails.Text.Trim.Replace(" ", "")
isValid = emailExpression.IsMatch(txtServiceEmails.Text.Trim)
Return isValid
Catch ex As Exception
isValid = False
Return isValid
End Try
End Function

Related

How validate for domain name of email address

I have a form in which user enters email address.I am validating it through java script.I want to validate the Domain name of email address
What is the best way to validate domain name of email address in .net ?
best way for check domain name in Email address is use regular expression
this Expression use for validation email
\w+([-+.']\w+)#\w+([-.]\w+).\w+([-.]\w+)*
you can edit domain part in this expression \w+([-.]\w+)*\
this webservive is checking domain:
http://www.ecocoma.com/domain_webservice.aspx
you must substring domain name from email address and send to webservice
notice: for testing this webservive, you must online
sample code for working it:
protected void btnwhoIs_Click(object sender, EventArgs e)
{
try
{
Whois_Service service = new Whois_Service();
Whois whois = new Whois();
service.SoapVersion = SoapProtocolVersion.Soap12;
whois = service.GetWhois("DOM-T36309683M", "", txtWhoIs.Text);
divRes.InnerText = whois.Description;
}
catch (System.Net.WebException ex)
{
divRes.InnerText = ex.Message;
}
}
As #KingCronus said, there's no good method built in the framework for doing this. The most reliable method I know of is using this commercial component: http://cobisi.com/email-validation/.net-component
I've once done work using it for a client and it seemed reliable. You can use it to detect bogus email services (like http://mailinator.com/), but unfortunately, I don't know of any free component that performs this functionality.

Multiple IP address lookup

I was wondering if there is an API that will allow me to insert a 100 or more IP addresses separated by a new line, trace them retrieve their info all in one push of a button? At the moment I am using a free API but I cannot figure out if it can trace multiple IP addresses and if so, how?
Here is the API url: http://www.ipaddressapi.com/
and here is the url where I enter the IP address at the end of it:
http://www.ipaddressapi.com/l/55ffa3e1bb4f123a2e0e21bf30a6731fec615a69b682?h=45.0.0.0
I tried doing it like this
http://www.ipaddressapi.com/l/55ffa3e1bb4f123a2e0e21bf30a6731fec615a69b682?h=45.0.0.0&47.0.0.0 (Adding & then the second IP address) but that didn't work either. Any suggestions or thoughts?
Just do something like the following:
Loop through your ip addresses:
For Each s as String in MyAddresses
'Add the ip address on the end of the url you wish to get the data for:
Dim result as string = GetWebPageAsString(New Uri("http://someaddress.com?" + s))
'parse result however you need to here
Next
A function to get web page as a string
Public Shared Function GetWebPageString(ByVal address As Uri) As String
Try
Using client As New Net.WebClient()
Return client.DownloadString(address)
End Using
Catch ex As System.Exception
Return ""
End Try
End Function

How to check email address exists or not using ASP.NET?

How to check the given email (any valid email) address exists or not using ASP.NET?
You can't check if an email exists without actually sending an mail.
The only thing you can check is if the address is in a correct shape with regexes:
string email = txtemail.Text;
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
Response.Write(email + " is corrct");
else
Response.Write(email + " is incorrct");
you send invitation mail to user with encrypted key..
If user is verified you have to verified key and you have only verified email..
Here's a code solution that may work for you. This sample sends a message from address different from From: address specified in the message. This is useful when bounced messages should be processed and the developer wants to redirect bounced messages to another address.
http://www.afterlogic.com/mailbee-net/docs/MailBee.SmtpMail.Smtp.Send_overload_3.html
The full process is not so simple.
Its required a full communication with the email server and ask him if this email exist or not.
I know a vendor that give a dll that make all this communication and check if the email exist or not on the server, the aspNetMX at http://www.advancedintellect.com/product.aspx?mx
First you need to import this namespace:
using System.Text.RegularExpressions;
private bool ValidateEmail(string email)
{
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
Match match = regex.Match(email);
if (match.Success)
return true;
else
return false;
}
Visit Here to full source code.

LDAP user attribute request returns unusual results

I'm struggling to return user details from AD using LDAP, after i have authenticated that the user exists.
I am using a simple auth method as follows:
Function AuthenticateUser(path As String, user As String, pass As String) As Boolean
Dim de As New DirectoryEntry(path, user, pass, AuthenticationTypes.Secure)
Try
Dim ds As DirectorySearcher = New DirectorySearcher(de)
Dim result As SearchResult = ds.FindOne()
If result Is Nothing Then Return False
'>>DEBUG OUTPUTS ONLY:
displayName.Text = result.GetDirectoryEntry().Properties.Item("distinguishedName").Value
displayName.Text += result.GetDirectoryEntry().Properties("name").Value
Return True
Catch
Return False
End Try
End Function
the problem is that "distinguishedName" returns "DC=our-domain,DC=co,DC=uk"
and "name" returns just "our-domain", not the name of the user that has just been auth'ed
Note: the displayName.text outputs are purely for debug purposes
I have tried various combos of requests but nothing seems to return USER details.
ETA: to the security police: this is all within a https connection, I'm not sending passwords about in plain text!
1. Dim de As New DirectoryEntry(path, user, pass, AuthenticationTypes.Secure)
2. Try
3. Dim ds As DirectorySearcher = New DirectorySearcher(de)
4. Dim result As SearchResult = ds.FindOne()
Line 1 is basically creating a DirectoryEntry element, that refers to the object at path. The only purpose that the username and password parameters serve is to authorise access to whatever entity path refers to.
As you currently have things, you're binding to the domain, not to the user (but you're authorised to connect to the domain as that user).
You then, in line 3, create a DirectorySearcher. But the constructor you're using just says to root the search at de (which as we've established, is just the domain). You've not done anything yet to search for that particular user within the domain - they could be connecting to perform almost any kind of search imaginable.
What you might want to do is look at the overload of DirectorySearcher that accepts a filter parameter - and provide a filter parameter that restricts the search to just the user. I don't know what form your user parameter is in - if it is, say, in the form of a user principal name (user#domain), you might try specifying a filter of:
Dim ds As DirectorySearcher = New DirectorySearcher(de,"(userPrincipalName=" + user + ")")
If you have just a username, you'd want to search against sAMAccountName. If you have an older style domain name (domain\user), then usually you want to split that on \, discard the domain name, and still search on sAMAccountName.
Some (but not too much!) help on constructing the filter parameters is found in the Filter property documentation.

How to validate email address inputs?

I have an ASP.NET web form where I can can enter an email address.
I need to validate that field with acceptable email addresses ONLY in the below pattern:
xxx#home.co.uk
xxx#home.com
xxx#homegroup.com
A regular expression to validate this would be:
^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$
C# sample:
string emailAddress = "jim#home.com";
string pattern = #"^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$";
if (Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase))
{
// email address is valid
}
VB sample:
Dim emailAddress As String = "jim#home.com"
Dim pattern As String = "^[A-Z0-9._%+-]+((#home\.co\.uk)|(#home\.com)|(#homegroup\.com))$";
If Regex.IsMatch(emailAddress, pattern, RegexOptions.IgnoreCase) Then
' email address is valid
End If
Here's how I would do the validation using System.Net.Mail.MailAddress:
bool valid = true;
try
{
MailAddress address = new MailAddress(email);
}
catch(FormatException)
{
valid = false;
}
if(!(email.EndsWith("#home.co.uk") ||
email.EndsWith("#home.com") ||
email.EndsWith("#homegroup.com")))
{
valid = false;
}
return valid;
MailAddress first validates that it is a valid email address. Then the rest validates that it ends with the destinations you require. To me, this is simpler for everyone to understand than some clumsy-looking regex. It may not be as performant as a regex would be, but it doesn't sound like you're validating a bunch of them in a loop ... just one at a time on a web page
Depending on what version of ASP.NET your are using you can use one of the Form Validation controls in your toolbox under 'Validation.' This is probably preferable to setting up your own logic after a postback. There are several types that you can drag to your form and associate with controls, and you can customize the error messages and positioning as well.
There are several types that can make it a required field or make sure its within a certain range, but you probably want the Regular Expression validator. You can use one of the expressions already shown or I think Visual Studio might supply a sample email address one.
You could use a regular expression.
See e.g. here:
http://tim.oreilly.com/pub/a/oreilly/windows/news/csharp_0101.html
Here is the official regex from RFC 2822, which will match any proper email address:
(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])
I second the use of a regex, however Patrick's regex won't work (wrong alternation). Try:
[A-Z0-9._%+-]+#home(\.co\.uk|(group)?\.com)
And don't forget to escape backslashes in a string that you use in source code, depending on the language used.
"[A-Z0-9._%+-]+#home(\\.co\\.uk|(group)?\\.com)"
Try this:
Regex matcher = new Regex(#"([a-zA-Z0-9_\-\.]+)\#((home\.co\.uk)|(home\.com)|(homegroup\.com))");
if(matcher.IsMatch(theEmailAddressToCheck))
{
//Allow it
}
else
{
//Don't allow it
}
You'll need to add the Regex namespace to your class too:
using System.Text.RegularExpressions;
Use a <asp:RegularExpressionValidator ../> with the regular expression in the ValidateExpression property.
An extension method to do this would be:
public static bool ValidEmail(this string email)
{
var emailregex = new Regex(#"[A-Za-z0-9._%-]+(#home\.co\.uk$)|(#home\.com$)|(#homegroup\.com$)");
var match = emailregex.Match(email);
return match.Success;
}
Patricks' answer seems pretty well worked out but has a few flaws.
You do want to group parts of the regex but don't want to capture them. Therefore you'll need to use non-capturing parenthesis.
The alternation is partly wrong.
It does not test if this was part of the string or the entire string
It uses Regex.Match instead of Regex.IsMatch.
A better solution in C# would be:
string emailAddress = "someone#home.co.uk";
if (Regex.IsMatch(emailAddress, #"^[A-Z0-9._%+-]+#home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
// email address is valid
}
Of course to be completely sure that all email addresses pass you can use a more thorough expression:
string emailAddress = "someone#home.co.uk";
if (Regex.IsMatch(emailAddress, #"^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#home(?:\.co\.uk|(?:group)?\.com)$", RegexOptions.IgnoreCase))
{
// email address is valid
}

Resources