Send a mail in mvc 3 - asp.net-mvc

A question regarding send mail in mvc 3.
When I click on btnApply it should send 2 emails to abcd#gmail.com and also send an acknowledgement to (who filled email id in apply form like be 123#gmail.com)
For example:
Email1 : xyz#gamail.com
Email2 : abcd#gmail.com
Email3 : email entered in apply form, e.g 123#gmail.com
when a Email3 click apply send mail from Email1(Sender) to Email2(receiver) & Email3(receiver)
or
when a Email3 click apply send mail from Email2(Sender) to Email2(receiver) & Email3(receiver)
I have form in popup:
#using (Html.BeginForm()){
Your Full Name
<input type="text" value="" id="txtname" name="txtname" required />
Your Email
<input type="email" value="" id="txtemail" name="txtemail" required />
Upload Your Resume
<input name="Upload Saved Replay" id="btnFile" type="file" />
<input type="button" id="btnApply" name="btnApply" value="Apply" />
}
I have a email manager, it only send 1 mail that from xyz#gmail.com to email id that specified in apply form (123#gmail.com )
public class EmailManager
{
private const string EmailFrom = "xyz#gmail.com";
public static void Enquiry( int JobId, string UserName, string Email, string Massage)
{
using (var client = new SmtpClient()) {
using (var message = new MailMessage(EmailFrom, Email)) {
message.Subject = "Successful";
message.Body = "<html><head><meta content=\"text/html; charset=utf-8\" /></head><body><p>Dear " + UserName +
", </p> <p>Thankyou for Registering</p>"
+ "</a></p><div>Best regards,</div><div>Nisha</div></body></html>";
message.IsBodyHtml = true;
client.EnableSsl = true;
client.Send(message);
};
};
}
}

You could use a for loop between two usings.
string[] Emails = { Email,"abcd#gmail.com", "xyz#gmail.com" }
for(var i = 0; i < 3; i++)
{
using (var message = new MailMessage(EmailFrom, Emails[i]))
{
message.Subject = "Successful";
message.Body = "<html><head><meta content=\"text/html; charset=utf-8\" /></head><body><p>Dear " + UserName +
", </p> <p>Thankyou for Registering</p>"
+ "</a></p><div>Best regards,</div><div>Nisha</div></body></html>";
message.IsBodyHtml = true;
client.EnableSsl = true;
client.Send(message);
};
}
Variable Email comes from void Enquiry, others are hard coded

Related

coinpayment api in mvc

I am in beginner programming. I want to get some coins on my site through https://www.coinpayments.net/
I found a class library on that site to call API for transactions
And a form tag to post values
Now I'm confused which one should I use?
<form action="https://www.coinpayments.net/index.php" method="post">
<input type="hidden" name="cmd" value="_pay">
<input type="hidden" name="reset" value="1">
<input type="hidden" name="merchant" value="606a89bb575311badf510a4a8b79a45e">
<input type="hidden" name="currency" value="LTC">
<input type="hidden" name="amountf" value="10.00">
<input type="hidden" name="item_name" value="Test Item">
<input type="image" src="https://www.coinpayments.net/images/pub/buynow-grey.png" alt="Buy Now with CoinPayments.net">
Has anyone experienced the launch of coinpayment in mvc?
You can use this code in your controller
Create a method that a return string with this code:
NameValueCollection data = new NameValueCollection();
data.Add("cmd", "_pay"); // the api method. you can found more method in www.coinpayments.net/apidoc
data.Add("merchant", "your merchant id "); // you can get it in your cp account
data.Add("currency", "USD");
data.Add("item_name", "the item name to buy");
data.Add("want_shipping", "0");
data.Add("quantity", "1");
data.Add("amount", amount);
data.Add("amountf", amount);
data.Add("item_number", "1");
data.Add("invoice", invoce nick);
data.Add("allow_extra", "0");
data.Add("reset", "1");
data.Add("email", "email#example"); // very importat to buyer in refund case
data.Add("custom", "email#example");
data.Add("first_name", "first name");
data.Add("last_name", "last name");
data.Add("ipn_url", "Your ipn url"); // you can get it in your cp account
data.Add("success_url", "https://myfxagents.com/bo/BackOffice/MakeDeposit.aspx?s=yes");
data.Add("cancel_url", "https://myfxagents.com/bo/BackOffice/MakeDeposit.aspx?s=no");
//Prepare the Posting form, Note this return a string
return PreparePOSTForm("https://www.coinpayments.net/index.php", data);
Create other method with name PreparePOSTForm with this code:
private static String PreparePOSTForm(string url, NameValueCollection data)
{
//Set a name for the form
string formID = "PostForm";
//Build the form using the specified data to be posted.
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"" + formID + "\" name=\"" +
formID + "\" action=\"" + url +
"\" method=\"POST\">");
foreach (string key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key +
"\" value=\"" + data[key] + "\">");
}
strForm.Append("</form>");
//Build the JavaScript which will do the Posting operation.
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var v" + formID + " = document." +
formID + ";");
strScript.Append("v" + formID + ".submit();");
strScript.Append("</script>");
//Return the form and the script concatenated.
//(The order is important, Form then JavaScript)
return strForm.ToString() + strScript.ToString();
}
next run your application in that method.
I hope i've helped.

