I create a method for send Email like:
public async Task SendEmailCC(string body, string subject, List<string> mainRecievers, List<string> receivers)
{
SmtpClient client = new SmtpClient("smtp-mail.outlook.com")
{
UseDefaultCredentials = true,
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("Test#gmail.com", "MyMailPassword")
};
MailMessage mailMessage = new MailMessage { From = new MailAddress("job#test.org") };
foreach (var reciever in mainRecievers)
{
mailMessage.To.Add(reciever);
}
foreach (var item in receivers)
{
mailMessage.CC.Add(item);
}
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.Subject = subject;
await client.SendMailAsync(mailMessage);
}
For test, I send an email to my self, but I didn't get Email. how can I find my problem?
Indeed I don't like answer my question but I found that.
My mail server was google and I used of OutLookSmtp,To this section of my code I have that and I changed. like:
SmtpClient client = new SmtpClient("smtp-mail.outlook.com")
changed to:
SmtpClient client = new SmtpClient("smtp.gmail.com")
After that I get this exception:
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required", than the error might occur due to following cases.
For this issue I try this:
case 1: when the password is wrong
case 2: when you try to login from some App
case 3: when you try to login from the domain other than your time zone/domain/computer (This is the case in most of scenarios when sending mail from code)
There is a solution for each
solution for case 1: Enter the correct password.
solution 1 for case 2: go to security settings at the followig link https://www.google.com/settings/security/lesssecureapps and enable less secure apps . So that you will be able to login from all apps.
solution 2 for case 2:(see https://stackoverflow.com/a/9572958/52277) enable two-factor authentication (aka two-step verification) , and then generate an application-specific password. Use that newly generated password to authenticate via SMTP.
solution 1 for case 3: (This might be helpful) you need to review the activity. but reviewing the activity will not be helpful due to latest security standards the link will not be useful. So try the below case.
solution 2 for case 3: If you have hosted your code somewhere on production server and if you have access to the production server, than take remote desktop connection to the production server and try to login once from the browser of the production server. This will add excpetioon for login to google and you will be allowed to login from code.
But what if you don't have access to the production server. try the solution 3
solution 3 for case 3: You have to enable login from other timezone / ip for your google account.
to do this follow the link https://g.co/allowaccess and allow access by clicking the continue button.
And that's it. Here you go. Now you will be able to login from any of the computer and by any means of app to your google account
Related
I am trying to send a mail in Production with a verification link for a user registration.
For this, I have attached the credentials of the gmail account that sends the mail in my appsettings.json
APPSETTINGS.JSON:
The action of my controller that sends the mail is the following:
[HttpPost]
public async Task<JsonResult> Register(AddUserViewModel model)
{
if (ModelState.IsValid)
{
User user = await _userHelper.AddUserAsync(model, imageId);
if (user == null)
{
return Json("Email repeat");
}
string myToken = await _userHelper.GenerateEmailConfirmationTokenAsync(user);
string tokenLink = Url.Action("ConfirmEmail", "Account", new
{
userid = user.Id,
token = myToken
}, protocol: HttpContext.Request.Scheme);
Response response = _mailHelper.SendMail(model.Username, "App - Confirmación de cuenta", $"<h1>App - Confirmación de cuenta</h1>" +
$"Para habilitar el usuario, " +
$"por favor hacer clic en el siguiente enlace: </br></br>Confirmar Email");
if (response.IsSuccess)
{
return Json("Email send");
}
string message = response.Message;
return Json(message);
}
return Json("Model invalid");
}
The sendEmail method that returns a Response is as follows:
public Response SendMail(string to, string subject, string body)
{
try
{
string from = _configuration["Mail:From"];
string smtp = _configuration["Mail:Smtp"];
string port = _configuration["Mail:Port"];
string password = _configuration["Mail:Password"];
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress(from));
message.To.Add(new MailboxAddress(to));
message.Subject = subject;
BodyBuilder bodyBuilder = new BodyBuilder
{
HtmlBody = body
};
message.Body = bodyBuilder.ToMessageBody();
using (SmtpClient client = new SmtpClient())
{
client.CheckCertificateRevocation = false;
client.Connect(smtp, int.Parse(port), false);
client.Authenticate(from, password);
client.Send(message);
client.Disconnect(true);
}
return new Response { IsSuccess = true };
}
catch (Exception ex)
{
return new Response
{
IsSuccess = false,
Message = ex.Message,
Result = ex
};
}
}
The error message is the following:
"534: 5.7.14
\u003Chttps://accounts.google.com/signin/continue?sarp=1\u0026scc=1\u0026plt=AKgnsbt\n5.7.14
GCim6bqtaJeANyyQ0NvegYJS8qnYbDSCz3M0IMvB-rgIFdr1rLrIl1wbt4DkimTvNMLDl\n5.7.14
8dSGZxGuAWmDwX6gPD1T_lJ3U1e0G8EEAu6Lgt3p5gk1yJpr85Pm2mBN9nO4G33Y\u003E\n5.7.14
Please log in via your web browser and then try again.\n5.7.14 Learn
more at\n5.7.14 https://support.google.com/mail/answer/78754
t15sm12262168pjy.17 - gsmtp"
Am I sending correctly?
Should I change any gmail settings?
In the development environment the sending works without problems, any help or suggestion for me?
Directly using providers like Gmail, Outlook and similar ones is not advised because they perform checks that can disrupt your code just like you're seeing here.
This can happen without previous notice. And believe me, it will happen from time to time.
Common issues
Web-based OAuth flow
Most providers (Gmail specially) now enforce a web-based flow, from the most recent OAuth/OpenID specifications, for safer authentication/authorization.
This would be my first guess: Gmail auth (which is browser based) is simply blocking your login attempt because it wants you to use a browser and not simply submit your credentials.
There's a lot of background work done by IAM solutions to help protect users, namely called risk assessment. This, in time, might require both captcha and MFA challenges to be sent back to the user, so an API would not really work on this, that's another reason why they focus on browsers and not simply on getting the correct credentials.
Bot prevention
Email providers (specially Gmail) are great at detecting possible bots and this would be my second guess: it detected your service as a bot and put a temporary hold on your account to "protect you".
It's possible that this works on lower environments (aka: your machine and/or testing environment) and not production because of the server bot prevention system, which typically inspects IP address, user agent from the browser (if any), API call rate, authentication rate and others.
Usage rate limit
Yet another thing that can block you when doing such integration is the rate limit. Typically, 500 messages/month.
Possible solutions
Workaround - still using Gmail
To workaround this and still use Gmail, this is the way to go:
https://support.google.com/accounts/answer/185833?hl=en
It's called application password and is a different password that you generate on your account for a particular app to be allowed signing in. That will skip the OAuth and the bot validation (at least on most cases).
Proper long-term solution
The only reliable way to have this fixed is to use a proper send email service. Something like Amazon Simple Email Service, Sendgrid, or a bunch of others out there.
That's because they are created to be used by API calls and won't get in your way. You can set-up your own domain there, including SPF and DKIM keys so your recipient's email server will recognize the message as safe and indeed as coming from your (and not a random SPAM).
I have to send mails using my web application. Given the below code showing The SMTP server requires a secure connection or the client was not authenticated. The server response was:
5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM.
Help me to find a proper solution. Thank you.
Code:
protected void btnsubmit_Click(object sender, EventArgs e)
{
Ticket_MailTableAdapters.tbl_TicketTableAdapter tc;
tc = new Ticket_MailTableAdapters.tbl_TicketTableAdapter();
DataTable dt = new DataTable();
dt = tc.GetEmail(dpl_cate.SelectedValue);
foreach (DataRow row in dt.Rows)
{
string eml = (row["Emp_Email"].ToString());
var fromAddress = "emailAddress";
var toAddress = eml;
const string fromPassword = "*****";
string body = "Welcome..";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.office365.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.UseDefaultCredentials = false;
smtp.Timeout = 600000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, subject, body);
}
}
}
#Reshma- In case you have not figured it yet, here are below things that I tried and it solved the same issue.
Make sure that NetworkCredentials you set are correct. For example in my case since it was office SMTP, user id had to be used in the NetworkCredential along with domain name and not actual email id.
You need to set "UseDefaultCredentials" to false first and then set Credentials. If you set "UseDefaultCredentials" after that it resets the NetworkCredential to null.
Hope it helps.
You seem to be passing the From address as emailAddress, which is not a proper email address. For Office365 the From needs to be a real address on the Office365 system.
You can validate that if you hardcode your email address as the From and your Office 365 password.
Don't leave it there though of course.
I spent way too much time on this and the solution was super simple.
I had to use my "MX" as the host and port 25.
var sClient = new SmtpClient("domain-com.mail.protection.outlook.com");
var message = new MailMessage();
sClient.Port = 25;
sClient.EnableSsl = true;
sClient.Credentials = new NetworkCredential("user", "password");
sClient.UseDefaultCredentials = false;
message.Body = "Test";
message.From = new MailAddress("test#test.com");
message.Subject = "Test";
message.CC.Add(new MailAddress("dude#good.com"));
sClient.Send(message);
I use to have the same problem.
Add the domain solved it..
mySmtpClient.Credentials = New System.Net.NetworkCredential("email#domain.com", "password", "domain.com")
In my case, 2 Factor Authentication was turned on for the FROM account in Office 365. Once that was turned off, the email sent successfully.
Main two reasons only as mentioned in above comments
NetworkCredentials you set should be correct. Verify with try actually signing into the account.
You need to set UseDefaultCredentials to false first and then set Credentials
Or
Put smtp.UseDefaultCredentials = false; above the smtp.Credentials assignment.
In my case, I followed the following 3 steps and it worked.
If you are getting one of the following errors:
535 5.7.3 Authentication unsuccessful
5.7.57 Client not authenticated to send mail
There are a few things you should check:
Enable Client SMTP submission on the licensed mailbox being used:
From Microsoft 365 Admin Center, go to Active Users and select the user.
Go to the Mail tab.
In the Email apps section, select Manage email apps.
Verify that the Authenticated SMTP setting is checked (enabled).
Select Save changes.
Disable Multi-Factor Authentication (MFA) on the licensed mailbox being used:
In the Microsoft 365 admin center, in the left navigation menu, choose Users > Active users.
On the Active user's page, choose Multi-Factor Authentication.
On the Multi-Factor Authentication page, select the user and disable the Multi-Factor Authentication status.
Disable the Azure Security Defaults by toggling the Enable Security Defaults to No:
Sign in to the Azure portal as a Security administrator, Conditional Access administrator, or Global administrator.
Browse to Azure Active Directory > Properties.
Select Manage security defaults.
Set the Enable security defaults to toggle to No.
Select Save.
Microsoft Reference Link
This is an old question but since this is the first result in google for this error, I thought I would update my progress in this issue.
I spent way too may hours on this issue. In the end I had to change my Office 365 account's password few times until my code succeeded in sending emails.
Didn't have to make any changes in code.
If you are using office 365 follow this steps:
check the password expiration time using Azure power shell :Get-MsolUser -All | select DisplayName, LastPasswordChangeTimeStamp
Change the password using a new password (not the old one). You can eventually go back to the old password but you need to change it twice.
Hope it helps!
Probably the password of the account that you trying to send e-mail is expired. Just check your password policy expire date.
In my case I was using the MailMessage constructor that takes two strings (to, from) and getting the same error. When I used the default constructor and then added a MailAddress object to the To property of the MailMessage it worked fine.
If you reorder your code this way, it should work:
SmtpClient client = new SmtpClient();
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(mailOut, pswMailOut);
client.Port = 587; // 25 587
client.Host = "smtp.office365.com";
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.EnableSsl = true;
MailMessage mail = new MailMessage();
mail.From = new MailAddress(mailOut, displayNameMailOut);
mail.To.Add(new MailAddress(mailOfTestDestine));
mail.Subject = "A special subject";
mail.Body = sb.ToString();
client.Send(mail);
I changed the Office365 password and then tried to send a test email and it worked like a charm for me.
I used the front end (database mail option) and settings as smtp.office365.com port number 587 and checked the secure connection option. use basic authentication and store the credentials. Hope this turns out useful for someone.
In my situation, our IT department made MFA mandatory for our domain. This means we can only use option 3 in this Microsoft article to send email. Option 3 involves setting up an SMTP relay using an Office365 Connector.
Try resetting your password for the email used. Had similar issue, and got it fixed only after changing password.
I had similar issue. please read this microsoft support article.
specially this section.
For us it failed this way but only from the servers (Azure) not from the developer machines.
It turned out that the Office365 admin required MFA when accessing office365 from outside of the corporate country.
Our production server was in Ireland but the dev machines where in Sweden -> confusion... The admin turned of MFA for our sending account -> works.
Started working after adding property:
mail.smtp.starttls.enable=true
Using:
mail.smtp.host=smtp.office365.com
mail.smtp.port=587
mail.transport.protocol=smtp
mail.smtp.auth=true
mail.smtp.starttls.enable=true
mail.smtp.user=xxx#example.com
mail.smtp.password=xxx
mail.smtp.from=yyy#example.com
Set the User default credentials to true:
smtp.UseDefaultCredentials = True;
Before that, input your credential:
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
This should work fine.
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.
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.
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.