Send Email in C# using NTLM - c#

I need to send email using NTLM, currently, I'm using the following code to send email
SmtpClient objSmtpClient;
System.Net.NetworkCredential objNetworkCredential;
objSmtpClient = new SmtpClient("10.xxx.xxx.xxx", 587);
objSmtpClient.EnableSsl = true;
objNetworkCredential = new System.Net.NetworkCredential(userName, password);
try
{
string to = txtto.Text;
MailMessage objMailMessage = new MailMessage();
objMailMessage.From = new MailAddress("from#email.com", "sendername");
objMailMessage.To.Add(new MailAddress("to#email.com"));
objMailMessage.Subject = "subject";
objMailMessage.Body = "body";
objMailMessage.IsBodyHtml = true;
objSmtpClient.EnableSsl = true;
objSmtpClient.UseDefaultCredentials = true;
objSmtpClient.Credentials = objNetworkCredential;
objSmtpClient.Send(objMailMessage);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " INNER EXCEPTION > "+ex.InnerException +" DATA > "+ex.Data);
}
The Above code works if I try to change the port to 25 and EnableSSL to false, But when I try to send it using 587 and setting EnableSSL to true it doesn't work.
I'm getting the following error, sometimes I get an Invalid Certificate error.
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.1 Client was not authenticated.
I am also getting this error
I think the problem is with Authentication, how can I force to use NTLM
I talked with the IT team they installed a tool on my pc to check email, using that tool email was sent successfully.
The following are the setting which he applied in that tool
Can someone please help

I was testing, I had the same problem, I fixed it by disabling SSL security
SC.EnableSsl = false;

Related

Sending email from office 365 mailbox through C# using SMTP

I have a console application, through which I need to send out email notifications. I am able to login into mailbox using the same credentials in the browser.
From the exception thrown, it seems like I am not able to open connect with Office OWA through C# code and getting an error message: "Failure Sending mail" - Inner exception - "Unable to connect to remote server".
I have noticed that while login into mailbox from the browser, it 1st make me land on company-specific page based on email address domain and then ask to enter password to login into the mailbox.
Also, network credentials passed to open smtpClient connect need to have some admin privileges or elevated permissions in Office 365, or it can be a regular office 365 user with a mailbox.
Reference blog:
https://weblogs.asp.net/sreejukg/send-email-using-office-365-account-and-c?__r=8d721ba733714a1
https://learn.microsoft.com/en-us/Exchange/mail-flow-best-practices/how-to-set-up-a-multifunction-device-or-application-to-send-email-using-office-3?redirectSourcePath=%252farticle%252fHow-to-set-up-a-multifunction-device-or-application-to-send-email-using-Office-365-69f58e99-c550-4274-ad18-c805d654b4c4#HowtoconfigSMTPCS
try
{
String userName = "SenderEmailAddress#myCompanyDomain.com";
String password = "passwordgoeshere";
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress("john.smith#myCompanyDomain.com"));
msg.From = new MailAddress(userName);
msg.Subject = "Test Office 365 Account";
msg.Body = "Testing email using Office 365 account.";
msg.IsBodyHtml = true;
using (SmtpClient client = new SmtpClient
{
Host = "smtp.office365.com",
Credentials = new System.Net.NetworkCredential(userName, password),
Port = 587,
EnableSsl = true,
})
{
client.Send(msg);
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
Console.ReadKey();
}
Goal:
I should be able to send out emails from a shared mailbox if I open the connection using shared mailbox credentials.
Please add UseDefaultCredentials = false, otherwise it will select system or authenticated user credential for sending email
using (SmtpClient client = new SmtpClient
{
Host = "smtp.office365.com",
Credentials = new System.Net.NetworkCredential(userName, password),
Port = 587,
EnableSsl = true,
UseDefaultCredentials = false
})
{
client.Send(msg);
}
or recommend to set like this
using (SmtpClient client = new SmtpClient
{
Host = "smtp.office365.com",
Credentials = new System.Net.NetworkCredential(userName, password),
Port = 587,
EnableSsl = true
})
{
client.UseDefaultCredentials = false;
client.Send(msg);
}

