MVC Contact Form with Email - asp.net

I wonder if someone can please help with a MVC Contact Form which send an Email on submission? I think I have most elements setup, but for some reason the form appear to be sending (takes ages) then just returns back to the form and no email is received.
MailModels.cs:
namespace WebApplication1.Models
{
public class MailModels
{
public string Name { get; set; }
public string Email { get; set; }
public string Telephone { get; set; }
public string Message { get; set; }
}
}
Contact.cshtml:
#using (Html.BeginForm("Contact", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #id = "contact-form", role = "form" }))
{
#Html.ValidationSummary()
<fieldset>
<div class="form-div-1">
<label class="name">
#Html.TextBoxFor(m => m.Name, new { #placeholder = "Name *", #type = "text" })
</label>
</div>
<div class="form-div-2">
<label class="email">
#Html.TextBoxFor(m => m.Email, new { #placeholder = "Email Address *", #type = "email" })
</label>
</div>
<div class="form-div-3">
<label class="phone notRequired">
#Html.TextBoxFor(m => m.Telephone, new { #placeholder = "Telephone Number", #type = "text" })
</label>
</div>
<div>
<label class="message">
#Html.TextAreaFor(m => m.Message, new { #placeholder = "Message *" })
</label>
</div>
<div class="button-wrapper">
<input type="submit" value="Send" name="submit" class="button"> <input type="reset" value="Reset" name="MFReset" class="button"><span>* Required Fields</span>
</div>
</fieldset>
}
HomeController.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using WebApplication1.Models;
using System.Text;
namespace WebApplication1.Controllers
{
public class HomeController : Controller
{
public ActionResult Contact()
{
ViewBag.Message = "Test Form";
return View();
}
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
StringBuilder message = new StringBuilder();
MailAddress from = new MailAddress(e.Email.ToString());
message.Append("Name: " + e.Name + "\n");
message.Append("Email: " + e.Email + "\n");
message.Append("Telephone: " + e.Telephone + "\n\n");
message.Append(e.Message);
MailMessage mail = new MailMessage();
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.mail.yahoo.com";
smtp.Port = 465;
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("yahooaccount", "yahoopassword");
smtp.Credentials = credentials;
smtp.EnableSsl = true;
mail.From = from;
mail.To.Add("yahooemailaddress");
mail.Subject = "Test enquiry from "+e.Name;
mail.Body = message.ToString();
smtp.Send(mail);
}
return View();
}
Banging my head against a brickwall with this one, any help would be much appreciated :-)

