SmtpException when Sending Mail in ASP.NET - c#

I have some code that I am attempting to use to send emails from my ASP.NET MVC 5 website. From what I have read I am doing this the right way and the code is correct
public static Task SendEmailAsync(IEnumerable<string> to,
IEnumerable<string> cc, string body)
{
if (to == null || to.Count() == 0)
return null;
if (String.IsNullOrEmpty(body))
throw new ArgumentNullException("body of the email is empty");
// Send email.
return Task.Factory.StartNew(() =>
{
// Client setup.
using (SmtpClient smtpClient = new SmtpClient("smtp.servername.com", 25)) // Tried 587 too.
{
smtpClient.Credentials = new System.Net.NetworkCredential()
{
UserName = Constants.AdminEmailAddress,
Password = Constants.AdminPwd
};
smtpClient.UseDefaultCredentials = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.EnableSsl = true;
// Mail message.
using (MailMessage mail = new MailMessage())
{
mail.Body = body;
mail.From = new MailAddress(Constants.AdminEmailAddress, "Business Name Here");
foreach (var a in to)
mail.To.Add(new MailAddress(a));
if (cc != null)
foreach (var a in cc)
mail.CC.Add(new MailAddress(a));
smtpClient.Send(mail); // Here I get exception.
}
}
});
}
But on the line marked above I get
System.Net.Mail.SmtpException: Unable to connect to the remote server A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond NNN.NNN.NNN.NNN:MMM
I understand that this is clearly saying that the client cannot connect, but these are the exact same details that I am using to send email from Microsoft Outlook and that works.
Why can't I connect to the mail server using these credentials, what am I missing?
I am aware that I may have to contact the mail service provider and ask for permissions, but this is my first attempt at this and would like some clarification about what to do. I have looked at mandrillapp.com which provides a mail service, is this a good option, can someone advise?
Thank for your time.
Note, I have read
How to send email from Asp.net Mvc-3?
http://www.c-sharpcorner.com/UploadFile/sourabh_mishra1/sending-an-e-mail-using-Asp-Net-mvc/
send email from MVC 4 ASP.NET app
Update
Following the very helpful suggestions by #Dave Zych below I have removed the SmtpException but I now have System.Security.Authentication.AuthenticationException saying "The remote certificate is invalid according to the validation procedure.". So I am in the same boat and still cannot send email.

Don't specify UseDefaultCredentials (or set it to false). That causes it to use the credentials of the currently logged in user, not what you set in the Credentials property.
From MSDN:
Some SMTP servers require that the client be authenticated before the server sends e-mail on its behalf. Set this property to true when this SmtpClient object should, if requested by the server, authenticate using the default credentials of the currently logged on user. For client applications, this is the desired behavior in most scenarios.
...
If the UseDefaultCredentials property is set to false, then the value set in the Credentials property will be used for the credentials when connecting to the server. If the UseDefaultCredentials property is set to false and the Credentials property has not been set, then mail is sent to the server anonymously.

Related

Go Daddy email SMTP not sending email but no error

I've recently purchased the essentials email package from GoDaddy and I am trying to set up sending email from my website via SMTP. I have the following code set up.
var smtp = new SmtpClient
{
Host = "mycoolwebsite.com.mail.protection.outlook.com",
Port = 25,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("info#mycoolwebsite.com", "supersecurepassword")
};
using (var message = new MailMessage("info#mycoolwebsite.com", "myemail#test.com")
{
IsBodyHtml = true,
Subject = subject,
Body = body
})
{
smtp.Send(message);
}
This gets to send and doesn't throw any exceptions, however the email is not sent. I am very confused at why this doesn't work.
Has anyone got any ideas?
This is going to require TLS which means using MailKit's SMTP. You can get it using the NuGet package manager in Visual Studio. Search for MailKit by Jeffrey Stedfast.
Documentation is here as well.
Once you have all the references in place, use the MailKit.Net.Smtp.SmtpClient class:
Set "smtp.office365.com" as your host
Use port 587.
You will need to add this line after creating your smtp instance because you have no OAuth token:
smtp.AuthenticationMechanisms.Remove("XOAUTH2");
That will do what you need.
Here's an example of what the whole thing should look like:
string FromPseudonym = "MySite Support";
string FromAddress = "admin#MySite.com";
var message = new MimeMessage();
message.From.Add(new MailboxAddress(FromPseudonym, FromAddress));
message.To.Add(new MailboxAddress("Recipient Pseudonym", "RecipientAddress#somewhere.com"));
message.Subject = "Testing Email";
var bodyBuilder = new BodyBuilder();
string MsgBody = "Message Body stuff goes here";
bodyBuilder.HtmlBody = MsgBody;
message.Body = bodyBuilder.ToMessageBody();
using (var client = new SmtpClient())
{
client.Connect("smtp.office365.com", 587);
client.AuthenticationMechanisms.Remove("XOAUTH2");
client.Authenticate(FromAddress, "Your super secret password goes here");
client.Send(message);
client.Disconnect(true);
}
You'll need the following namespaces to be included:
using MimeKit;
using MimeKit.Utils;
using MailKit.Net.Smtp;
I've been where you are before. If you are running the app from your dev environment, the emails will not be sent. GoDaddy SMTP is configured so that emails will only be sent when requested from within their environment.
If you push the code to their host and run it, it will work. The most painful thing about this is that everything appears to go smoothly, but the SMTP client just eats the request and leaves you wondering why no email is sent.
Not knowing anything about GoDaddy's API, the only thing I can suggest, is maybe verify that the port is correct. It might require transport layer security, in which case port 25 will be closed.
For example, I think the office365 SMTP server (smtp.office365.com) requires secure SMTP and uses port 587.