Contact form not sending body and/or subject

So I have been making a simple contact form, and have written the code, and it sends the form, I receive it but it comes blank, no subject and no body.
Reviewing similar issues here on stackoverlow I found A LOT of php solutions but no asp.net that would come helpful in my scenario.
Here is the controller:
public ActionResult Send(Contact c)
{
if (ModelState.IsValid)
{
try
{
MailAddress sender = new MailAddress(c.Email, c.Name);
MailAddress recipient = new MailAddress("mymail#hotmail.com");
MailMessage Message = new MailMessage();
Message.From = sender;
Message.To.Add(recipient);
Message.Subject = c.Subject;
Message.Body = c.Msg;
Message.IsBodyHtml = true;
SmtpClient client = new SmtpClient("smtp.gmail.com");
client.EnableSsl = true;
client.Port = 587;
client.Credentials = new NetworkCredential("gmail#gmail.com", "password");
client.Send(Message);
return Redirect("/Success.html");
}
catch (Exception)
{
return Redirect("/Error.html");
}
}
else
{
return Redirect("www.google.com");
}
}
HTML:
<body>
<form action="/Mail/Send" method="post">
<div id="glavni">
<p>
<label for="TextName">Name:</label>
<input id="TextName" type="text" name="Name" required autofocus />
</p>
<p>
<label for="TextSubject">Subject:</label>
<input id="TextSubject" type="text" name="Subject" required />
</p>
<p>
<label for="TextMail">Email:</label>
<input id="TextMail" type="email" name="Email" required />
</p>
<p>
<label for="TextMsg">Unesite Poruku:</label>
<textarea id="TextMsg" type="text" name="Msg" rows="12" cols="20" ></textarea>
</p>
<p>
<button type="submit">Send</button>
</p>
</div>
</form>
MODEL:
public class Contact
{
public string Name { get; set; }
public string Email { get; set; }
public string Subject { get; set; }
public string Msg {get; set;}
}
The Contact Models class props have the same names as html name attributes and for some reason sends empty emails.
Hope someone can shed some light!
Default all the actions in controllers are GET methods. So you have to specify the HTTP web method as POST
[HttpPost]
public ActionResult Send(Contact c)

ASP MVC - Form input types and model binding issues