Sending an email will take time. It should be a thread. Put your code in a function. And make the following changes:
public void SendEmail(string toAddress, string fromAddress,
string subject, string message)
{
try
{
using (var mail = new MailMessage())
{
const string email = "username#yahoo.com";
const string password = "password!";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = message;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient(
"smtp.mail.yahoo.com", 465))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
//dispose the client
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex)
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusy ||
status == SmtpStatusCode.MailboxUnavailable)
{
Response.Write("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//resend
//smtpClient.Send(message);
}
else
{
Response.Write("Failed to deliver message to {0}",
t.FailedRecipient);
}
}
}
catch (SmtpException Se)
{
// handle exception here
Response.Write(Se.ToString());
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
Call that function in your controller:
[HttpPost]
public ActionResult Contact(MailModels e)
{
if (ModelState.IsValid)
{
//prepare email
var toAddress = "someadress#yahoo.co.uk";
var fromAddress = e.Email.ToString();
var subject = "Test enquiry from "+ e.Name;
var message = new StringBuilder();
message.Append("Name: " + e.Name + "\n");
message.Append("Email: " + e.Email + "\n");
message.Append("Telephone: " + e.Telephone + "\n\n");
message.Append(e.Message);
//start email Thread
var tEmail = new Thread(() =>
SendEmail(toAddress, fromAddress, subject, message));
tEmail.Start();
}
return View();
}
If you dont get email, check your spam folder

You need to implement Producer Consumer pattern for this use case. You will have to have one thread running dedicated to emails. This thread will read from the queue & send emails. In the contact method, you will just add to the queue. Its not a good idea to do time consuming operations in controller methods.
C# producer/consumer

settings to web.config
<system.net>
<mailSettings>
<smtp from="you#outlook.com">
<network host="smtp-mail.outlook.com"
port="587"
userName="you#outlook.com"
password="password"
enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
Port 465 or 587?
Lots of code samples for Gmail feature port 465 but most people cannot get this to work. When they revert to port 587, their email suddenly works. According to Gmail's documentation SSL is required if you specify port 465. Many people think that setting EnableSsl to true achieves this, but in fact, it means that your app must be running under https. When you set EnableSsl to true, you actually switch TLS on, which is required for port 587. Https is not supported by the SmtpClient object. For more details, read the Remarks section of the docs on MSDN.

public void SendEmail(string toAddress, string fromAddress,string subject, string message)
{
try
{
using (var mail = new MailMessage())
{
const string email = "username#yahoo.com";
const string password = "password!";
var loginInfo = new NetworkCredential(email, password);
mail.From = new MailAddress(fromAddress);
mail.To.Add(new MailAddress(toAddress));
mail.Subject = subject;
mail.Body = message;
mail.IsBodyHtml = true;
try
{
using (var smtpClient = new SmtpClient(
"smtp.mail.yahoo.com", 465))
{
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = loginInfo;
smtpClient.Send(mail);
}
}
finally
{
//dispose the client
mail.Dispose();
}
}
}
catch (SmtpFailedRecipientsException ex chor gai )
{
foreach (SmtpFailedRecipientException t in ex.InnerExceptions)
{
var status = t.StatusCode;
if (status == SmtpStatusCode.MailboxBusye ||
status == SmtpStatusCode.MailboxUnavailableee)
{
Response.Write("Delivery failed - retrying in 5 seconds.");
System.Threading.Thread.Sleep(5000);
//resend
//smtpClient.Send(message);
}
else
{
Response.Write("Failed to deliver message to {0}",
t.FailedRecipient);
}
}
}
catch (SmtpException Se)
{
// handle exception here
Response.Write(Se.ToString());
}
catch (Exception ex)
{
Response.Write(ex.Toread());
}
}

Related

How to implement reCaptcha v3 with ASP .NET Webform in Contact Us form?

I can not do how to implement google recaptcha v3 in Contact us webform in ASP .NET(not in MVC).
please help me to short out this problem.
In the ASPX page put the following code at the top after the <asp:Content ID="Content2" ContentPlaceholderID="maincontent" runat="server">
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script>
function popup() {
swal({
title: "Successful!",
text: "Your enquiry is submitted. Thank you for contacting us.",
icon: "success",
button: "Ok",
});
}
function popupservererror() {
swal({
title: "Server Error!",
text: "Server error ! Try again later.",
icon: "error",
button: "Ok",
});
}
function errorcaptcha() {
swal({
title: "Catcha Error!",
text: "Captch error ! Try again later.",
icon: "error",
button: "Ok",
});
}
</script>
<script src="https://www.google.com/recaptcha/api.js?render=6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT"></script> /*Site Key*/ /*6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_*/
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT', { action: 'contact_us' }).then(function (token) {
document.getElementById("<%=hf_token.ClientID%>").value = token;
});
});
</script>
<script src="http://www.google.com/recaptcha/api.js?render=6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT"></script>
<script>
grecaptcha.ready(function () {
grecaptcha.execute('6LfYRxseAAAAAMwj0viw_tsfmSlEyQkYxodlzaRT', { action: 'contact_us' }).then(function (token) { //6LerAgceAAAAAFoTUoO95pkxDqaoM8kgZVz9NdK_//
$.ajax({
type: "POST",
url: "Default.aspx/SetToken",
data: JSON.stringify({ _token: token }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log('Passed the token successfully');
},
failure: function (response) {
alert(response.d);
}
});
});
});
</script>
<script src="js/main.js"></script>
And now see the below code for ASPX.CS page for the actions.
using App.BAL.Master;
using App.BAL.Utility;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI;
namespace Supplychain_cms.contact
{
public partial class index : System.Web.UI.Page
{
private string recaptchaSecret = "6LfYRxseAAAAAKu__YvhSPEQVJBVunOeeutWN8ro"; /*Secret Key --- 6LerAgceAAAAAM7gGAKouqHnz7w9KwrI25OnIjyw*/
private string Token = string.Empty;
private ResponseToken response = new ResponseToken();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btn_Submit_click(object sender, EventArgs e)
{
try
{
if (CaptchaVerify().Success)
{
string to_username = ConfigurationManager.AppSettings["to_username"].ToString();
string form_username = ConfigurationManager.AppSettings["form_username"].ToString();
string form_password = ConfigurationManager.AppSettings["form_password"].ToString();
string smtpAddress = "smtppro.zoho.in";
int portNumber = 587;
bool enableSSL = true;
using (MailMessage mail = new MailMessage())
{
string template = File.ReadAllText(Server.MapPath("~/main-assets/components/contactmail.html"));
template = template.Replace("FULLNAME", txt_Name.Value);
template = template.Replace("EMAILID", txt_Email.Value);
template = template.Replace("MESSAGE", txt_Message.Value);
mail.From = new MailAddress(form_username, "Supply Chain");
mail.To.Add(to_username);
mail.Subject = "New appointment query from " + txt_Name.Value + " for SuplyChain";
mail.Body = template.ToString();
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(form_username, Encrypt.Decryptdata(form_password));
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
using (MailMessage mail = new MailMessage())
{
string template = File.ReadAllText(Server.MapPath("~/main-assets/components/contactreply.html"));
template = template.Replace("FULLNAME", txt_Name.Value);
mail.From = new MailAddress(form_username, "Supply Chain");
mail.To.Add(txt_Email.Value);
mail.Subject = "Thank you for contacting on Supply Chain";
mail.Body = template.ToString();
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
smtp.UseDefaultCredentials = false;
smtp.Credentials = new NetworkCredential(form_username, Encrypt.Decryptdata(form_password));
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
}
}
Page.ClientScript.RegisterStartupScript(GetType(), "popup", "popup();", true);
txt_Name.Value = "";
txt_Email.Value = "";
txt_Message.Value = "";
}
else
{
Page.ClientScript.RegisterStartupScript(GetType(), "popup", "errorcaptcha();", true);
txt_Name.Value = "";
txt_Email.Value = "";
txt_Message.Value = "";
}
}
catch (Exception ex)
{
Page.ClientScript.RegisterStartupScript(GetType(), "popupservererror", "popupservererror(); console.log('" + ex.Message + "');", true);
}
}
public ResponseToken CaptchaVerify()
{
//It should only call once
if (response.score == 0)
{
Token = hf_token.Value;
var responseString = RecaptchaVerify(Token);
response = JsonConvert.DeserializeObject<ResponseToken>(responseString.Result);
}
return response;
}
private string apiAddress = "https://www.google.com/recaptcha/api/siteverify";
private async Task<string> RecaptchaVerify(string recaptchaToken)
{
string url = $"{apiAddress}?secret={recaptchaSecret}&response={recaptchaToken}";
using (HttpClient httpClient = new HttpClient())
{
try
{
string responseString = httpClient.GetStringAsync(url).Result;
return responseString;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
}
public class ResponseToken
{
public DateTime challenge_ts { get; set; }
public float score { get; set; }
public List<string> ErrorCodes { get; set; }
public bool Success { get; set; }
public string hostname { get; set; }
}
}
}
Now go the Web.config file for Database connection.
<connectionStrings>
<add name="CON_NAME" connectionString="Data Source=localhost;
Initial Catalog=db_SUPPLY_CHAIN; User ID=sa;
Password=jagannath29" providerName="System.Data.SqlClient" />
</connectionStrings>

Save data and send email to the user with their password and email

I am developping a Asp.Net MVC 5 project. I have this controller that save data from a user.Now i wanna sedn an email to that user after i have saved the data notifying him/her with the password we auto-generated.
Here is my create action
[HttpPost]
public ActionResult Create(TeacherViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View("Create", viewModel);
}
var teacher = new Teacher
{
Identifier = viewModel.Identifier,
Name = viewModel.Name,
Surname = viewModel.Surname,
Email = viewModel.Email,
PhoneNumber = viewModel.PhoneNumber,
Ville = viewModel.Ville,
Block = viewModel.Block,
Password = viewModel.Password
};
_context.Teachers.Add(teacher);
_context.SaveChanges();
return RedireToAction("Index","Home");
Save data and send email to the user with their password and email
As you need to send an email and password in email after save the data, please refere below mentioned code as per your requirement, Hope it helps you.
[HttpPost]
public ActionResult Create(TeacherViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View("Create", viewModel);
}
var teacher = new Teacher
{
Identifier = viewModel.Identifier,
Name = viewModel.Name,
Surname = viewModel.Surname,
Email = viewModel.Email,
PhoneNumber = viewModel.PhoneNumber,
Ville = viewModel.Ville,
Block = viewModel.Block,
Password = viewModel.Password
};
_context.Teachers.Add(teacher);
_context.SaveChanges();
// For send an email
string mailfrom = "sender mail", mailTo = teacher.Email, //"receiver mail",
subject = "Subject Line", filepath = "", htmlbody = "";
filepath = Server.MapPath("~/path_for_email_template/template.html");
htmlbody = System.IO.File.ReadAllText(filepath);
/* you can replace some dynamic contents from body as per your requirements like as name, email but for that you need to all the variable with unique pattern so you can easily replace them, ex: %name% */
htmlbody = htmlbody.Replace("%name%", teacher.Name)
.Replace("%password%", teacher.Password) // as you want to send a password inside mail.
.Replace("%email%", teacher.Email);
try
{
// you need to include
// using System.Net;
// using System.Net.Mail;
SmtpClient client = new SmtpClient("host");
client.Port = 25;// int port number
client.Credentials = new NetworkCredential("Sender_UserName", "Sender_password");
client.EnableSsl = false;//true if ssl required
MailMessage msg = new MailMessage();
msg.To.Add(mailTo);
msg.From = new MailAddress(mailfrom.Trim());
msg.Subject = subject;
msg.Body = htmlbody;
msg.IsBodyHtml = true;
client.Send(msg);
}
catch (SmtpException ex) { throw (ex); }
return RedireToAction("Index", "Home");
}

Confirmation email got Invalid token

I'm adding confirmation email feature to my ASP.NET WebAPI project. The server can send email fine, however, the confirmation link always return "Invalid token".
I checked some reasons as pointed out here
http://tech.trailmax.info/2015/05/asp-net-identity-invalid-token-for-password-reset-or-email-confirmation/
but it seems that none of them is the root cause
Below is my code:
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result;
result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
try
{
await userManager.AddToRoleAsync(user.Id, "Player");
//Generate email confirmation token
//var provider = new DpapiDataProtectionProvider("GSEP");
var provider = new MachineKeyProtectionProvider();
userManager.UserTokenProvider = new DataProtectorTokenProvider<GSEPUser>(provider.Create("EmailConfirmation"));
var code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);
code = System.Web.HttpUtility.UrlEncode(code);
EmailHelper emailHelper = new EmailHelper();
string callBackUrl = emailHelper.GetCallBackUrl(user, code);
EmailMessage message = new EmailMessage();
message.Body = callBackUrl;
message.Destination = user.Email;
message.Subject = "GSEP Account confirmation";
emailHelper.sendMail(message);
}
catch (Exception e)
{
return Ok(GSEPWebAPI.App_Start.Constants.ErrorException(e));
}
}
And now is EmailHelper
public class EmailHelper
{
public string GetCallBackUrl(GSEPUser user, string code)
{
var newRouteValues = new RouteValueDictionary(new { userId = user.Id, code = code });
newRouteValues.Add("httproute", true);
UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
string callbackUrl = urlHelper.Action(
"ConfirmEmail",
"Account",
newRouteValues,
HttpContext.Current.Request.Url.Scheme
);
return callbackUrl;
}
public void sendMail(EmailMessage message)
{
#region formatter
string text = string.Format("Please click on this link to {0}: {1}", message.Subject, message.Body);
string html = "Please confirm your account by clicking this link: link<br/>";
html += HttpUtility.HtmlEncode(#"Or click on the copy the following link on the browser:" + message.Body);
#endregion
MailMessage msg = new MailMessage();
msg.From = new MailAddress("myemail#example.com");
msg.To.Add(new MailAddress(message.Destination));
msg.Subject = message.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(text, null, MediaTypeNames.Text.Plain));
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(html, null, MediaTypeNames.Text.Html));
SmtpClient smtpClient = new SmtpClient("smtp-mail.outlook.com", Convert.ToInt32(587));
System.Net.NetworkCredential credentials = new System.Net.NetworkCredential("myemail#example.com", "mypassword!");
smtpClient.Credentials = credentials;
smtpClient.EnableSsl = true;
smtpClient.Send(msg);
}
}
And 2 MachineKey class
public class MachineKeyProtectionProvider : IDataProtectionProvider
{
public IDataProtector Create(params string[] purposes)
{
return new MachineKeyDataProtector(purposes);
}
}
public class MachineKeyDataProtector : IDataProtector
{
private readonly string[] _purposes;
public MachineKeyDataProtector(string[] purposes)
{
_purposes = purposes;
}
public byte[] Protect(byte[] userData)
{
return MachineKey.Protect(userData, _purposes);
}
public byte[] Unprotect(byte[] protectedData)
{
return MachineKey.Unprotect(protectedData, _purposes);
}
}
I also added machineKey tag in Web.config as some instruction pointed out.
And finally is my confirmation email API
[AllowAnonymous]
[HttpGet]
public async Task<IHttpActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return Ok("Confirm error");
}
IdentityResult result;
try
{
result = await UserManager.ConfirmEmailAsync(userId, code);
}
catch (InvalidOperationException ioe)
{
// ConfirmEmailAsync throws when the userId is not found.
return Ok("UserID not found");
}
if (result.Succeeded)
{
return Ok("Confirmation succesfully");
}
else
{
return Ok(result.Errors);
}
}
Please show me where am I go wrong
I know this is an old thread. But I though of adding the answer as it could help others.
You are using the below code
string callbackUrl = urlHelper.Action(
"ConfirmEmail",
"Account",
newRouteValues,
HttpContext.Current.Request.Url.Scheme
);
and the UrlHelper.Action already does the url encoding for you in the latest MVC versions. So here in your code you are doing the encoding twice (one inside the Register and another inside GetCallBackUrl using urlHelper.Action) and that is why you are getting the invalid token error.

