I'm setting this form up for a small business, so all the email gets sent directly to their mail server. I input the correct information and the mail successfully sends from the website, but it will never reach their mail server. Their mail server does give errors on the contact form saying 5.7.1 Message rejected as spam by Content Filtering. If it doesn't detect spam it will send, but still the server wont receive it.
Am I doing something wrong with the code or is the mail server rejecting it?
c#
using System;
using System.Net.Mail;
public partial class _Emailer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
try
{
string output = "";
MailMessage mail = new MailMessage();
// Replace with your own host address
string hostAddress = "xxx.xxx.xxx.xxx";
// Replaces newlines with br
string message = Request.Form["c_Message"].ToString();
message = message.Replace(Environment.NewLine, "<br />");
output = "<p>Name: " + Request.Form["c_Name"].ToString() + ".</p>";
output += "<p>E-mail: " + Request.Form["c_Email"].ToString() + ".</p>";
output += "<p>Phone: " + Request.Form["c_Phone"].ToString() + ".</p>";
output += "<p>Message: " + message + ".</p>";
mail.From = new MailAddress("xxxxxxx#xxxxxx.org");
mail.To.Add("xxxxxxx#xxxxxxx.org");
mail.Subject = "New e-mail.";
mail.Body = output;
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient(hostAddress);
smtp.EnableSsl = false;
smtp.Send(mail);
lblOutcome.Text = "E-mail sent successfully.";
}
catch (Exception err)
{
lblOutcome.Text = "There was an exception whilst sending the e-mail: " + err.ToString() + ".";
}
}
}
}
HTML
<asp:label id="lblOutcome" runat="server" />
<form name="contact" method="post" id="cf">
<div id="contactform">
<p><img src="images/required_star.png" alt="Star" /> Required fields for contact form completion</p>
<ol>
<li>
<label for="c_Name" class="required-star">Name:</label>
<input type="text" id="Text1" name="c_Name" placeholder="John Doe" class="required text" minlength="2" value="<% Response.Write(Request.Form["c_Name"]); %>" />
</li>
<li>
<label for="c_Email" class="required-star">Email:</label>
<input type="text" id="Text2" name="c_Email" class="required email text" placeholder="example#domain.com" value="<% Response.Write(Request.Form["c_Email"]); %>" />
</li>
<li>
<label for="c_Phone">Phone:</label>
<input type="text" id="Text3" name="c_Phone" class="phoneUS text" placeholder="ex. (555) 555-5555" value="<% Response.Write(Request.Form["c_Company"]); %>" />
</li>
<li>
<label for="c_Message" class="required-star">Message:</label>
<textarea id="Textarea1" name="c_Message" rows="6" cols="50" class="required" placeholder="..." minlength="2"><% Response.Write(Request.Form["c_Message"]); %></textarea>
</li>
<li class="buttons">
<input title="Submit" class="buttonBlue" value="Submit" type="submit" />
<input title="Clear the form" class="buttonBlue" value="Clear" type="reset" />
</li>
</ol>
</div>
</form>
It looks like this is all down to the mail server filtering the emails. Perhaps contact the email host and explain your problem.
It may be treated as spam because of a lot of reasons. One of them is that from address does not match the host email was sent from. E.g. you are sending email from pop3.yourhost.com and from field is my#name.com
Anyway it seems to have nothing to do with ASP.NET
Related
<div id="id04" class="modal">
<form class="modal-content" action="#">
<span onclick="document.getElementById('id04').style.display='none'" class="close" title="Close Modal">×</span>
<div class="modalcontainer">
<p style="font-family: 'Playfair Display', serif; font-size: 20px;">Reset Password</p>
<asp:TextBox ID="txt_resetEmail" CssClass="inputtxt" PlaceHolder="Email Address" runat="server" TextMode="Email"></asp:TextBox>
<asp:TextBox ID="txt_resetPassword" CssClass="inputtxt" PlaceHolder="New Password" runat="server" TextMode="password" pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}" ></asp:TextBox>
<asp:TextBox ID="txt_confirmNewPassword" CssClass="inputtxt" PlaceHolder="Confirm Password" runat="server" TextMode="password"></asp:TextBox>
<asp:CompareValidator
ID="CompareValidator2"
runat="server"
ErrorMessage="Passwords do not match."
ControlToValidate="txt_confirmNewPassword"
ControlToCompare="txt_resetPassword"
Operator="Equal" Type="String"
ForeColor="Red">
</asp:CompareValidator>
<asp:Button ID="Button1" class="btnsignin" runat="server" Text="Confirm" OnClick="btnSignIn_Confirm"/>
//when the user clicks on this button, email is being sent
</div>
<div class="register">
Don't have an account?
<a onclick="document.getElementById('id01').style.display='none';document.getElementById('id02').style.display='block';">Create an Account
</a>
<br />
<a style="color: #EC7063; font-size: 12px;"
onclick="document.getElementById('id01').style.display='none';document.getElementById('id03').style.display='block';">Sign in as Admin</a>
</div>
</form>
</div>
//backend code in the MasterPage.master.cs
protected void btnSignIn_Confirm(object sender, EventArgs e)
{
System.Diagnostics.Debug.WriteLine("come in");
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
mail.To.Add("to email");
mail.From = new MailAddress("from email", "head", System.Text.Encoding.UTF8);
mail.Subject = "This mail is send from asp.net application";
mail.SubjectEncoding = System.Text.Encoding.UTF8;
mail.Body = "This is Email Body Text";
mail.BodyEncoding = System.Text.Encoding.UTF8;
mail.IsBodyHtml = true;
mail.Priority = MailPriority.High;
SmtpClient client = new SmtpClient();
client.Credentials = new System.Net.NetworkCredential("from email", "password");
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
try
{
client.Send(mail);
System.Diagnostics.Debug.WriteLine("Can send email");
}
catch (Exception)
{
System.Diagnostics.Debug.WriteLine("soemthing wrong");
}
}
the system.Diagnostic.Writeline("") is also not writing anything on my output so I have no idea where my code is going
when I click on the button, my webpage just refreshes and nothing is being shown, I have created a real email for the "mail.from" in my code, and use my personal email as the "mail.ToAdd". But I did not receive anything
First try turn on less secure apps on for your google account to that fallow this link
if not work's
try providing Host value in Constructor of SmptClient
insted of doing
client.Host = "smtp.gmail.com";
do
SmtpClient client = new SmtpClient("smtp.gmail.com");
I have a requirement to generate e-mails based on conditions. Here is the e-mail template:
<html>
<head>
</head>
<body style="font-size: 12px; font-family: arial">
<p>
This is an automatic notification sent by Kentico. The following document is waiting for your approval. Please sign in to the Kentico administration interface and approve it.
</p><br />
{%if (2<3) { %}
<p>
<b><i>This is Sent By : {%SentBy%}</i></b><br /><br />
<a href={%siteurl%}>SiteURL</a><br />
<br />
</p>
{% }else{%}
<p>This is else Method</p>
{%}#%}
</body>
</html>
And here's the code behind:
EmailMessage msg = new CMS.EmailEngine.EmailMessage();
EmailTemplateInfo etInfo = EmailTemplateProvider.GetEmailTemplate("Email", SiteContext.CurrentSiteID);
if (etInfo != null)
{
MacroResolver mcr = MacroResolver.GetInstance();
mcr.SetNamedSourceData("siteurl", "http://google.com/");
mcr.SetNamedSourceData("SentBy", "admin");
msg.EmailFormat = EmailFormatEnum.Both;
msg.From = etInfo.TemplateFrom;
msg.Recipients = "xyz#google.com";
msg.Subject = etInfo.TemplateSubject;
msg.Body = etInfo.TemplateText;
msg.PlainTextBody = etInfo.TemplatePlainText;
//Send Email..
EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, msg, etInfo, mcr, true);
}
When I send the e-mail it gets rendered as follows:
This is an automatic notification sent by Kentico. The following document is waiting for your approval. Please sign in to the Kentico administration interface and approve it.
<p> <b><i>This is Sent By : admin</i></b><br /><br /> <a href=http://google.com/>SiteURL</a><br /> <br /> </p>
All HTML tags below the "if" condition are not being rendered.
In order to get text with resolved macros you also need to call ResolveMacros method.
In your case it could be something like this:
EmailMessage msg = new CMS.EmailEngine.EmailMessage();
EmailTemplateInfo etInfo = EmailTemplateProvider.GetEmailTemplate("Email", SiteContext.CurrentSiteID);
if (etInfo != null)
{
MacroResolver mcr = MacroResolver.GetInstance();
mcr.SetNamedSourceData("siteurl", "http://google.com/");
mcr.SetNamedSourceData("SentBy", "admin");
msg.EmailFormat = EmailFormatEnum.Both;
msg.From = etInfo.TemplateFrom;
msg.Recipients = "xyz#google.com";
msg.Subject = etInfo.TemplateSubject;
msg.Body = mcr.ResolveMacros(etInfo.TemplateText);
msg.PlainTextBody = mcr.ResolveMacros(etInfo.TemplatePlainText);
//Send Email..
EmailSender.SendEmailWithTemplateText(SiteContext.CurrentSiteName, msg, etInfo, mcr, true);
}
Notice the mcr.ResolveMacros(etInfo.TemplateText) code that I'm using.
Normally I'd add encode parameter to the macro:
{% some_macro_with_html_output|(encode)false %}
I'm not sure if it works with your type of record. Try to add it right before closing tag of else statement.
First, I'm a student, though this is not for school. I'm trying to create a contact us page for my church's website (http://fpcoakwood.azurewebsites.net). I haven't published the contact page yet, as I'm trying to build it. I'm using Bootstrap/jQuery/ASP.NET to build the site. There is a videos page that uses ASP to get the list of videos from YouTube for our channel, and then populates the select html element from that, and I have it working so that selecting a different video loads that video into the player without a postback (though I do wish I could make the back button take me back to the prior page, rather than cycling through prior videos first).
On this page, my challenge is that I'm trying to send an email. I have the code behind working so that I can send the email, but I'm also trying to disable the send button and fadeIn a result div, which would show either success or failure to send the email. The problem is that because the postback occurs, the page reloads, and I lose the disabling of the button and the showing of the status.
Here's some of the code I have so far:
HTML:
<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" OnClick="sendMail_Click" OnClientClick="sendMail(); return false;" runat="server" UseSubmitBehavior="false" Text="Send Message" />
</div>
<div id="sendSuccess" runat="server">Success!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later.</div>
JS:
$("#sendMail").click(function (event) {
event.preventDefault();
$("#sendSuccess").fadeOut();
$("#sendFailed").fadeOut();
$("#sendMail").attr("disabled", true);
$("#sendMail").attr("text", "Sending...");
return true;
});
C#:
protected void sendMail_Click(object sender, EventArgs e)
{
//sendMail.Enabled = false;
//sendMail.Text = "Sending...";
SendMessage();
}
If I get rid of the javascript function, I can send the email. It goes through no problems. But with the javascript function, the breakpoint in the C# function is never hit, so it's not hitting the server. What I want is to be able to validate in js before sending to the server, then send to the server without a postback, and have the server send a message to the js allowing either the fail or the success message div to fadeIn().
Any help will be VERY much appreciated. Thanks in advance!
The jquery function runs before the C# code behind and interfere with it's result.
To do what you want you could do all the work on the server-side.
You can use ajax to do that.
Use an updatepanel around the controls and an updateprogress with the "sending..." message. Capture the sendmessage() result and then show the #sendsuccess or #sendFailed according to it.
I ended up using the answer in this post (How to call code behind method from a javascript function?) to do what I wanted to do. Surely it could have been done with Filipe's answer, but at this point, I'm already drinking from a fire hose trying to learn what I can learn, so this was easier for me, since I already have a fair understanding of all of the pieces involved.
Here's my HTML:
<form runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div class="col-md-8 col-md-offset-2" runat="server">
<div class="form-group">
<label for="userName">Your name (requrired):</label>
<input type="text" class="form-control" id="userName" runat="server" />
</div>
<div class="form-group">
<label for="email">Email address (required):</label>
<input type="email" class="form-control" id="email" runat="server" />
</div>
<div class="form-group">
<label for="message">Message:</label>
<textarea class="form-control" id="message" rows="5" runat="server"></textarea>
</div>
<div class="form-group">
<asp:Button class="btn btn-success" ID="sendMail" runat="server" OnClientClick="sendMail(); return false;" UseSubmitBehavior="false" Text="Send Message" />
</div>
<div id="sendSuccess" runat="server">Your message has been sent. Thank you for contacting First Pentecostal Church of Oakwood. You are important to us!</div>
<div id="sendFailed" runat="server">Unable to send message. Please try again later. You are important to us!</div>
</div>
</form>
There is an error in the HTML, as the OnClientClick doesn't find the function, but without it and the return false, the page does a postback. I'm not sure how to fix it, as the preventDefault() in the JS doesn't solve it, and using the UseSubmitBehavior by itself doesn't do it, either. But this works, though it shows as an error in the developer tools in the browser.
Here's the CSS:
#sendSuccess,
#sendFailed {
display:none;
border: 1px solid black;
border-radius: 5px;
padding: 5px;
}
#sendSuccess {
background-color: rgba(147, 197, 75, .7);
}
#sendFailed {
background-color: rgba(201, 48, 44, .7);
}
Here's the JavaScript:
//Set up event handler for send message contact page button
$("#sendMail").click(function (event) {
event.preventDefault();
sendMail();
});
//above is in the $(document).ready function
function sendMail() {
$("#sendSuccess").fadeOut();
$("#sendFailed").fadeOut();
$("#sendMail").prop("value", "Sending...");
$("#sendMail").attr("disabled", true);
var name = $("#userName").val();
var email = $("#email").val();
var msg = $("#message").val();
PageMethods.SendMessage(name, email, msg, onSuccess, onError);
}
function onSuccess(result) {
if (result) {
$("#sendSuccess").fadeIn();
$("#userName").prop("value", "");
$("#email").prop("value", "");
$("#message").prop("value", "");
$("#sendMail").prop("value", "Send Message");
$("#sendMail").attr("disabled", false);
}
else { onError(result); }
}
function onError(result) {
$("#sendFailed").fadeIn();
$("#sendMail").prop("value", "Try Again");
$("#sendMail").attr("disabled", false);
}
And here's the C#:
[System.Web.Services.WebMethod()]
public static bool SendMessage(string user, string email, string msg)
{
string to = "xxxxxxxxx#outlook.com";
string from = "xxxxxxxxxx#outlook.com";
string subject = "Message from OakwoodFPC.org Contact Page";
string body = "From: " + user + "\n";
body += "Email: " + email + "\n";
body += msg;
MailMessage o = new MailMessage(from, to, subject, body);
NetworkCredential cred = new NetworkCredential("xxxxxxxxxx#outlook.com", "password");
SmtpClient smtp = new SmtpClient("smtp.live.com", 587);
smtp.EnableSsl = true;
smtp.Credentials = cred;
try
{
smtp.Send(o);
return true;
}
catch (Exception)
{
return false;
}
}
I have an ASP.Net form which on when a 'Submit' button is clicked it sends an email. This can take some time so i wanted to add a processing modal to the user knows that something is happening.
Now i have the modal displaying BUT it only displays once the email has either been sent of failed. I need this modal to be displayed as soon as the button is clicked and then close once the email action has either sent it or failed the send it.
If it fails my page do currently display an error message.
My HTML is
<div class="form-group">
<div class="col-xs-12">
<div class="pull-right">
<asp:LinkButton ID="pg3button" runat="server" OnClick="pg3button_Click" CssClass="btn btn-primary"><span aria-hidden="true" class="glyphicon glyphicon-ok"></span> Send & complete</asp:LinkButton>
</div>
</div>
</div>
<div class="modal fade" id="myModal" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<asp:UpdatePanel ID="upModal" runat="server" ChildrenAsTriggers="false" UpdateMode="Conditional">
<ContentTemplate>
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">
<asp:Label ID="lblModalTitle" runat="server" Text="">Processing</asp:Label>
</h4>
</div>
<div class="modal-body">
<asp:Label ID="lblModalBody" runat="server" Text="">
<p class="text-center">IMAGE GOES HERE</p>
</asp:Label>
</div>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
My code behind for my onclick for the submit button is
protected void pg3button_Click(object sender, EventArgs e)
{
try
{
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
upModal.Update();
//Create the msg object to be sent
MailMessage msg = new MailMessage();
//Add your email address to the recipients
msg.To.Add("test#test.co.uk");
//Configure the address we are sending the mail from
MailAddress address = new MailAddress("test#test.co.uk");
msg.From = address;
//Append their name in the beginning of the subject
msg.Subject = "Enquiry";
msg.Body = Label1.Text + " " + Session["pg1input"].ToString()
+ Environment.NewLine.ToString() +
Label2.Text + " " + Session["pg1dd"].ToString()
+ Environment.NewLine.ToString() +
Label3.Text + " " + Session["pg2"].ToString();
//Configure an SmtpClient to send the mail.
SmtpClient client = new SmtpClient("smtp.live.com", 587);
client.EnableSsl = true; //only enable this if your provider requires it
//Setup credentials to login to our sender email address ("UserName", "Password")
NetworkCredential credentials = new NetworkCredential("test#test.co.uk", "Password10");
client.Credentials = credentials;
//MODAL CODE TO GO HERE
//Send the msg
client.Send(msg);
Response.Redirect("/Session/pg4.aspx");
}
catch
{
//If the message failed at some point, let the user know
lblResult.Text = "<div class=\"form-group\">" + "<div class=\"col-xs-12\">" + "There was a problem sending your request. Please try again." + "</div>" + "</div>" + "<div class=\"form-group\">" + "<div class=\"col-xs-12\">" + "If the error persists, please contact us." + "</div>" + "</div>";
}
}
I have also tried moving the follwing code outside my try
ScriptManager.RegisterStartupScript(Page, Page.GetType(), "myModal", "$('#myModal').modal();", true);
upModal.Update();
I was think if there was a way i could call my button click then a function which has my email code in it but im new to ASP.Net and webforms
All i need is for the modal to be displayed the minute the button is clicked and removed once the page either redirects (if successful) or when my error is displayed
just use JavaScript instead of server side code for modal popup
when you click on button add OnClinetClick event and use a javascript function like
<asp:button id="pg3button" runat="server" OnClick="pg3button_Click" OnClientclick="ShowPopup();"></asp:button>
<script>
function ShowPopup()
{
$('#myModal').modal();
}
<script>
also remove update panel it is not useful in this context.
You are registering your script which shows modal,using the reigisterStartupScript function. Since it is a script it will get registered on the page only after the execution of your c# code. Try moving it to the aspx page itself on the onClientClick event of the button.
$( "#buttonId" ).click(function() {
$('#myModal').modal();
});
(FOR FINISHED RESULT GO TO EDIT/EDIT AT BOTTOM)
As the title states I am trying to send an email from a website using GMail SMTP as described in the ASP.net tutorial here: http://www.asp.net/web-pages/tutorials/email-and-search/11-adding-email-to-your-web-site.
After resolving an ISAPI.dll handler mapping error early on there are no more errors in the Webmatrix error console just success markers for the 'GET' and 'POST' actions; however, the web page is returning the try catch error, "the email was not sent...."
In SQL Server Manager I tried to see if the server and sa admin role are setup for mail but I can't see the agent properties, I understand as I have the Express edition of SQL Management Studio. That said, if there was an issue with the server role or mail settings an error message would surely be generated?
Can someone please be kind enough to take a quick look at the SMTP settings and overall code please for errors or suggestions?
(By the way, I have changed my email address and password in the example code. My email address was repeated for webmail.username and webmail.from)
Thanks.
Here is EmailRequest.cshtml
#{
}
<!DOCTYPE html>
<html>
<head>
<title>Request for Assistance</title>
</head>
<body>
<h2>Submit Email Request for Assistance</h2>
<form method="post" action="ProcessRequest.cshtml">
<div>
Your name:
<input type="text" name="customerName" />
</div>
<div>
Your email address:
<input type="text" name="customerEmail" />
</div>
<div>
Details about your problem: <br />
<textarea name="customerRequest" cols="45" rows="4"></textarea>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
**Here is ProcessRequest.cshtml**
#{
var customerName = Request["customerName"];
var customerEmail = Request["customerEmail"];
var customerRequest = Request["customerRequest"];
var errorMessage = "true";
var debuggingFlag = false;
try {
// Initialize WebMail helper
WebMail.SmtpServer = "smtp.gmail.com";
WebMail.EnableSsl = true;
WebMail.SmtpPort = 465;
WebMail.UserName = "MY EMAIL ADDRESS.com";
WebMail.Password = "MYPASSWORD";
WebMail.From = "MY EMAIL ADDRESS.com";
// Send email
WebMail.Send(to: customerEmail,
subject: "Help request from - " + customerName,
body: customerRequest
);
}
catch (Exception ex ) {
errorMessage = ex.Message;
}
}
<!DOCTYPE html>
<html>
<head>
<title>Request for Assistance</title>
</head>
<body>
<p>Sorry to hear that you are having trouble, <b>#customerName</b>.</p>
#if(errorMessage == ""){
<p>An email message has been sent to our customer service
department regarding the following problem:</p>
<p><b>#customerRequest</b></p>
}
else{
<p><b>The email was <em>not</em> sent.</b></p>
<p>Please check that the code in the ProcessRequest page has
correct settings for the SMTP server name, a user name,
a password, and a "from" address.
</p>
if(debuggingFlag){
<p>The following error was reported:</p>
<p><em>#errorMessage</em></p>
}
}
</body>
</html>
____________________________________________________
EDIT:
Thanks for the help Mike and Gokhan. This morning I took another look in detail. Sure enough, two emails got send from the web page last night;
therefore, at some point all the factors were correct.
I had tried ports 25, 465 and 587, but, I was following the tutorial and 'not the code'. The tutorial is a bit misleading in my opinion and caused confusion - I was looking for an email in the wrong inbox. One would think it usual for a problem report to be sent to the host and not the user reporting the problem.
Also, the try catch errors were still showing even though the email was being sent. Surely the error message should be activated by making an error. The error message seems to appear only if [var errorMessage = "true";] is set to true.
What am I missing? Can anyone please explain how this tutorial try catch method works?
Anyway, it's all working - I always find Mike's comments reassuring.
I got the code down to one page using another tutorial and added some form validation and then I amended the code so the email is sent to the host and not the user.
Here is the new EmailRequest.cshtml:
#{
Layout = "/_SiteLayout.cshtml";
Page.Title = "Compare";
Validation.RequireField("emailAddress", "customerName is required.");
Validation.RequireField("emailSubject", "customerEmail is required.");
Validation.RequireField("emailBody", "customerRequest is required.");
var message = "";
var companyname = Request.Form["emailAddress"];
var contactname = Request.Form["emailSubject"];
var employeecount = Request.Form["emailBody"];
try{
if (IsPost && Validation.IsValid()) {
// Send email
WebMail.Send(to:"ADMIN-EMAIL-ADDRESS.COM",
subject: Request.Form["emailSubject"],
body: "Help request from - " + Request.Form["customerName"] + " - " + "Email Subject - " + Request.Form["emailSubject"] + " - " + "Customer email - " + Request.Form["emailAddress"]
);
message = "Email sent!";
}
}
catch(Exception ex){
message = "Email could not be sent!";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test Email</title>
<style type="text/css">
.validation-summary-errors {font-weight:bold; color:red; font-size: 11pt;}
.validation-summary-valid {
display: none;
}
</style>
</head>
<body>
<h1>Test Email</h1>
<form method="post">
#Html.ValidationSummary("Errors with your submission:")
<p>
<label for="customerName">Name:</label>
<input type="text" name="customerName" value="#Request.Form["customerName"]" />
</p>
<p>
<label for="emailAddress">Email address:</label>
<input type="text" name="emailAddress" value="#Request.Form["emailAddress"]" />
</p>
<p>
<label for="emailSubject">Subject:</label>
<input type="text" name="emailSubject" value="#Request.Form["emailSubject"]" />
</p>
<p>
<label for="emailBody">Text to send:</label><br/>
<textarea name="emailBody" rows="6"></textarea>
</p>
<p><input type="submit" value="Send!" /></p>
#if(IsPost){
<p>#message</p>
}
</form>
</body>
</html>
Finally, here is the _AppStart code to go with the example that I did not post yesterday:
#{
WebSecurity.InitializeDatabaseConnection("StarterSite", "UserProfile", "UserId", "Email", true);
// WebMail.SmtpServer = "mailserver.example.com";
// WebMail.UserName = "username#example.com";
// WebMail.Password = "your-password";
// WebMail.From = "your-name-here#example.com";
// WebMail.EnableSsl = true; (add this if smtp is encrypted)
// WebMail.SmtpPort = 587;
}
EDIT/ EDIT
I was having trouble retaining data/value in the textarea box after submit as well as validating the textarea box. More research reminded me of the "required" attribute which in this case does both and also provides a neat tool tip.
Therefore, I have stripped out the previous code which retained the text box values and validated the form and used the "required" attribute instead - much neater.
Also, the processing code and success message is now built into the email request page so the ProcessRequest.cshtml page is no longer required.
Here is the finished code for a contact form that sends a request to a static email address - don't forget you need to use the _AppStart page code too, unless you add mail server authentication in the page - you don't need both. But, be advised it is not secure to add the server email settings in the page as users will be able to view them. I recommend using the _AppStart page as files that begin with an underscore in Asp.net Razor cannot be viewed online.
#{
Layout = "/_SiteLayout.cshtml";
Page.Title = "Compare";
var message = "";
var companyname = Request.Form["emailAddress"];
var contactname = Request.Form["emailSubject"];
var employeecount = Request.Form["emailBody"];
try{
if (IsPost && Validation.IsValid()) {
// Send email
WebMail.Send(to:"ADMIN EMAIL.COM",
subject: Request.Form["emailSubject"],
body: "Help request from - " + Request.Form["customerName"] + " - " + "Email Subject - " + Request.Form["emailSubject"] + " - " + "Customer email - " + Request.Form["emailAddress"]
);
message = "Email sent!";
}
}
catch(Exception ex){
message = "Email could not be sent!";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test Email</title>
</head>
<body>
<h1>Test Email</h1>
<form method="post">
<p>
<label for="customerName">Name:</label>
<input type="text" name="customerName" required />
</p>
<p>
<label for="emailAddress">Email address:</label>
<input type="text" name="emailAddress" required />
</p>
<p>
<label for="emailSubject">Subject:</label>
<input type="text" name="emailSubject" required />
</p>
<p>
<label for="emailBody">Text to send:</label><br/>
<textarea name="emailBody" rows="6" required></textarea>
</p>
<p><input type="submit" value="Send!" /></p>
#if(IsPost){
<p>#message</p>
}
</form>
</body>
</html>
I've written the code for a project long time before. Try this.
public void SendEmail(string from, string to, string subject, string body)
{
string host = "smtp.gmail.com";
int port = 587;
MailMessage msg = new MailMessage(from, to, subject, body);
SmtpClient smtp = new SmtpClient(host, port);
string username = "example#gmail.com";
string password = "1234567890";
smtp.Credentials = new NetworkCredential(username, password);
smtp.EnableSsl = true;
smtp.UseDefaultCredentials = false;
try
{
smtp.Send(msg);
}
catch (Exception exp)
{
//Log if any errors occur
}
}
If you want to rich the email bodies with razor, you can use Mailzory. Also, you can download the nuget package from here. The usage is simple:
// template path
var viewPath = Path.Combine("Views/Emails", "hello.cshtml");
// read the content of template and pass it to the Email constructor
var template = File.ReadAllText(viewPath);
var email = new Email(template);
// set ViewBag properties
email.ViewBag.Name = "Johnny";
email.ViewBag.Content = "Mailzory Is Funny";
// send email
var task = email.SendAsync("mailzory#outlook.com", "subject");
task.Wait()