I am playing around with server-side form validation, model binding and ModelState and I’ve noticed the following:
If I have an input of type “email” and I insert an invalid email
address (such as ‘hello’), model binding doesn’t work – the value
shows up as ‘null’.
However, if I insert a valid email address,
everything works out.
Can someone explain to me why this happens?
Thanks in advance!
Form:
<form name="contactForm" id="contactF" ng-controller="Contacts" ng-submit="contactForm.$invalid ? sendMessage() : return;" novalidate>
<input type="email" name="email" ng-model="model.EmailAddress" required placeholder="Email"/>
<div ng-messages="contactForm.email.$error" ng-if="contactForm.email.$touched || contactForm.$submitted">
<div ng-messages-include="/Helpers/error-messages.html"></div>
</div>
<textarea name="message" ng-model="model.message" required placeholder="Escreva a sua mensagem aqui."></textarea>
<div ng-messages="contactForm.message.$error" ng-if="contactForm.message.$touched || contactForm.$submitted">
<div ng-messages-include="/Helpers/error-messages.html"></div>
</div>
<br />
<input type="submit" value="Enviar"/>
</form>
Model:
public class HomeContactVM
{
[Required(ErrorMessage = "Error message here")]
public string Name { get; set; }
[Required(ErrorMessage = "Error msg here.")]
[EmailAddress(ErrorMessage = "Please use a valid email address.")]
public string EmailAddress { get; set; }
[Required(ErrorMessage = "Error msg here.")]
public string Message { get; set; }
}
Action method:
[HttpPost]
public JsonResult Contact(HomeContactVM model)
{
string message;
if (ModelState.IsValid)
{
using (SmtpClient client = new SmtpClient())
{
MailMessage msg = new MailMessage()
{
Body = model.Message,
BodyEncoding = Encoding.UTF8,
Subject = "New message from " + model.EmailAddress,
From = new MailAddress(model.EmailAddress),
Sender = new MailAddress("xxx#gmail.com", "xx")
};
int retries = 5;
bool retry = true;
while (retry)
{
try
{
client.Send(msg);
message = "Your message was sent.";
return Json(message, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
if (retries > 0) {
retries--;
}
else {
retry = false;
message = "Something went wrong. Please try again later.";
return Json(message, JsonRequestBehavior.AllowGet);
}
}
}
}
}
message = "Your model is not valid.";
return Json( message, JsonRequestBehavior.AllowGet);
}
So, if anyone is facing the same problem, here's what I found: the problem is not related to ASP, it's due to Angular's default behaviour.
If an input fails validation, Angular sets its value to undefined and it doesn't pass it to the model, hence it showing up as null. A possible workaround is to set ng-model-options="{allowInvalid: true}"
You can find more about this behaviour here: Angular.js - ngModel value is undefined when ng-pattern is set in directive and Get "raw" value from invalid input field
Hope this helps!

SignalR and MVC 5 partial views

Hey guys I have the following issue with Asp SignalR. I want to have a chat with Admins and Users. I have 1 View with two divs (! for the Admin and 1 for the users), which I show or hide by checking the user. So far so good, everything works ! Both the admins and users get the necessary divs and can exchange messages - red div admin, blue div user.. Take a look at the code and I'll explain where I get a problem.
<div class="Admin" id="divMessageAdmin" style="background-color:red;">
<div class="welcome"></div><br />
<div id="divWaitingUser"></div><br />
<input id="txtMessage" type="text" />
<input id="btnSendMessage" type="button" value="Send" />
<div id="divAdminMessage"></div>
</div>
<div class="User" id="divMessageUser" style="background-color:blue;">
<div class="welcome"></div><br />
<input id="txtUserMessage" type="text" />
<input id="btnSendUserMessage" type="button" value="Send" />
<div id="divUserMessage"></div>
</div>
<input id="hUserId" type="hidden" />
<input id="hId" type="hidden" />
<input id="hUserName" type="hidden" />
<input id="hGroup" type="hidden" />
#section scripts {
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
<script src="~/signalr/hubs" type="text/javascript"></script>
<script>
$(function () {
var objHub = $.connection.chatHub;
loadClientMethods(objHub);
$.connection.hub.start().done(function () {
loadEvents(objHub);
});
});
function loadEvents(objHub) {
var name = '#HttpContext.Current.User.Identity.Name';
objHub.server.connect(name);
//alert(name);
$('#btnSendMessage').click(function () {
var msg = $("#txtMessage").val();
if (msg.length > 0) {
var username = $('#hUserName').val();
document.getElementById('txtMessage').value = "";
// <<<<<-- ***** Return to Server [ SendMessageToGroup ] *****
objHub.server.sendMessageToGroup(username, msg);
}
});
$('#btnSendUserMessage').click(function () {
// alert("wrks");
var msg = $("#txtUserMessage").val();
if (msg.length > 0) {
var username = $('#hUserName').val();
document.getElementById('txtUserMessage').value = "";
// <<<<<-- ***** Return to Server [ SendMessageToGroup ] *****
objHub.server.sendMessageToGroup(username, msg);
}
});
$("#txtMessage").keypress(function (e) {
if (e.which == 13) {
$('#btnSendMessage').click();
}
});
}
function loadClientMethods(objHub) {
objHub.client.getMessagesAdmin = function (userName, message) {
$(".txtMessage").val('');
$('#divAdminMessage').append('<div><p>' + userName + ': ' + message + '</p></div>');
var height = $('#divAdminMessage')[0].scrollHeight;
$('#divAdminMessage').scrollTop(height);
}
objHub.client.getMessagesUser = function (userName, message) {
$("#txtMessage").val('');
$('#divUserMessage').append('<div><p>' + userName + ': ' + message + '</p></div>');
var height = $('#divUserMessage')[0].scrollHeight;
$('#divUserMessage').scrollTop(height);
}
objHub.client.onConnected = function (id, userName, UserID, userGroup, flag) {
alert(flag);
var strWelcome = 'Welcome' + +userName;
$('.welcome').append('<div><p>Welcome:' + userName + '</p></div>');
$('#hId').val(id);
$('#hUserId').val(UserID);
$('#hUserName').val(userName);
$('#hGroup').val(userGroup);
if ( flag == "1") {
$("#divMessageUser").hide();
$("#divMessageAdmin").show();
}
else {
$("#divMessageUser").show();
$("#divMessageAdmin").hide();
}
}
}
</script>
}
The thing is, that I want these two divs to be in separated Partial Views. This is what I'm trying. At the beginning of my page I check if the user is authenticated, if it is I fire a [ChildActionOnly] action method in my ChatController:
<h2>Chat</h2>
#{
if (!User.Identity.IsAuthenticated)
{
#Html.Partial("_UnauthenticatedUserForm");
}
else
{
Html.RenderAction("AuthenticatedUsersChat");
}
}
and my action method in the controller
[ChildActionOnly]
public ActionResult AuthenticatedUsersChat()
{
AppContext db = new AppContext();
User user = db.Users.Single(usr => usr.Email == User.Identity.Name);
int isAdmin = user.AdminCode;
if (isAdmin == 0)
{
return PartialView("_UserChatPartial");
}
else
{
return PartialView("_AdminChatPartial");
}
}
this works and the partial views are returning in the way I want. In both partial views I've moved the divs ONLY! Admin Partial:
<div class="Admin" id="divMessageAdmin" style="background-color:red;">
<div class="welcome"></div><br />
<div id="divWaitingUser"></div><br />
<input id="txtMessage" type="text" />
<input id="btnSendMessage" type="button" value="Send" />
<div id="divAdminMessage"></div>
</div>
and UserPartial
<div class="User" id="divMessageUser" style="background-color:blue;">
<div class="welcome"></div><br />
<input id="txtUserMessage" type="text" />
<input id="btnSendUserMessage" type="button" value="Send" />
<div id="divUserMessage"></div>
</div>
BUT somehow then only the Administrator can see the messages. The user can send messages (admin receives it), but the user cannot see his or admins messages - result. I simply don't see any logic why only the user can't see the messages. Please if you have any ideas help me. Thanks in advance !
my method for the messages in the hub class
public void SendMessageToGroup(string userName, string message)
{
if (UsersList.Count != 0)
{
var strg = (from s in UsersList where (s.Email == userName) select s).First();
MessageList.Add(new MessageInfo { UserName = userName, Message = message, UserGroup = strg.UserGroup });
string strgroup = strg.UserGroup;
Clients.Group(strgroup).getMessagesAdmin(userName, message);
Clients.Group(strgroup).getMessagesUser(userName, message);
}
}
// End SendMessage
and the connection method in the hub
public void Connect(string userName)
{
//if freeflag==0 ==> Busy
//if freeflag==1 ==> Free
//if tpflag==0 ==> User
//if tpflag==1 ==> Admin
var id = Context.ConnectionId;
string userGroup = "";
AppContext db = new AppContext();
var userInfo = (from m in db.Users
where m.Email == HttpContext.Current.User.Identity.Name
select new { m.UserId, m.Email, m.AdminCode, m.FirstName, m.LastName }).FirstOrDefault();
try
{
if ((int)userInfo.AdminCode == 0)
{
var strg = (from s in UsersList where (s.tpflag == "1") && (s.freeflag == "1") select s).First();
userGroup = strg.UserGroup;
strg.freeflag = "0";
//now add USER to UsersList
UsersList.Add(new User { ConnectionId = id, UserId = userInfo.UserId, Email = userName, UserGroup = userGroup, freeflag = "0", tpflag = "0", });
var flag = (from s in UsersList where (s.Email == userName) select s.tpflag);
Groups.Add(Context.ConnectionId, userGroup);
Clients.Caller.onConnected(id, userName, userInfo.UserId, userGroup, flag);
}
else
{
UsersList.Add(new User { ConnectionId = id, UserId = userInfo.UserId, Email = userName, UserGroup = userInfo.AdminCode.ToString(), freeflag = "1", tpflag = "1" });
var flag = (from s in UsersList where (s.Email == userName) select s.tpflag);
Groups.Add(Context.ConnectionId, userInfo.AdminCode.ToString());
Clients.Caller.onConnected(id, userName, userInfo.UserId, userInfo.AdminCode.ToString(), flag);
}
}
catch
{
Clients.Caller.NoExistAdmin();
}
}
Sounds like your "blue" user is not in the group strgroup which you're trying to send to. Set a breakpoint to this line in the SendMessageToGroup method and check it.
Also strange code in if ((int)userInfo.AdminCode == 0) why to get First from UsersList and then add to it again? May be exception here?

