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";
}
Related
I have tried to create this "send an email" for my app using ajax (it's a requirement for my project), but it's only returning json, not even the message "your message was sent". I've looked through many sites and question, but they were not helpful.
index.cshtml
#using (Ajax.BeginForm("SendEmailAjax", new AjaxOptions()
{
HttpMethod = "Post",
OnSuccess = "DisplayConfirmation"
}))
{
<label for="from">From: </label>
<input type="text" name="FromEmail" id="from" />
<br />
<label for="subject">Subject: </label>
<input type="text" name="Subject" id="subject" />
<br />
<label for="message">Message: </label>
<input type="text" name="MessageText" id="message" />
<input type="submit" value="Send" />
}
<div id="formresult"></div>
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script>
function DisplayConfirmation(result) {
var confirmation = "Message was sent!";
$('#formresult').html(confirmation);
}
</script>
emailconfirmation.cshtml, email.cshtml
#model Project.Models.MessageDetails
#{
ViewBag.Title = "EmailConfirmation";
Layout = "~/Views/_Layout.cshtml";
}
<h2>Congratulatons!</h2>
<div>
You sent a message:
<p>
#Model.MessageText
</p>
</div>
emailcontroller.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Web.Mvc;
using Project.Models;
namespace Project.Controllers
{
public class EmailController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SendEmail(MessageDetails message)
{
return View("EmailConfirmation", message);
}
[HttpPost]
public ActionResult SendEmailAjax(MessageDetails message)
{
return Json(message);
}
}
}
Below is standard code to send email via SMTP. Modify below code according to your change and keep this code in SendEmailAjax method controller. if you are using any organization SMPT server then make sure that IT team allowed you to send email via SMTP. for testing purpose you can use gmail SMTP with your gmail account credentials.
Change or modify below code according to you change:
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.Mail.SmtpClient smtp = new SmtpClient("smtp.xxxxx.com");
smtp.Timeout = 300000;
mail.From = new MailAddress("sender#xxxxx.com");
mail.To.Add("receiver#yyyy.com");
mail.CC.Add("receivercc#yyyy.com");
mail.Subject = "My Subject";
mail.Body = "This is a testing mail";
mail.IsBodyHtml = true;
mail.SubjectEncoding = Encoding.UTF8;
mail.BodyEncoding = System.Text.Encoding.UTF8;
smtp.Send(mail);
For gmail SMTP configuration, you need to tweak smtp configuration like below :
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new NetworkCredential("sender#gmail.com", "password here");
smtp.EnableSsl = enableSSL;
smtp.Send(mail);
refer this article for more details:
https://www.c-sharpcorner.com/blogs/send-email-using-gmail-smtp
let me know if you need more details.
I'm using ASP.Net MVC with EF6, I want to enable user to send email for list of students by click on send button in View then the message will sent to each student in the list (students email address are stored in the list ).
the user will enter his name, email and message,
How to call Contact method from controller for each student when the user click send in View?
public ActionResult Project(int? id)
{
mytable s = new mytable()
{
//this student list contains student information (name, email .. )
Student = (from ss in db.Student
join sp in db.Stu_Projects on ss.studentId equals
sp.StuId
where sp.PId == id
select ss).ToList()
};
return View(s);
}
//I want to call this method for each student in the list when the user click send button in the view
[HttpPost]
[ValidateAntiForgeryToken]
public async Task ContactAsync(String FromName, String FromEmail, String Message,String to)
{
if (ModelState.IsValid)
{
var body = ".....";
var message = new MailMessage();
message.To.Add(new MailAddress(to)); // receiver (each student in the list)
message.Subject = "Testing";
message.Body = string.Format(body, FromName, FromEmail, Message);
message.IsBodyHtml = true;
using (var smtp = new SmtpClient())
{
await smtp.SendMailAsync(message);
}
}
}
#model --------
#{
/**/
ViewBag.Title = "Project";}
<form>
Email
<input type="text" name="email" placeholder="your email..." id="from">
Subject
<input type="text" name="subject" placeholder="Subject..." id="contact-subject">
Message
<textarea name="message" placeholder="Message..." id="contact-message"></textarea>
<button type="submit" class="btn">Send message</button>
</form>
Your inputs name should have the same name like its named in attributes at your function ContactAsync
<input name="FromName"/>
and so on..
also you can read msdnenter link description here
you try this below razor view .
#model --------
#{
/**/
ViewBag.Title = "Project";
}
<form>
Email
<input type="text" name="email" placeholder="your email..." id="email">
Subject
<input type="text" name="contact-subject" placeholder="Subject..." id="contact-subject">
Message
<textarea name="contact-message" placeholder="Message..." id="contact-message"></textarea>
<button type="submit" class="btn">Send message</button>
</form>
How can I make a button "Confirm Subscription" like in MailChimp?
My HTML code so far:
<div itemscope itemtype="http://schema.org/EmailMessage">
<meta itemprop="description" content="Confirmacao de inscricao" />
<div itemprop="action" itemscope itemtype="http://schema.org/ConfirmAction">
<meta itemprop="name" content="Confirmar Agora" />
<div itemprop="handler"
itemscope itemtype="http://schema.org/HttpActionHandler">
<link itemprop="url"
href="http://beta.pegacupom.com.br/confirmnews.aspx?code=xyz" />
</div>
</div>
</div>
The above code was tested in 'https://developers.google.com/gmail/schemas/testing-your-schema' and works correctly.
But when I put that code in my c# website, the email does not send.
Can be some problem with SPF or DKIM ?
This is my code to send mail in C#:
System.Net.Mail.MailMessage objMail = new System.Net.Mail.MailMessage();
objMail.From = new MailAddress("myemail#myDOMAIN.com", "myName");
objMail.To.Add(new MailAddress(emailTO));
objMail.Headers.Add("Content-Type", "text/html");
objMail.Body = mensagem;
objMail.IsBodyHtml = true;
objMail.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1");
objMail.BodyEncoding = Encoding.GetEncoding("ISO-8859-1");
objMail.Subject = assunto;
SmtpClient objSMTP = new SmtpClient("smtp.myDOMAIN.com.br", 587);
System.Net.NetworkCredential objCredential = new System.Net.NetworkCredential("name#myDOMAIN.com.br", "myPASS");
objSMTP.Credentials = objCredential;
objSMTP.Send(objMail);
Why does the email not send?
Try to enable SSL:
objSMTP.Credentials = objCredential;
objSMTP.EnableSsl = true; // add this line
objSMTP.Send(objMail);
Hope this helps.
(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()
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