asp.net mvc send email error: unable to send an email - asp.net-mvc

I have mvc web app sending an email when new user gets created with following code:
private static void SendMail(User user)
{
string ActivationLink = "http://localhost/Account/Activate/" +
user.UserName + "/" + user.NewEmailKey;
var message = new MailMessage("ashu#gmail.com", user.Email)
{
Subject = "Activate your account",
Body = ActivationLink
};
var client = new SmtpClient("localhost");
client.UseDefaultCredentials = false;
client.Send(message);
}
What's wrong with my code please tell me.
ERROR : Failure sending mail. {"Unable to connect to the remote server"}
Smtp configuration :

Here are the likely causes of this error:
1 You are not supplying the correct authentication details
2 The port is blocked, for example by a firewall
In your example, I notice you are not specifying the port when you create your SmtpClient - it may help to specify it.

Gmail opens in port 587, and u need to enable ssl.
Try following code.
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(<fromAddress>, <fromPassword>)
};
using (var message = new MailMessage(<fromAddress>, <toAddress>)
{
Subject = <subject>,
Body = <body>
})
{
smtp.Send(message);
}

Related

asp.net mvc SMS Service using twilio

i using twilio to send sms verification code when add phone Number to account
and when i debug my app the usermanager.smsSerivice is null while i regesterd it in identitiyconfig here is my code
// Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
// You can write your own provider and plug it in here.
manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider<ApplicationUser>
{
MessageFormat = "Your security code is {0}"
});
manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider<ApplicationUser>
{
Subject = "Security Code",
BodyFormat = "Your security code is {0}"
});
manager.EmailService = new EmailService();
manager.SmsService = new SmsService();
var dataProtectionProvider = options.DataProtectionProvider;
if (dataProtectionProvider != null)
{
manager.UserTokenProvider =
new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
}
return manager;
You can call SmsService without a manager like below:
var message = new IdentityMessage
{
Destination = phoneNumber,
Body = "Your verification code is: " + code
};
await new SmsService().SendAsync(message);

Form data to an email address in asp.net core

What is the easiest way to have form data sent to an email address , in an asp.net core app? I have tried to send an email from my outlook account to gmail one wit Mailkit, but i keep getting an error AuthenticationException: AuthenticationInvalidCredentials , even if my credentials are corect.
var message = new MimeMessage();
message.From.Add(new MailboxAddress("Joey Tribbiani", "joey#outlook.com"));
message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "Chandler#gmail.com"));
message.Subject = "How you doin'?";
message.Body = new TextPart("plain")
{
Text = #"Hey Chandler"
};
using (var client = new SmtpClient())
{
// For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
client.ServerCertificateValidationCallback = (s, c, h, e) => true;
client.Connect("smtp.outlook.com", 587, false);
// Note: since we don't have an OAuth2 token, disable
// the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove("XOAUTH2");
// Note: only needed if the SMTP server requires authentication
client.Authenticate("username", "*************");
client.Send(message);
client.Disconnect(true);
}

"Unrecognized SSL message, plaintext connection" during send mail using grails async mail api

I am trying to send mail using Grails Async Mail API
When I tried for Gmail using below configuration :
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "xxxx#gmail.com"
password = "xxxx"
props = ["mail.smtp.auth":"true",
"mail.smtp.socketFactory.port":"465",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"false"]
}
}
in config.groovy, I was able to send mail. When I changed above configuration for a specific mail server as below :
grails {
mail {
host = "xxx"
port = 25
username = "xxx"
props = ["mail.smtp.auth":"false",
"mail.smtp.socketFactory.port":"25",
"mail.smtp.socketFactory.class":"javax.net.ssl.SSLSocketFactory",
"mail.smtp.socketFactory.fallback":"true",
"mail.smtp.starttls.enable": "false",
"mail.smtp.starttls.required": "false"]
}
}
I am getting below error :
javax.mail.MessagingException: Could not connect to SMTP host: xxx, port: 25;
nested exception is:
javax.net.ssl.SSLException: Unrecognized SSL message, plaintext connection?
Please provide me some hint, what I am doing wrong in above case.
You can try to do simply following and it should work for you
grails {
mail {
host = "xxx"
port = 25
username = "xxx"
props = ["mail.smtp.auth":"false",
"mail.smtp.socketFactory.port":"25",
"mail.smtp.starttls.enable": "true"]
}
}