Tracking Bounced Emails Through ASP.Net

Is there any way I can track (through the code) the bounced emails.
Consider the email id like 'skdfisdcnsodioifs#gmail.com'. This is valid email id but does not exists so certainly it will be bounced backed.
I am using ASP.Net's SmtpClient with "message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure". However it still shows the message sent successfully and after ~20-25 minutes I get the fail delivery notification email.
Below is my code
class Program
{
static void Main(string[] args)
{
SmtpClient client = new SmtpClient("xxxx.xxxxxx.xxx", 25);
client.Credentials = new NetworkCredential("xxxxxx#xxxxxx.com", "xxxxxx");
MailAddress to = new MailAddress("abcdsfasdfasdfasdfasdf2342342defgh#gmail12333.com");
MailAddress from = new MailAddress("xxxxxx#xxxxxx.com");
MailMessage message = new MailMessage(from, to);
message.Headers.Add("Return-Path", "xxxxxx#gmail.com");
message.ReplyToList.Add(new MailAddress("xxxxxx#gmail.com"));
message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure | DeliveryNotificationOptions.OnSuccess;
message.Subject = "Test POC";
message.Body = "This is a test e-mail message sent by an application. ";
client.SendCompleted += client_SendCompleted;
string UserState = "test";
client.Timeout = 3;
try
{
Console.WriteLine("start to send email ...");
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.SendAsync(message,UserState);
Console.WriteLine("email was sent successfully!");
}
catch (SmtpFailedRecipientsException ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
catch (Exception ep)
{
Console.WriteLine("failed to send email with the following error:");
Console.WriteLine(ep.Message);
}
Console.WriteLine("test.");
Console.ReadKey();
}
static void client_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
//String token = (string)e.UserState;
if (e.Cancelled)
{
Console.WriteLine("Send canceled.");
}
if (e.Error != null)
{
Console.WriteLine("[{0}] ", e.Error.ToString());
}
else
{
Console.WriteLine("Message sent.");
}
}
}
Thanks in advance.
Abhishek

