Asked by:
how to send email by ajax

Question
-
User-1634604574 posted
i have this code i want to change this code to json result and ajax to send email can anyone change it for me?
without entity framework please
public bool SendEMail(string smtpHost ="smtp.gmail.com", int port = 587, string senderMail , string senderPass, ArrayList mailToArr, string subject, bool isHtml, string body) { try { SmtpClient smtpClient = new SmtpClient(smtpHost, port); smtpClient.UseDefaultCredentials = false;// true; smtpClient.Credentials = new System.Net.NetworkCredential(senderMail, senderPass); smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network; smtpClient.EnableSsl = true; MailMessage mail = new MailMessage(); mail.From = new MailAddress(senderMail); for (int i = 0; i < mailToArr.Count; i++) { mail.To.Add(new MailAddress((string)mailToArr[i])); } mail.Subject = subject; //mail.CC.Add(new MailAddress("MyEmailID@gmail.com")); mail.Body = body; mail.IsBodyHtml = isHtml; mail.Priority = MailPriority.Normal; smtpClient.Send(mail); return true; } catch (Exception ex) { return false; // write exception on server log } }
Monday, September 23, 2019 5:45 AM
All replies
-
User753101303 posted
Hi,
The general idea to return json from an MVC controller is https://chsakell.com/2013/06/08/retrieve-json-data-from-mvc-controllers-in-asp-net-mvc/ (ie return a JsonResult and use the Json method to tell which value should be returned)
More likely you don't want the id/password to be transmitted from the client side. Also turning an exception into a return code (or just a bool) is considered bad( the caller could ignore the returned value and won't really know what happened).
Monday, September 23, 2019 11:25 AM -
User475983607 posted
zhyanadil.it@gmail.com
i have this code i want to change this code to json result and ajax to send email can anyone change it for me?This question indicates that you do not understand the fundamentals. As explained in your similar thread AJAX does NOT send email. AJAX is an XHR (HTTP GET or POST) request sent from a JavaScript application. Your AJAX function should send an HTTP POST to an MVC action. This request should contain input parameters from the user. The following code is an AJAX request example that shows how to send an HTTP POST to the Index action.
Actions
public class AjaxController : Controller { // GET: Ajax [HttpGet] public ActionResult Index() { return View(); } //POST: AJax [HttpPost] public ActionResult Index(SmtpParameters input) { return Json(input); }
Model
public class SmtpParameters { public string SenderMail { get; set;} public string SenderPass { get; set; } = "Password"; public ArrayList MailTo { get; set; } public string Subject { get; set; } public bool IsHtml { get; set; } public string Body { get; set; } public string SmtpHost { get; set; } = "smtp.gmail.com"; public int Port { get; set; } = 587; }
View
@{ ViewBag.Title = "Index"; } <h2>Index</h2> <form> <div> <input type="text" name="SenderMail" id="SenderMail" value="SenderMail@eamil.com" /> </div> <div> <input type="text" name="MailTo" id="MailTo" value="MailTo@mail.com" /> </div> <div> <input type="text" name="Subject" id="Subject" value="Subject" /> </div> <div> <input type="checkbox" name="IsHtml" id="IsHtml" checked /> </div> <div> <input type="text" name="Body" id="Body" value="Body" /> </div> <div> <input id="Button1" type="button" value="button" /> </div> </form> @section scripts { <script> $('#Button1').click(function (e) { e.preventDefault(); var data = { SenderMail: $('#SenderMail').val(), MailTo: $('#MailTo').val(), Subject: $('#Subject').val(), IsHtml: $('#IsHtml').is(':checked'), Body: $('#Body').val(), }; $.ajax({ url: '/ajax/index', type: "POST", data: JSON.stringify(data), contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { console.log(data); }, failure: function (errMsg) { console.log(errMsg); } }); }); </script> }
Once you have UI working as expected, then all you have to do is call your SendEMail method.
[HttpPost] public ActionResult Index(SmtpParameters input) { bool results = SendEMail(input.SenderMail, input.SenderPass, new ArrayList() { input.MailTo }, input.Subject, input.IsHtml, input.Body, input.SmtpHost, input.Port); return Json(results); }
Also, your SendEMAil method has syntax errors and does not compile. You'll need to change the method signature.
public bool SendEMail(string senderMail, string senderPass, ArrayList mailToArr, string subject, bool isHtml, string body, string smtpHost = "smtp.gmail.com", int port = 587)
Keep in mind, the code above is an example of sending an AJAX POST and how to call a method. You still need to design a solution that meets your unknown requirements. You also need to test the SMTP method. Feel free to modify the code as needed.
Monday, September 23, 2019 11:37 AM -
User-1634604574 posted
why it doesn't send email are checked your code?
Monday, September 23, 2019 11:57 AM -
User475983607 posted
zhyanadil.it@gmail.com
why it doesn't send email are checked your code?I have no idea. You did not post your code. If you just copied my code and expected it to send an email then you are mistaken. You need to an valid SMTP host, username, password, etc.
I'm a little confused. You provided the SendEMail() method. I simply showed how to send an AJAX POST and call your SendEMail() method. Is there a reason why you are unable to debug your code? Frankly, your code is poorly designed and you should clean up the code and do some testing.
I provided sample SMTP code in your similar thread. Anyway, the official SMTP docs work for me. All I did was use my SMTP setting.
Monday, September 23, 2019 12:13 PM -
User-1634604574 posted
i used this
smtp.gmail.com
Monday, September 23, 2019 12:26 PM -
User753101303 posted
Are you sure you don't have an exception when this code runs? Even before changing anything I would suggest to check that your code can really send a mail without any error.
Check the return result or even just get rid for now of your try/catch.
Edit: knowing you used smtp.gmail.com doesn't help. Always start from the actual problem that happens when your code runs. For now I suspect you have an exception. You tested the returned value (if not it is precisely why transforming an exception into a result code you may or may not test is considered bad, it makes quite easy to just ignore a possible error)
If I remember with gmail you have now to enable https://support.google.com/accounts/answer/6010255?hl=en if using this authentication approach.
Monday, September 23, 2019 12:29 PM -
User-1634604574 posted
i dont have any error and exception
main controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Globalization;
using System.Web.Security;
using System.Threading;
using System.Net.Mail;
using System.Net;
using System.Text;
using send_email.Models;
using System.Collections;namespace send_email.Controllers
{
public class MainController : Controller
{
// GET: Main
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(SmtpParameters input)
{bool results = SendEMail(input.SenderMail,
input.SenderPass,
new ArrayList() { input.MailTo },
input.Subject,
input.IsHtml,
input.Body,
input.SmtpHost,
input.Port);return Json(results);
}//private bool SendEMail(string senderMail, string senderPass, ArrayList arrayList, string subject, bool isHtml, string body, string smtpHost, int port)
//{
// throw new NotImplementedException();
//}public bool SendEMail(string senderMail,
string senderPass,
ArrayList mailToArr,
string subject,
bool isHtml,
string body,
string smtpHost = "smtp.elasticemail.com",
int port = 587)
{
return true;
throw new NotImplementedException();
}public string emailsend(EmailClass ec)
{string To = ec.To;
string Body = ec.Body;
string Subject = ec.Subject;MailMessage mm = new MailMessage();
mm.From = new MailAddress("zhyanadil.it@gmail.com");
mm.Subject = Subject;
mm.Body = Body;
mm.To.Add(To);
mm.IsBodyHtml = false;
SmtpClient smtp = new SmtpClient("smtp.elasticemail.com");
smtp.Port = 587;
smtp.UseDefaultCredentials = true;
smtp.EnableSsl = true;
smtp.Credentials = new System.Net.NetworkCredential("zhyanadil.it@gmail.com", "password");
smtp.Send(mm);
return "The mail has been sent to" + ec.To.ToString();}
}
}=================================
index view
@{
ViewBag.Title = "Index";
}<h2>Index</h2>
<form>
<div>
<input type="text" name="SenderMail" id="SenderMail" value="SenderMail@eamil.com" />
</div>
<div>
<input type="text" name="MailTo" id="MailTo" value="MailTo@mail.com" />
</div>
<div>
<input type="text" name="Subject" id="Subject" value="Subject" />
</div>
<div>
<input type="checkbox" name="IsHtml" id="IsHtml" checked />
</div>
<div>
<input type="text" name="Body" id="Body" value="Body" />
</div>
<div>
<input id="Button1" type="button" value="button" />
</div>
</form>@section scripts {
<script>
$('#Button1').click(function (e) {
e.preventDefault();var data = {
SenderMail: $('#SenderMail').val(),
MailTo: $('#MailTo').val(),
Subject: $('#Subject').val(),
IsHtml: $('#IsHtml').is(':checked'),
Body: $('#Body').val(),
};$.ajax({
url: '/Main/index',
type: "POST",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
console.log(data);
},
failure: function (errMsg) {
console.log(errMsg);
}
});
});
</script>
}=========================================
class
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;namespace send_email.Models
{
public class SmtpParameters
{
public string SenderMail { get; set; }
public string SenderPass { get; set; } = "Password";
public ArrayList MailTo { get; set; }
public string Subject { get; set; }
public bool IsHtml { get; set; }
public string Body { get; set; }
public string SmtpHost { get; set; } = "smtp.gmail.com";
public int Port { get; set; } = 587;
}
}Monday, September 23, 2019 12:37 PM -
User753101303 posted
You don't debug code by reading it and trying to guess which wrong thing could possibly happen (often a lot) but rather you start by looking at what actually happens when your code runs.
Here you took care of writing to the console so use F12 Network and F12 Console to see what happens for your Ajax call and which result you get if the Ajax call happens...
Edit: when you want to show code you have a {;} icon in the toolbar which better show your code:
// GET: Main public ActionResult Index() { return View(); }
It seems your current SendEMail method does nothing else than returning true ? So could it just work fine and do what you asked for ie doing nothing at all ?
Monday, September 23, 2019 12:51 PM -
User475983607 posted
i dont have any error and exceptionOf course not! The SEndEMail() method return true. From my perspective it seems you are not making the slightest effort to debug your own code and just posting it on the forum for other to debug.
[HttpPost] public ActionResult Index(SmtpParameters input) { bool results = SendEMail(input.SenderMail, input.SenderPass, new ArrayList() { input.MailTo }, input.Subject, input.IsHtml, input.Body, input.SmtpHost, input.Port); return Json(results); } public bool SendEMail(string senderMail, string senderPass, ArrayList mailToArr, string subject, bool isHtml, string body, string smtpHost = "smtp.elasticemail.com", int port = 587) { return true; throw new NotImplementedException(); }
Monday, September 23, 2019 1:37 PM