Check email credentials existence - c#

There are dozen of questions asking is smtp server working like Testing SMTP server is running via C# and Can I test SmtpClient before calling client.Send()? and they do they work of checking by sending commands to smtp servers. They never use any credentials for testing purposes. So I'm wondering is there a way to check are these login and password valid on this smtp-server without sending a mail?

My big concern when I was working on this issue is to find a solution where I do not have to send email to check if the credentials are valid or not. So after trying a bunch of the solutions offered online, I came up with my own acceptable one to test email credentials :
I use MailKit to help me out.
public static bool ValidateCredentials(string username, string password, string server, int port, bool certificationValidation)
{
try
{
using (var client = new MailKit.Net.Smtp.SmtpClient())
{
try
{
client.ServerCertificateValidationCallback = (s, c, h, e) => certificationValidation;
client.Connect(server, port, false);
client.Authenticate(username, password);
client.Disconnect(true);
return true;
}
catch (Exception ex)
{
Console.WriteLine(string.Format("ValidateCredentials Exception: {0}", ex.Message));
}
}
}
catch (System.Exception ex)
{
Console.WriteLine(string.Format("ValidateCredentials Exception: {0}", ex.Message));
}
return false;
}

SMTP doesn't allow you login without sending an email.
have a look at the below:
How to validate smtp credentials before sending mail?

Related

The operation has timed out. while sending email through smtp using C# ASP.net

I am getting error "operation time out"and it throws me to the exception when i am sending email through my smtp server.I am using the code with gmail smtp and the same code works fine.In smtp details I am using network credential as my username and password i got when i created my email account on my domain and outgoing server and smtp port. following is my code..
protected void send_Click(object sender, EventArgs e)
{
string to = "xyz#gmail.com"; //To address
string from = "xyz#gmail.com"; //From address
MailMessage message = new MailMessage(from, to);
string mailbody = "Welcome to gmail...";
message.Subject = "Sending Email";
message.Body = mailbody;
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("server host",port);
System.Net.NetworkCredential basicCredential1 = new
System.Net.NetworkCredential("Username ","Password");
client.EnableSsl = true;
//client.Timeout = 10000;
client.UseDefaultCredentials =false;
client.Credentials = basicCredential1;
try
{
client.Send(message);
}
catch (Exception ex)
{
throw ex;
}
}
Because you haven't posted any log data, what you have already tried, and what didn't work, and only giving us the timeout as an outcome, there are a lot of open ended questions to your question. So instead of a specific answer, all I can do is give you vague directions what you need to do, to resolve your issue.
There can be a lot of issues with this sort of thing.
You write that this code performs correctly with another server, if I understand you correctly?
I would check:
A, Am I 100% sure my server connection string is correct? Also port wise?
B, Am I sure the ports are open for this communication to happen?(Check the firewalls are open)
C, Am I that there isn't some sort of version or configuration that is different between the gmail smtp, and you local smtp?
D, Check the SMTP server logs, if you are even receiving the request.
D1, if you are receiving, check which error is causing the timneout, this will likely be in the log.
D2, Start from A, There is something wrong with your connection to the SMTP server.

Connecting to LDAP with PHP Successfully, but cannot connect with C#