Umbraco mvc Please help me with the HandleForgottenPassword

I have been ask this question for few days but no answer, i am very new to Umbraco and junior of programming.i am working on trying to get admin user to reset password when they are forget their password and sent them an email to reset their password, after they
reset they password they will get a new password to login when they
login they we will force them to change password, so for now i am
struggle on the HandleForgottenPassword, getting
Object reference not set to an instance of an object. on the yellow line,
enter code here
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult HandleForgottenPassword(ForgottenPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return PartialView("ForgottenPassword", model);
}
//Find the member with the email address
var name =Member.GetMemberFromLoginName(model.LoginName);
var findMember = Member.GetMemberFromEmail(model.EmailAddress);
if (findMember != null)
{
//We found the member with that email
//Set expiry date to
DateTime expiryTime = DateTime.Now.AddMinutes(15);
//Lets update resetGUID property
// findMember.getProperty("resetGUID").Value = expiryTime.ToString("ddMMyyyyHHmmssFFFF");
//Save the member with the up[dated property value
findMember.Save();
//Send user an email to reset password with GUID in it
EmailHelper email = new EmailHelper();
email.SendResetPasswordEmail(findMember.Email, expiryTime.ToString("ddMMyyyyHHmmssFFFF"));
}
else
{
ModelState.AddModelError("ForgottenPasswordForm.", "No member found");
return PartialView("ForgottenPassword", model);
}
return PartialView("ForgottenPassword", model);
}
please help with sending email ( using EmailHelper from the package)
private const string SendGridUsername = "sendGridUsername";
private const string SendGridPassword = "sendGridPassword";
private const string EmailFromAddress = "you#yoursite.com";
public void SendResetPasswordEmail(string memberEmail, string resetGUID)
{
//Send a reset email to member
// Create the email object first, then add the properties.
var myMessage = SendGrid.GetInstance();
// Add the message properties.
myMessage.From = new MailAddress(EmailFromAddress);
//Send to the member's email address
myMessage.AddTo(memberEmail);
//Subject
myMessage.Subject = "Umb Jobs - Reset Your Password";
//Reset link
string baseURL = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, string.Empty);
var resetURL = baseURL + "/reset-password?resetGUID=" + resetGUID;
//HTML Message
myMessage.Html = string.Format(
"<h3>Reset Your Password</h3>" +
"<p>You have requested to reset your password<br/>" +
"If you have not requested to reste your password, simply ignore this email and delete it</p>" +
"<p><a href='{0}'>Reset your password</a></p>", resetURL);
//PlainText Message
myMessage.Text = string.Format(
"Reset your password" + Environment.NewLine +
"You have requested to reset your password" + Environment.NewLine +
"If you have not requested to reste your password, simply ignore this email and delete it" +
Environment.NewLine + Environment.NewLine +
"Reset your password: {0}",
resetURL);
// Create credentials, specifying your user name and password.
var credentials = new NetworkCredential(SendGridUsername, SendGridPassword);
// Create an SMTP transport for sending email.
var transportSMTP = SMTP.GetInstance(credentials);
// Send the email.
transportSMTP.Deliver(myMessage);
}
when i try to sending the email i got this erro
Unable to read data from the transport connection: net_io_connectionclosed.
here is my *web.config *
<system.net>
<mailSettings>
<smtp>
<network host="127.0.0.1" userName="username" password="password" />
</smtp>
</mailSettings>
</system.net>
Thank you in advance. MC
If you are on a residential internet connection quite often your ISP will block outgoing email sends by blocking all outbound connections to port 25. This is quite common in the US. Try connecting to a local email server over TCP/IP, or to one on your own internal network.

Confused with the SmtpClient.UseDefaultCredentials Property