SmtpClient to Hosted Exchange Server gives - An attempt was made to access a socket in a way forbidden by its access permissions xxx.xxx.xxx.xxx:25

I've been banging my head against this one for weeks, but today was the day I promised I'd get it fixed. So far I've failed.
I am trying to send an email from a hosted MVC application, via a Hosted Exchange server. The IT department has said and confirmed that they have allowed the IP of the MVC application through. However, the following code gives me "An attempt was made to access a socket in a way forbidden by its access permissions ###.###.###.###:25" every time.
ActionResult Test()
{
MailMessage message = new MailMessage();
message.From = new MailAddress("valid.email.address");
message.Subject = "Test Email";
message.To.Add(new MailAddress("another.valid.email.address"));
message.Body = "Hey, this is a test!";
using (SmtpClient client = new SmtpClient())
{
client.Credentials = new System.Net.NetworkCredential("username", "password");
client.Port = 25;
client.EnableSsl = true; // Either true or false gives same result
client.Host = "actual.host.url";
try
{
client.Send(message);
}
catch (Exception ex)
{
ViewBag.LogMessage = string.Format("Error: {0}<br />{1}<br />{2}", ex.Message, ex?.InnerException.Message, ex?.InnerException?.InnerException.Message);
return View();
}
ViewBag.LogMessage = string.Format("client.Host: {0}<br />Client.Port: {1}<br />Client.EnableSsl: {2}<br />message.To[0].Address: {3}", client.Host, client.Port, client.EnableSsl ? "true" : "false", message.To[0].Address);
}
return View();
}
The value of the LogMessage is:
Error: Failure sending mail.
Unable to connect to the remote server
An attempt was made to access a socket in a way forbidden by its access permissions ###.###.###.###:25
Any suggestions would be welcome! I've tried port 587 with no luck. I've tried with and without credentials, with or without SSL, username matching from address or not. I've run out of things to try.
Thanks!
Try the following code, the first line tells SMTP Client to ignore any issue with the SSL cert if its provide from an invalid provider.
ServicePointManager.ServerCertificateValidationCallback =(sender,certificate, chain, sslPolicyErrors) => true;
var smtpClient = new SmtpClient("oba.exchangeserver.com")
{
Port = 587,
EnableSsl = true,
Credentials =
new NetworkCredential("username","password")
};
return smtpClient;

SmtpClient is unable to connect to Gmail using SSL

I see many posts on SMTPClient but I'm still stuck.
I am creating a C# Console application targeting the .NET 4.0 framework and running on a Windows 2008 R2 Datacenter (server).
I want send an email using SSL from a gmail account I just created.
If I use port 587, I get an exception:
The SMTP server requires a secure connection or the client was not authenticated
If I use port 465, I get another one:
Unable to read data from the transport connection: A blocking operation was interrupted by a call to WSACancelBlockingCall.
I realize this question has been asked several times in the past. All answers I see relate to the order in which UseDefaultCredentials is set. It must be set to false BEFORE the real credentials are set. I have followed this advice (as per the code below) and yet I still get a failure.
Other answers include switching ports from 465 to 587... which i have tried and just results in a different error (as stated above).
Here's my code:
NetworkCredential credentials = new NetworkCredential("something#gmail.com", "2-step-auth-Password");
MailAddress address = new MailAddress("something#gmail.com");
SmtpClient client = new SmtpClient("smtp.gmail.com", 465); // or 587
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.EnableSsl = true;
client.Credentials = credentials;
client.Timeout = 10000; // 10 seconds.
client.Host = "smtp.gmail.com";
//client.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);
MailMessage message = new MailMessage("example#gmail.com", recipients);
message.Subject = "Hello";
message.Body = "Goodbye";
message.BodyEncoding = Encoding.UTF8;
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateTestMessage2(): {0}", ex.ToString());
}
message.Dispose();
Update 2: I see another answer which may be my issue: gmail requires an application-specific password (which is apparently not available with my current gmail account. not sure why yet). but this may be my issue.
Update 3: I have followed all instructions. Generated 2-step authentication with Gmail, and still fails.
Below code works for me, you can try this:
SmtpClient smtp = new SmtpClient("smtp.office365.com");
//Your Port gets set to what you found in the "POP, IMAP, and SMTP access" section from Web Outlook
smtp.Port = 587;
//Set EnableSsl to true so you can connect via TLS
smtp.EnableSsl = true;
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("Username", "Password");
smtp.Credentials = cred;
MailMessage mail = new MailMessage();
mail.From = new MailAddress("Sender Email Address", "Sender Name");
StringBuilder mailBody = new StringBuilder();
mail.To.Add("ToEmailAddress");
mail.Subject = "Subject";
mail.IsBodyHtml = true;
mail.Body = "Body Text";
try
{
smtp.Send(mail);
}
catch (Exception ex)
{
}

