send email by smtp and ajax in asp.net mvc - ajax

I am beginner in ASP.NET MVC and trying to get email using smtp server and ajax in webApplication. When user click on the button my code will generate the email which will be send to desired ID. I am successfully getting my all values by debug the code. But, I am not able to receive the email there. Although, I am also getting Success massage from browser. But no email is there, in my desirable account.
Index.cshtml
<div>
<a class="btn btn-primary btn-block btn-lg" onclick="SendEmail()" >Click to send Email</a>
</div>
<script>
var SendEmail = function () {
$.ajax({
type: "Post",
url: "/Feedbacks/SendMailToUser",
success: function (data) {
alert("Success");
}
})
}
</script>
FeedbacksController.cs
public JsonResult SendMailToUser() {
bool result = false;
result = SendEmail("abc#gmail.com", "Test", "<p>Hi abc,<br/>This message is for testing purpose. So don't be upset.<br/>Kind Regards,<br/>abc</p>");
return Json(result, JsonRequestBehavior.AllowGet);
}
public bool SendEmail(string toEmail, string subject, string emailBody) {
try
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 578);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
client.Send(mailMessage);
return true;
}
catch (Exception ex) {
return false;
}
}
}
Web.config
<appSettings>
<add key="SenderEmail" value="abc#gmail.com" />
<add key="SenderPassword" value="********" />
</appSettings>

Try to use SmtpClient without object initializer:
SmtpClient client = new SmtpClient();

I have solved my problem because I was using wrong port number. When I use
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
instead of
SmtpClient client = new SmtpClient("smtp.gmail.com", 578);
I got email there.

you insert wrong port you can use simple 587 and also 25

Related

Sending URL Link to Email ASP.NET WEB API

I'm trying to generate a confirmation link to be sent to the email. The email was sent and received but the link is just not there.
heres the code
[HttpPost]
public async Task<IActionResult> SendEmail(Otp request)
{
randomcode = CreateRandomToken();
var confirmationLink = Url.Action("confirmotp", "Authentication", new {randomcode}, Request.Scheme);
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(_config.GetSection("EmailUsername").Value));
email.To.Add(MailboxAddress.Parse(request.EmailAddress));
email.Subject = "Confirmation Link For" + (request.EmailAddress);
email.Body = new TextPart(TextFormat.Html)
{
Text = "Hello " + request.EmailAddress + ", click on the link: " + confirmationLink
}
using var smtp = new SmtpClient();
smtp.Connect(_config.GetSection("EmailHost").Value, 587, SecureSocketOptions.StartTls);
smtp.Authenticate(_config.GetSection("EmailUsername").Value, _config.GetSection("EmailPassword").Value);
smtp.Send(email);
smtp.Disconnect(true);
return Ok();
}
and this is the email I received :
Hello xxx#gmail.com, click on the link:
the link is just not being read. appreciate any help i can get thank you.
Please try this to create the URL:
Uri uri = new Uri(url);
More details can be found in How to build a Url?

Server-side method does not write to database unless client-side caller is paused/interrupted (via alert)

I am using an Ajax post method to pass a JSON string to a server-side MVC action. The IActionResult method parses the JSON string into an array which is uploaded into SQL Server via Microsoft.Data.SqlClient methods. The IActionResult returns an Ok() result to the caller upon completion.
The anomaly I have observed is that the database upload (server-side) only completes if I pause/interrupt the browser by placing an alert just after the Ajax method (client-side). My code is as follows:
Client-side:
function ExportJSON() {
var myJson = "some JSON stuff goes here";
$.ajax({
type: "POST",
url: "/Dailies/UploadJson/",
dataType: 'json',
data: { jsonString: myJson },
success: function (data) {
console.log(data);
}
});
alert("Your data has been saved.");
}
Server-side action:
[HttpPost]
[ProducesResponseType(StatusCodes.Status200OK)]
public async Task<IActionResult> UploadJson(string jsonString)
{
if (jsonString != null) {
var myJArray = JsonConvert.DeserializeObject<JArray>(jsonString);
TimePunches[] timePunches = myJArray.ToObject<TimePunches[]>();
try
{
string constr = _configuration.GetConnectionString("MYSQLSERVER");
using (SqlConnection sqlConnection = new SqlConnection(constr)) {
await sqlConnection.OpenAsync();
foreach (TimePunches timePunch in timePunches) {
string query = "INSERT INTO TimePunches([Projectid], [CrewLeaderId]) ";
query += "VALUES(#Projectid, #CrewLeaderId) ";
using (SqlCommand cmd = new SqlCommand(query)) {
cmd.Connection = sqlConnection;
cmd.Parameters.AddWithValue("#Projectid", timePunch.Projectid);
cmd.Parameters.AddWithValue("#CrewLeaderId", timePunch.CrewLeaderId);
await cmd.ExecuteNonQueryAsync();
}
}
sqlConnection.Close();
}
}
catch (Exception ex) {
TempData["msg"] = ex.Message;
}
}
return Ok();
}
To reiterate, the server-side action uploads data to the database (as expected) so long as the alert is present in the client-side ExportJSON() method. Conversely, removing the alert causes the database upload to fail.
Any assistance would be greatly appreciated.
I found an answer to this issue. The following link provides an excellent article explaining the nuances of asynchronous JavaScript calls and, in particular, how to manage synchronization issues when using Ajax: https://stackify.com/return-ajax-response-asynchronous-javascript-call/
In my particular case the solution was as simple as adding an async: false qualifier to my Ajax "post" method.