Sending mail using gmail and .net

Getting the exception:
Failure sending mail.
While using System.Net.Mail.Smtp
in C#.NET on the line smtp.Send(message);
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add(sendto);
message.Subject = "CP1 Lab Password";
message.From = new System.Net.Mail.MailAddress("abc#gmail.com");
message.Body = mail_message;
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("yoursmtphost");
smtp.Host = "smtp.gmail.com";
smtp.Port = 465; //(465 for SSL)587
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("abc#gmail.com", "mypassword");
smtp.Send(message);
Edit 1:
Here is the detail of the error:
A connection attempt failed because the connected party did not
properly respond after a period of time, or established connection
failed because connected host has failed to respond ...
The same error when using port 25.
Few months before this code used to work but today it is not working
As from your exception message (incomplete) and the code, it is very hard to say what went wrong in your case. Failure sending mail is thrown when the server is not found, port cannot be connected. It means that connection was not established, until now.
The exception message that gets raised if the connection was established but authentication was not performed correctly is, "The SMTP server requires an authenticated connection...". I would suggest that you check the PORT, SMTP server host (do not add http://) and then re-try. An SMTP connection (in most general cases) requires
SMTP Server host: smtp.gmail.com is enough!
PORT to connect at: I have always used default TCP port for SMTP, 25. It works.
EnableSsl: most require it. I suggest you always use it. client.EnableSsl = true;
Credentials are required by all: No server would allow bots sending emails. In this concern, if you create a new account. You may face trouble sending emails programmatically, I faced the problem with a new account not sending the emails whereas an old account (default account of mine) was sending the email without any trouble.
The following code template (if filled with accurate parameters) will definitely send the email, because I have tested and verified it bazillion times. :)
// You should use a using statement
using (SmtpClient client = new SmtpClient("<smtp-server-address>", 25))
{
// Configure the client
client.EnableSsl = true;
client.Credentials = new NetworkCredential("<username>", "<password>");
// client.UseDefaultCredentials = true;
// A client has been created, now you need to create a MailMessage object
MailMessage message = new MailMessage(
"from#example.com", // From field
"to#example.com", // Recipient field
"Hello", // Subject of the email message
"World!" // Email message body
);
// Send the message
client.Send(message);
/*
* Since I was using Console app, that is why I am able to use the Console
* object, your framework would have different ones.
* There is actually no need for these following lines, you can ignore them
* if you want to. SMTP protocol would still send the email of yours. */
// Print a notification message
Console.WriteLine("Email has been sent.");
// Just for the sake of pausing the application
Console.Read();
}
Sending an email may be a headache sometimes, because it requires some basic understanding of networking also. I have written an article that covers sending emails in .NET framework and a few problems that beginners usually stumble upon such as this one. You may be interested in reading that article also.
http://www.codeproject.com/Articles/873250/Sending-emails-over-NET-framework-and-general-prob

SMTP email client is throwing errors "Timeout" or "requires secure connection" even with correct credential

