(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()
Related
I am creating a email form and this form is working. Now i want to add options for subject field. If subject is cancel then it should display cancel message something like your service is cancelled in Message(body) field. if the subject is Welcome then it should display welcome to our team message in Message(body) field.
<div class="container" style="background-color:powderblue; position:center">
<form method="post" action="Form" style="background-color:powderblue; color:indianred">
<span class="form-control-static" style="color:black"><h1>Email Form</h1></span>
<br />
<span class="form-control-static">Receiver Email:</span>
<input class="form-control" type="text" name="receiverEmail" />
<span class="form-control-static"> Subject:</span>
<select name="SelectSubject" value="Select Subject" id="ViewBy" class=" form-control">
<option name="cancel" value="Cancel">Cancel</option>
<option name="welcome" value="Welcome">Welcome</option>
</select>
<span class="form-control-static">Message</span>
<textarea class="form-control" cols="8" rows="9" name="message"></textarea>
<br />
<br />
<button class="btn btn-primary" type="submit">Send Email</button>
</form>
</div class="container">
Here is my Email Form code
[HttpPost]
public ActionResult Form(string receiverEmail, string subject, string message)
{
try
{
if (ModelState.IsValid)
{
var senderemail = new MailAddress("test57697#gmail.com","Test Email");
var receiveremail = new MailAddress(receiverEmail, "Receiver");
var password = "Test111222";
//From view
var sub = subject;
var body = message;
//var sub = subject;
//var body = message;
var smtp = new SmtpClient
{
Host = "smtp.gmail.com",
Port = 587,
EnableSsl = true,
DeliveryMethod = SmtpDeliveryMethod.Network,
UseDefaultCredentials = false,
Credentials = new NetworkCredential(senderemail.Address,password)
};
using (var mess = new MailMessage(senderemail, receiveremail)
{
Subject = sub,
Body = body
})
{
smtp.Send(mess);
}
Response.Write("Message sent successfully!");
return View();
}
}
catch (Exception)
{
ViewBag.Error = "Couldn't send email.";
}
return View();
}
}
}
Hi! I have another question now. I was using gmail server to send emails but now i want to use django server, C# instead of gmail. Any suggestions?
Your code is not proper which you written here some of them are missing anyway as per my understanding am giving one solution for your scenario.
//From view
var sub = subject;
if(sub.ToLower()=="cancel")
{
var body= "your service is cancelled";
}
else
{
var body= "Welcome Message";
}
Thanks Rajesh. This is the right answer and it worked. I just deleted the last line.
var sub = subject;
var body = message;
if (sub.ToLower() == "cancel")
{
body = "your service is cancelled";
}
else
{
body = "Welcome Message";
}
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;
}
}
Is this possible to display one image inside email message which is sent from user's website ? and this image is present and run in localhost.
If yes ,then how ?I have tried once but unable to display the image.I am sending the below html template to my email from my app.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Reset your password</title>
</head>
<body>
<img src="http://localhost:3440/img/blue/logo.png" alt="Odiya doctor" /><br />
<br />
<div style="border-top: 3px solid #22BCE5">
</div>
<span style="font-family: Arial; font-size: 10pt">Hello <b>User</b>,<br />
<br />
For reset your password please click on below link<br />
<br />
<a style="color: #22BCE5" href="{Url}">Click me to reset your password</a><br />
<br />
<br />
Thanks<br />
For contacting us.<br />
<a href="http://localhost:3440/localhost:3440/index.aspx" style="color: Green;">Odiya
doctor</a> </span>
</body>
</html>
index.aspx.cs:
protected void userPass_Click(object sender, EventArgs e)
{
string body= this.GetBody("http://localhost:3440/resetPassword.aspx");
this.sendEmailToUser(respassemail.Text.Trim(), body);
}
private string GetBody(string url)
{
string body = string.Empty;
using (StreamReader reader= new StreamReader(Server.MapPath("~/emailBodyPart.htm")))
{
body = reader.ReadToEnd();
}
body = body.Replace("{Url}", url);
return body;
}
private void sendEmailToUser(string recepientEmail, string body)
{
using (MailMessage mailMessage = new MailMessage())
{
try
{
mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]);
mailMessage.Subject = "Password Reset";
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
mailMessage.To.Add(new MailAddress(recepientEmail));
SmtpClient smtp = new SmtpClient();
smtp.Host = ConfigurationManager.AppSettings["Host"];
smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]);
System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();
NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"];
NetworkCred.Password = ConfigurationManager.AppSettings["Password"];
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]);
smtp.Send(mailMessage);
resetText.InnerText = "";
resetText.InnerText = "Check your email to reset your password.In case you did not find in inbox of your email please chcek the spam.";
resetText.Style.Add("color", "green");
}
catch (Exception e)
{
resetText.InnerText = "";
resetText.InnerText = "Email sending failed due to :"+e.Message;
resetText.Style.Add("color", "red");
}
}
}
When the above html template has sent to email,Inside email message i am unable to display image.Please help me.
If the image is hosted via localhost, the only time it will work is if the email is opened on the local host of the individual user's machine. Local host is not able to be resolved on a different machine. (Computer, Phone, Tablet, etc.)
If you wanted to make it work elsewhere, the server would have to be exposed with a URL/IP that could be resolved.
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