Secure Web API Post Method with Username and Password

I have a Web API service hosted in Microsoft Azure. I need a certain POST method to be only accessible with one unique username and password.
I understand the [Authorize] method does a token based authentication but its not tied to a single username and password. In my app, the web api also does the login authentication, so anyone who registers can access this post method if im not mistaken. (Please correct me if im wrong)
I am new to this could you guide me the right way please.
This is my WebAPI Post method i want to secure access to with specific unique username&pass:
[AllowAnonymous]
[HttpPost, Route("send")]
public async Task<NotificationOutcome> Post([FromBody]string message)
{
string hubName = "myHub";
string hubNameDefaultShared = "myHubNameDefaultShared";
NotificationHubClient hub = NotificationHubClient
.CreateClientFromConnectionString(hubNameDefaultShared, hubName, enableTestSend: true);
string installationId = string.Empty;
var templateParams = new Dictionary<string, string>
{
["messageParam"] = message
};
NotificationOutcome result = null;
if (string.IsNullOrWhiteSpace(installationId))
{
result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
}
else
{
result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
}
return result;
}
And this is how I currently access the POST Method:
var client = new RestClient("myWebApiRouteName");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "46c23eba-8ca6-4ede-b4fe-161473dc063a");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("undefined", messageBody, ParameterType.RequestBody);
try
{
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Issue on sending embedded image to gmail jquery c# mvc

I am facing an issue on sending email. Actually, I am trying to send an email with more text and many images in the body of the mail . I am using jquery and c# controller to make this work out.
The following code explains bit better:
In jquery, am using
$scope.SendEMailNew = function () {
var data = new FormData();
var ToEmail = $("#emailTo").val();
var CcEmail = $("#emailCc").val();
var Subject = $("#emailSubject").val();
var Message = document.getElementById(divID).outerHTML;
data.append("ToEmail", ToEmail);
data.append("CcEmail", CcEmail);
data.append("Subject", Subject);
data.append("Message", Message);
mailsendingIndicator();
$.ajax({
url: ApplicationUrl + 'SendEmail/MailSend',
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
hidemailsendingIndicator();
toastr.clear();
toastr.success("Mail sent successfully", opts);
},
error: function (er) {
hidemailsendingIndicator();
toastr.clear();
toastr.error("Something went wrong", opts);
}
});
In c# mvc controller, i am using
[AcceptVerbs(HttpVerbs.Post)]
public void MailSend(SendEmail MailDetails)
{
string result = string.Empty;
string from = "FromMail#gmail.com";
using (MailMessage mail = new MailMessage(from,MailDetails.ToEmail))
{
mail.Subject = MailDetails.Subject;
mail.Body = MailDetails.Message;
mail.IsBodyHtml = true;
if (!string.IsNullOrEmpty(MailDetails.CcEmail))
mail.CC.Add(MailDetails.CcEmail);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential("FromMail#gmail.com", "Password");
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
}
}
After this code, the email could be sent with embedded images to my official mail id and to my client's mail id but to gmail and to outlook mails, the embedded images not displaying.
Especially, in outlook mails, I am not getting the option to download the image itself. In gmail, i am getting the image as base 64 code. Actually, the image is stored as bytes in database and retrieved to jquery through ajax call. I am facing this issue for long time.
What will be the solution for this kind of issue? Any idea will be a great help
Thanks

Show Custom Message for remote validation success response

I am using remote validation to check the availability of username during registration for my asp.net mvc 3 applicaion (C#).
I am using MVC remote Attribute validation as:
[Remote("IsUserNameAvailable", "User")]
public string UserName { get; set; }
I need to show the message on two conditions:
Show error message "Username not available" - Failure Condition
Show Success message "Username available" - Success Condition
I am able to show the Failure Condition's message without any issue like:
return Json("Username not available", JsonRequestBehavior.AllowGet);
But for Success Condition, I need to send true in response(not with the custom message) as:
return Json(true, JsonRequestBehavior.AllowGet);
How can i show custom message for Success Condition of Remote validation?
see this link...
here
One way to achieve that is to add a custom HTTP response header from the validation action:
public ActionResult IsUserNameAvailable(string username)
{
if (IsValid(username))
{
// add the id that you want to communicate to the client
// in case of validation success as a custom HTTP header
Response.AddHeader("X-ID", "123");
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json("The username is invalid", JsonRequestBehavior.AllowGet);
}
Now on the client we obviously have a standard form and an input field for the username:
#model MyViewModel
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.UserName)
#Html.ValidationMessageFor(x => x.UserName)
<button type="submit">OK</button>
}
and now the last piece of the puzzle is to attach a complete handler to the remote rule on the username field:
$(function () {
$('#UserName').rules().remote.complete = function (xhr) {
if (xhr.status == 200 && xhr.responseText === 'true') {
// validation succeeded => we fetch the id that
// was sent from the server
var id = xhr.getResponseHeader('X-ID');
// and of course we do something useful with this id
alert(id);
}
};
});
Are you able to return an object (which will be serialised to Json)?
Such as:
var answer = new { success = true, message = "Username available" };
return Json(answer, JsonRequestBehavior.AllowGet);
Then you can parse this in the view.
Also, if you do it this way, but the username is NOT available, you could add a few suggested usernames too.
e.g.
// pretend they chose "dave"
List<string> alternativeNames = new List<string>() { "dave1", "dave2" };
var answer = new { success = false, message = "Username not available", alternatives = alternativeNames };
return Json(answer, JsonRequestBehavior.AllowGet);

Resources