I was new to SMTP client in C#. So I decided to test it with my credentials. I built an ASP.NET Web forms application that has a Contact Us page on which I am trying to send an email to whoever person fills the form.
I tried sample code after going through this article - https://www.c-sharpcorner.com/UploadFile/87b416/sending-a-simple-email-using-smtpclient-in-C-Sharp/
I have one account in Yahoo so I used its SMTP domain "smtp.mail.yahoo.com" with port number: 465, then my app always threw Timeout exception. So I decided to try with Google's server "smtp.gmail.com" with "587" port and now it raised different exception with message:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
I don't understand what are the prerequisites for working with SMTP on secure servers like Google and Yahoo. Please someone explain.
Also note that I didn't have 2 step verification enabled for my Google account, just to make it clear since some questions on SO have mentioned that this might be the problem.
I also read this question but I am testing directly on my machine - Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required
In case if it helps, here is the sample code:
try
{
MailMessage m = new MailMessage();
m.From = new MailAddress("dummy123#gmail.com");
m.To.Add(new MailAddress("dummyreceiver123#gmail.com"));
m.Subject = TBSub.Text;
m.Body = TBBody.Text;
m.IsBodyHtml = true;
NetworkCredential nc = new NetworkCredential();
nc.UserName = "dummy123"
nc.Password = "dummy#123";
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = nc;
smtp.EnableSsl = true;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Send(m);
}
catch (Exception ex)
{
//Log this error
}
I just tested out your code it works fine you just need to modify this section:
nc.UserName = "test"
nc.Password = "password";
This has to be a valid gmail or google app email along with the password for the smtp connection to work properly. I would recommend that you put in your own for testing purposes, and then modify this to have your email as well:
m.From = new MailAddress("yourEmail#gmail.com");
m.To.Add(new MailAddress("yourEmail#gmail.com"));
Just so that you can validate that your message is being passed from your function.

Cannot send email through Hotmail / live.com / outlook.com

I have read other answers on the stackoverflow. but none of the solutions work for me.
I'm trying to send email through live.com, but unable to it.
The error message:
mailbox unavailable. The server response was: 5.7.3 requested action aborted;
user not authenticated
or error message:
System.Net.Mail.SmtpException: Service not available,
closing transmission channel.
The server response was: Cannot connect to SMTP server 65.55.176.126
(65.55.176.126:587), NB connect error 1460
The code:
MailMessage mail = new MailMessage();
mail.From = new MailAddress("email#live.com");
mail.To.Add("someone#someone.com");
mail.Subject = "hello";
mail.Body = "awefkljj kawefl";
mail.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("smtp.live.com", 587);
smtp.EnableSsl = true;
smtp.Credentials = new NetworkCredential("email#live.com", "password");
smtp.Send(mail);
Are you able to send the email by using above code?
It works before, last year, but it is no more working now.
I'm not sure what has been changed to live.com email server.
What new settings or parameters should apply?
I ran into an issue where I was unable to send emails using the smtp.live.com SMTP server from certain hosts -- particulary Azure hosts. In my case, the SMTP attempt was from a host that I had never used to sign-in previously, so the attempt was blocked with the 5.7.3 error:
Mailbox unavailable. The server response was: 5.7.3 requested action aborted; user not authenticated
The solution was to browse to the account settings, locate the SMTP request in its recent activity, and select "This was me":
Tested and it works (different host address and a few other property set):
using (var client = new SmtpClient("smtp-mail.outlook.com")
{
Port = 587,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
EnableSsl = true,
Credentials = new NetworkCredential(_sender, _password)
})
{
using (var mail = new MailMessage(_sender, _recipient)
{
Subject = _subject,
Body = _message
})
{
client.Send(mail);
}
}
Also, if the account has two-step verification turned on, you'll have to generate an app password and use that instead.
Your code works for me without any changes with a live.com address. I am able to generate the same exception by simply putting an incorrect password.
I would suggest following checks:
Did the user change password recently? Are you able to login with the credentials provided over the web interface?
if yes, does your program uses the exact same credentials? please note that white space can be your enemy.

asp.net code and mail send via amazon SES

I try to send an email using the amazon SES service. My code is taken from their documantation:
public static void SendWithSMTP(string username, string password, string host, int port)
{
using (var client = new System.Net.Mail.SmtpClient(host, port))
{
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send("from#example.com", "to#example.com", "This is a test subject.", "This is a test email message body.");
}
the problem is that i get the following exception:
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: Authentication required
Is there anyone who had the same or similar problem? Any suggestions on this problem?
this seems that the key you are using is wrong, please confirm this otherwise create a new one.
Ensure that the sender id is also permitted to send email the same can be done from Amazon ses control panel.
In your code you must permit from#example.com to send email

Categories

Resources