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.
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 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 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";
}
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.
(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()