In my MVC4 application, I'm using the SmtpClient to send out email via Gmail's smtp.gmail.com SMTP server.
I've configured my Web.Config file with the following settings:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network enableSsl="true"
defaultCredentials="false"
host="smtp.gmail.com"
port="587"
userName="xxMyUserNamexx#gmail.com"
password="xxMyPasswordxx" />
</smtp>
</mailSettings>
</system.net>
The method that uses the SmtpClient and sends an email message looks like:
public void SendMail(string fromDisplayName, string fromEmailAddress, string toEmailAddress, string subject, string body)
{
MailAddress from = new MailAddress(fromEmailAddress, fromDisplayName);
MailAddress to = new MailAddress(toEmailAddress);
MailMessage mailMessage = new MailMessage(from, to);
mailMessage.Body = body;
mailMessage.Subject = subject;
SmtpClient client = new SmtpClient();
//client.UseDefaultCredentials = false;
client.Send(mailMessage);
}
The code above works as expected and is fine. What confuses me is the commented line client.UseDefaultCredentials = false; - If I were to uncomment that line, I'll receive an exception message that states:
The SMTP server requires a secure connection or the client was not
authenticated. The server response was: 5.5.1 Authentication Required.
What's more is, it doesn't matter if I set the UseDefaultCredentials property to true or false, I'll still receive the exception message. The only way for me to avoid the exception message is to remove the line altogether.
Is this behavior normal? Can you explain why I'm receiving the exception message?
So why would me explicitly setting the property to false throw an exception?
The reason for this is because the setter for UseDefaultCredentials sets the Credentials property to null if you set it to false, or it sets it to the CredentialCache.DefaultNetworkCredentials property if set to true. The DefaultNetworkCredentials property is defined by MSDN as:
The credentials returned by DefaultNetworkCredentials represents the authentication credentials for the current security context in which the application is running. For a client-side application, these are usually the Windows credentials (user name, password, and domain) of the user running the application. For ASP.NET applications, the default network credentials are the user credentials of the logged-in user, or the user being impersonated.
When you set UseDefaultCredentials to true, it's using your IIS user, and I'm assuming that your IIS user does not have the same authentication credentials as your account for whatever SMTP server you're using. Setting UseDefaultCredentials to false null's out the credentials that are set. So either way you're getting that error.
Here's a look at the setter for UseDefaultCredentials using dotPeek:
set
{
if (this.InCall)
{
throw new InvalidOperationException(
SR.GetString("SmtpInvalidOperationDuringSend"));
}
this.transport.Credentials = value
? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials
: (ICredentialsByHost) null;
}
I was getting the same message and it was driving me crazy. After reading this thread I realized that the order mattered on setting my credentials. This worked:
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(smtpSettings.Username, smtpSettings.Password);
While this generated the error you describe:
client.Credentials = new NetworkCredential(smtpSettings.Username, smtpSettings.Password);
client.UseDefaultCredentials = false;
This is just an FYI to anybody else having the same problem.
This option will set the client to use the default credentials of the currently logged in user
If you set it to true, then it will try to use the user's credentials. If you set it to false, then it will use the values explicitly set for the Credentials property of the client, and if they aren't explicitly set, then it will try to connect anonymously as you are seeing.
This is how we can create SMTP Client with or without NetworkCredentials. I am using this code to send emails. We should use client.UseDefaultCredentials only when we are not passing credentials and going by default.
private SmtpClient InitializeSMTPClient()
{
var client = new SmtpClient(_smtpServer, _smtpPort);
client.UseDefaultCredentials = _useSMTPDefaultCredentials;
if (_useSMTPDefaultCredentials)
return client;
var credentials = new NetworkCredential(_smtpUsername, _smtpPassword);
client.Credentials = credentials;
return client;
}
SMTPEmailResult SendSMTPEmail(List<string> to_email, List<string> ccEmails, string subject, string message)
{
try
{
using (var client = InitializeSMTPClient())
{
var mail_message = GetMailMessage(to_email, ccEmails, subject, message);
log.Debug("Sending SMTP email.");
client.Send(mail_message);
log.Debug("SMTP email sent successfully.");
return SMTPEmailResult.SendSuccess;
}
}
catch (Exception ex)
{
log.Error(ex.Message, ex);
return SMTPEmailResult.SendFailed;
}
}

Resources