Error sending mail with SmtpClient

I've been struggeling a lot with this now.
I try to send mail with my mvc application using my google apps account. But I keep getting errors. It doesn't matter which settings I use. I tried using both port 465 and 587 with ssl and authentication turned on. With 465 I get Operation Timed Out and with 587 I get this message:
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication Required
I tried turning of the firewall with no luck. I have also tried to turn off 2-step authentication but I figured out that it wasn't even turned on.
I hope that you can help me
Regards
Here is the code as requested:
public static void SendMail(MailAddress from, MailAddress to, string subject, string body) {
MailMessage mail = new MailMessage();
mail.From = from;
mail.To.Add(to);
mail.Subject = subject;
mail.Body = body;
SmtpClient client;
if (Settings.Port != null)
client = new SmtpClient(Settings.Host, Int32.Parse(Settings.Port));
else
client = new SmtpClient(Settings.Host);
client.EnableSsl = Settings.UseSSL;
client.Timeout = 50000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
if (Settings.UseAuthentication) {
client.Credentials = new NetworkCredential(Settings.Username, Settings.Password);
client.UseDefaultCredentials = false;
}
client.Send(mail);
}
I have checked all obvius stuff like username and password (username is formed like user#domain.com). I've also stepped through the code to verify my settings class is working as it should
I found out what the problem was. client.UseDefaultCredentials = false; must go before the credentials is set. Now client.Sendmethod returns without exceptions.

couldn't send email in asp.net using gmail account

Can we use gmail account to send email in asp.net website from *localhost * (local machine) ? I am trying but badly unsuccessful. It works fine on hosting but donot work on my machine.
I have windows server 2003 on my machine, I have added port 587 and 465 in firewall in exceptions. In my gmail account I also have enabled POP and IMAP. Some people suggest to use port 465 and others say port 587 should be used. I tried both and below was my result:
Using port 465 it take time and finally give message that the opration has timed out. falure
Using port 587 it dont take time, show message "failuer sending email" with an inner expection "No connection could be made because the target machine actively refused it 72.14.213.109:587"
Below is my code, please guide me where I am wrong or what I should do.
thanks
public static bool SendMail(string gMailAccount, string password, string to, string subject, string message)
{
try
{
NetworkCredential loginInfo = new NetworkCredential(gMailAccount, password);
MailMessage msg = new MailMessage();
msg.From = new MailAddress(gMailAccount);
msg.To.Add(new MailAddress(to));
msg.Subject = subject;
msg.Body = message;
msg.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.UseDefaultCredentials = false;
client.Credentials = loginInfo;
client.Port = 587;
client.Send(msg);
return true;
}
catch (Exception e)
{
return false;
}
}
I use smtp.yandex.com. May be need change settings in your gmail account.
Try this firs: add:
client.DeliveryMethod = SmtpDeliveryMethod.Network;
If that does not help, your mailaddress might not be complete, use
var fromAddress = new MailAddress("from#gmail.com", "From Name");
and in the credentials use
Credentials = new NetworkCredential(fromAddress.Address, ....
Hope that helps
This SmtpClient has always worked for me:
new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("noreply#my_domain.com", "password")
};
And it matches yours.
Have you been able to contact smtp.gmail.com on port 587 through any other app? Telnet on that port maybe? Am thinking it's probably a network issue, although you did state that your firewall was wide open it's not the only hop between you and google.

Categories