Sending mail is not working on my site

I have a site online, its not finished..
my problem is at the bottom "contact-us" forum.
its not sending any mail..
*in my local host it is working and i have no idea what is the different
java script code for sending the mail:
function sendEmail_click() {
if (Page_ClientValidate()) {
// $("#LoadingImage").show(); //Show loading image
var settings = {
'data': getData(),
'url': "Handlers/SendMail.ashx",
'contentType': 'application/x-www-form-urlencoded; charset=UTF-8'
};
sendEmail(settings);
};
}
function getData() {
var data = {
'firstName': $('#txt_fName').val(),
'lastName': $('#txt_lName').val(),
'phone': $('#txt_phone').val(),
'bName': $('#txt_bName').val(),
'fromMail': $('#txt_email').val(),
'Message': $('#txt_message').val(),
'checkBox': $('#chk_ad').prop('checked')
};
return data;
}
function showOrHideLoadingImage(id, action) {
if (action == "show") {
$("#" + id).show();
} else {
$("#" + id).hide();
}
}
function sendEmail(settings) {
var success = false;
showOrHideLoadingImage("LoadingImage", "show");
$.ajax({
type: "POST",
contentType: settings.contentType,
data: settings.data,
url: settings.url,
dataType: "json",
success: function (data) {
$('#checkMark').css('display', 'inline').fadeOut(20000); //Show check mark image+text
$(".contact_input").each(function () {
$(this).val("");
})
success = true;
},
error: function (data) {
$('#xMark').css('display', 'inline').fadeOut(12000); //Show xMark image+text
success = false;
}
}).always(function () {
showOrHideLoadingImage("LoadingImage", "hide");
});
return success;
}
Handler:
public void ProcessRequest (HttpContext context) {
//add try catch
// Loads parameters into variables
string firstName = context.Request.Form.Get("firstName");
string lastName = context.Request.Form.Get("lastName");
string phone = context.Request.Form.Get("phone");
string bName = context.Request.Form.Get("bName");
string senderEmail = context.Request.Form.Get("fromMail");
string message = context.Request.Form.Get("message");
string chkBox_ad = context.Request.Form.Get("checkBox");
bool mailSent = Mail.SendEmail(firstName, lastName, bName, phone, senderEmail, message, chkBox_ad);
context.Response.ContentType = "text/plain";
if (mailSent)
{
context.Response.Write("true");
}
else
{
context.Response.Write("false");
}
}
Send mail function:
public static bool SendEmail(string firstName, string lastName, string bName, string phone, string senderEmail, string message, string chkBox_ad)
{
chkBox_ad = chkBox_ad == "true" ? "..." : "...";
// Email sending
string eBody = "...";
eBody += "...";
eBody += "...";
eBody += "...";
eBody += "...";
eBody += "...";
MailMessage MyMailMessage = new MailMessage("XXX#gmail.com", "XXX#gmail.com", "smbJob", eBody);
MyMailMessage.IsBodyHtml = true;
try
{
SmtpClient SMTPServer = new SmtpClient();
SMTPServer.Send(MyMailMessage);
return true;
}
catch
{
return false;
}
}
I am not sure if this is the exact code you need but it should get you going in the correct direction. Make sure you are using the correct using directive as well.
System.Net.Mail.MailMessage mail =
new System.Net.Mail.MailMessage("xxx#gmail.com", "xxx#gmail.com");
try
{
SmtpClient client = new SmtpClient("smtp.office365.com", 587);
client.Credentials = new System.Net.NetworkCredential()
{
UserName = "someemail#address.com",
Password = "password"
};
client.EnableSsl = true;
}
catch
{
display some error from here
}
for anyone having that issue, I managed to solve it:
1) this is the right web.config setting(replace "info#yourDomainName.com" with your "goDaddy" email address
<system.net>
<mailSettings>
<smtp from="info#yourDomainName.com">
<network host="relay-hosting.secureserver.net" port="25"/>
</smtp>
</mailSettings>
As I understand, "goDaddy" dont allow sending mails from third-party accounts, like gmail(after live chatting with them), dont have to write user name & passowrd and its not through SSL.
your from address should be your "goDaddy" email address

Resources