Get file upload for email attachment umbraco

I am creating one simple page which has one form. Its code is like below :
#inherits Umbraco.Web.Mvc.UmbracoTemplatePage
#using System.Net;
#using System.Net.Mail;
#{
if(IsPost)
{
//Way 1: to get attachment
var fileSavePath = "";
var uploadedFile = Request.Files[0];//Here not getting file name
var fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/media/" + fileName);
uploadedFile.SaveAs(fileSavePath);
FileInfo info = new FileInfo(fileSavePath);
string[] ext = fileName.Split('.');
//Way 2 :
var a = Request["fluld"];//Getting file name only
var b = Request.Files;//Getting null here
string d = Path.GetFullPath(Request["fluld"]);
string c = string.Empty;
try
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("xyz#gmail.com");
mail.To.Add("xyz#gmail.com");
mail.Subject = "Test Mail";
mail.Body = "This is for testing SMTP mail from GMAIL";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment("filepath");
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("xyz#gmail.com", "******");
SmtpServer.EnableSsl = true;
//SmtpServer.Send(mail);
//MessageBox.Show("mail Send");
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
}
<form method="post">
<input type="file" name="fluld" id="fluld" />
<input type="submit" value="Sub"/>
</form>
I am not able to get file for email attachment with this Request.Files. Help me with this. Any thing I need to add? This code is in template of umbraco.
Thanks
Dipa
Your form needs to be a 'multipart/form-data'
<form enctype="multipart/form-data" method="post">
<input type="file" name="fluld" id="fluld" />
<input type="submit" value="Sub"/>
</form>

Resources