I am connecting successfully to the LDAP with PHP, tried a whole lot of things but when I try with C# am always getting either "Server is not operational" or "The LDAP server in unavailable".
Here is the PHP code:
<?php
function login($username='user', $password='pass') {
if (empty($username) || empty($password)) {
throw new BadCredentialsException('Invalid username or password.');
}
if (($ldap = #ldap_connect($url = 'ldap://ds.xyz-example.com', $port = 636)) === false) {
echo('Error connecting LDAP server with url %s on port %d.');
}
if (!#ldap_bind($ldap, sprintf($dn='uid=%s,ou=People,dc=xyz-example,dc=com', $username), $password)) {
$error = ldap_errno($ldap);
if ($error === 0x31) {
echo('Invalid username or password.');
} else {
echo('error during authentication with LDAP.');
}
}
return true;
}
login(); // call the function
?>
This is working perfect but I need it with C#. How can I do this with C# using the port and the dn and the user and pass?
Here is what I tried with C# but with an error "Server is not operational"
string ldapPath = "LDAP://ds.xyz-example.com:636/UID=user,OU=People,DC=xyz-example,DC=com";
string user = "user";
string password = "pass";
DirectoryEntry deSSL = new DirectoryEntry(ldapPath, user, password, AuthenticationTypes.SecureSocketsLayer);
try
{
user = deSSL.Properties["uid"][0].ToString(); //if this works, we bound successfully
Response.Output.Write("Success... {0} has bound", user);
}
catch (Exception ex)
{
Response.Output.Write("Bind Failure: {0}", ex.Message);
}
Thanks in advance!
Could it be your library doesn't implement LDAP but rather a weird non-standard Microsoft version of LDAP called ActiveDirectory, which only works when the server is an actual ActiveDirectory Server and doesn't quite work as easily when you use non-microsoft servers, such as OpenLDAP?
Could it be?

Can't connect to Gmail with IMAPX using c#

I'm following an example from IMAPX but it will not connect to GMAIL.
IMAP is enabled for the account and I've triple checked the username and password but it won't connect:
var server = ConfigurationManager.AppSettings["server"];
var login = Decrypt(ConfigurationManager.AppSettings["user"]);
var password = Decrypt(ConfigurationManager.AppSettings["pass"]);
//create the IMAP CLient
var client = new ImapClient(server, true);
//connect to the server
if (!client.Connect())
{
Console.WriteLine("Error: Failed to connect");
return;
}
//login to the server
if (!client.Login(login, password))
{
Console.WriteLine("Error: Invalid login");
return;
}
Anyone have any idea how to use this library to connect to gmail? I have tried variations of "use SSL" and "verify certificate", but no mater what I try the login always fails.
Google by default does not allow "less secure" apps from account access unless the account is setup to allow it.
References:
https://support.google.com/accounts/answer/6010255?hl=en
https://security.stackexchange.com/questions/66025/what-are-the-dangers-of-allowing-less-secure-apps-to-access-my-google-account

mvc app; send email using gmail does NOT produce SmtpFailedRecipientException or SmtpFailedRecipientsException

I have an mvc application that uses gmail to send out an email.
My code:
Successfully sends out an email, providing:
I use proper account authentication (username, pw)
I send the email to a valid existing email account
I get an exception if I do not use my valid gmail username, pw. (which is good).
My question and my problem is:
When my code sends an email to an invalid email account, I do not get an exception of any kind! No SmtpFailedRecipientException, no SmtpFailedRecipientsException; nada.
Why is this happening? What do I need to change so that I get an exception back when an email is sent to an invalid, non-existent account?
Code in my MVC app:
In Identity.cs
public class EmailService : IIdentityMessageService
{
public Task SendAsync(IdentityMessage message)
{
try
{
System.Web.Helpers.WebMail.Send(message.Destination, message.Subject, message.Body, "DoNotReply#ourcompany.com");
}
catch (Exception e)
{
throw; //Add msg here; set break point when testing; whatever
}
return Task.FromResult(0);
}
}
And in AuthConfig.cs, I have the gmail account settings, which we know work.
System.Web.Helpers.WebMail.SmtpServer = "smtp.gmail.com";
WebMail.EnableSsl = true;
WebMail.UserName = "OurUserName";
WebMail.Password = "OurPW";
WebMail.From = "DoNotReply#OurCompany.com";
WebMail.SmtpPort = 587;
In my controller, I have this partial code:
public async Task<ActionResult> Register(RegisterViewModel model)
{
try
{
await UserManager.SendEmailAsync(user.Id, emailSubject, emailBody);
}
catch (Exception e)
{
}
}
The controller runs first. I am using the asp.identity2 (UserManager) and SendEmailAsync calls the SendAsync in Identity.cs.
Thank you for suggestions.
Gmail doesn't let you know which email addresses it has failed to send emails to to avoid bots looking for valid email addresses. You should get an email later though with details about failed email addresses.

System.Net.Mail The requested service provider could not be loaded or initialized

I got the following exception when trying to send email using System.Net.Mail.SmtpClient:
System.Net.Mail.SmtpException: The SMTP host was not found.
Inner exception:
System.Net.Sockets.SocketException: The requested service provider could not be loaded or initialized
My email sending code is rather simple:
private async Task SendEmail(string to, string subject, string email)
{
MailMessage msg = null;
SmtpClient smtp = null;
try
{
var set = Settings.Default;
msg = new MailMessage(set.EmailFrom, to, subject, email);
smtp = new SmtpClient(set.SMTPServer, set.Port)
{
EnableSsl = true,
Credentials = new NetworkCredential(set.EmailUsername, set.EmailPassword),
Timeout = 20000
};
await smtp.SendMailAsync(msg);
}
catch (Exception e)
{
_log.Error("Error on sending email", e);
throw;
}
finally
{
if (msg != null) msg.Dispose();
if (smtp != null) smtp.Dispose();
}
}
This error does not happen each time, but rather often. I tried to google it but have not found anything useful. The internet connection seems to be stable when I get this error.
Any ideas why this could happen?
Apologies for not posting this as a comment, I don't have sufficient rep.
I run a process using a very similar implementation to that and I have had the same thing happen to me. Try reducing SMTP the timeout, a new connection will be refused if there are too many requests that haven't let go of their existing connection yet. It's helped with my specific implementation.

Categories