Sending URL Link to Email ASP.NET WEB API - asp.net-web-api

I'm trying to generate a confirmation link to be sent to the email. The email was sent and received but the link is just not there.
heres the code
[HttpPost]
public async Task<IActionResult> SendEmail(Otp request)
{
randomcode = CreateRandomToken();
var confirmationLink = Url.Action("confirmotp", "Authentication", new {randomcode}, Request.Scheme);
var email = new MimeMessage();
email.From.Add(MailboxAddress.Parse(_config.GetSection("EmailUsername").Value));
email.To.Add(MailboxAddress.Parse(request.EmailAddress));
email.Subject = "Confirmation Link For" + (request.EmailAddress);
email.Body = new TextPart(TextFormat.Html)
{
Text = "Hello " + request.EmailAddress + ", click on the link: " + confirmationLink
}
using var smtp = new SmtpClient();
smtp.Connect(_config.GetSection("EmailHost").Value, 587, SecureSocketOptions.StartTls);
smtp.Authenticate(_config.GetSection("EmailUsername").Value, _config.GetSection("EmailPassword").Value);
smtp.Send(email);
smtp.Disconnect(true);
return Ok();
}
and this is the email I received :
Hello xxx#gmail.com, click on the link:
the link is just not being read. appreciate any help i can get thank you.

Please try this to create the URL:
Uri uri = new Uri(url);
More details can be found in How to build a Url?

Related

Secure Web API Post Method with Username and Password

I have a Web API service hosted in Microsoft Azure. I need a certain POST method to be only accessible with one unique username and password.
I understand the [Authorize] method does a token based authentication but its not tied to a single username and password. In my app, the web api also does the login authentication, so anyone who registers can access this post method if im not mistaken. (Please correct me if im wrong)
I am new to this could you guide me the right way please.
This is my WebAPI Post method i want to secure access to with specific unique username&pass:
[AllowAnonymous]
[HttpPost, Route("send")]
public async Task<NotificationOutcome> Post([FromBody]string message)
{
string hubName = "myHub";
string hubNameDefaultShared = "myHubNameDefaultShared";
NotificationHubClient hub = NotificationHubClient
.CreateClientFromConnectionString(hubNameDefaultShared, hubName, enableTestSend: true);
string installationId = string.Empty;
var templateParams = new Dictionary<string, string>
{
["messageParam"] = message
};
NotificationOutcome result = null;
if (string.IsNullOrWhiteSpace(installationId))
{
result = await hub.SendTemplateNotificationAsync(templateParams).ConfigureAwait(false);
}
else
{
result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
}
return result;
}
And this is how I currently access the POST Method:
var client = new RestClient("myWebApiRouteName");
var request = new RestRequest(Method.POST);
request.AddHeader("Postman-Token", "46c23eba-8ca6-4ede-b4fe-161473dc063a");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddParameter("undefined", messageBody, ParameterType.RequestBody);
try
{
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Issue on sending embedded image to gmail jquery c# mvc

I am facing an issue on sending email. Actually, I am trying to send an email with more text and many images in the body of the mail . I am using jquery and c# controller to make this work out.
The following code explains bit better:
In jquery, am using
$scope.SendEMailNew = function () {
var data = new FormData();
var ToEmail = $("#emailTo").val();
var CcEmail = $("#emailCc").val();
var Subject = $("#emailSubject").val();
var Message = document.getElementById(divID).outerHTML;
data.append("ToEmail", ToEmail);
data.append("CcEmail", CcEmail);
data.append("Subject", Subject);
data.append("Message", Message);
mailsendingIndicator();
$.ajax({
url: ApplicationUrl + 'SendEmail/MailSend',
type: "POST",
processData: false,
contentType: false,
data: data,
success: function (response) {
hidemailsendingIndicator();
toastr.clear();
toastr.success("Mail sent successfully", opts);
},
error: function (er) {
hidemailsendingIndicator();
toastr.clear();
toastr.error("Something went wrong", opts);
}
});
In c# mvc controller, i am using
[AcceptVerbs(HttpVerbs.Post)]
public void MailSend(SendEmail MailDetails)
{
string result = string.Empty;
string from = "FromMail#gmail.com";
using (MailMessage mail = new MailMessage(from,MailDetails.ToEmail))
{
mail.Subject = MailDetails.Subject;
mail.Body = MailDetails.Message;
mail.IsBodyHtml = true;
if (!string.IsNullOrEmpty(MailDetails.CcEmail))
mail.CC.Add(MailDetails.CcEmail);
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.EnableSsl = true;
NetworkCredential networkCredential = new NetworkCredential("FromMail#gmail.com", "Password");
smtp.UseDefaultCredentials = true;
smtp.Credentials = networkCredential;
smtp.Port = 587;
smtp.Send(mail);
}
}
After this code, the email could be sent with embedded images to my official mail id and to my client's mail id but to gmail and to outlook mails, the embedded images not displaying.
Especially, in outlook mails, I am not getting the option to download the image itself. In gmail, i am getting the image as base 64 code. Actually, the image is stored as bytes in database and retrieved to jquery through ajax call. I am facing this issue for long time.
What will be the solution for this kind of issue? Any idea will be a great help
Thanks

send email by smtp and ajax in asp.net mvc

I am beginner in ASP.NET MVC and trying to get email using smtp server and ajax in webApplication. When user click on the button my code will generate the email which will be send to desired ID. I am successfully getting my all values by debug the code. But, I am not able to receive the email there. Although, I am also getting Success massage from browser. But no email is there, in my desirable account.
Index.cshtml
<div>
<a class="btn btn-primary btn-block btn-lg" onclick="SendEmail()" >Click to send Email</a>
</div>
<script>
var SendEmail = function () {
$.ajax({
type: "Post",
url: "/Feedbacks/SendMailToUser",
success: function (data) {
alert("Success");
}
})
}
</script>
FeedbacksController.cs
public JsonResult SendMailToUser() {
bool result = false;
result = SendEmail("abc#gmail.com", "Test", "<p>Hi abc,<br/>This message is for testing purpose. So don't be upset.<br/>Kind Regards,<br/>abc</p>");
return Json(result, JsonRequestBehavior.AllowGet);
}
public bool SendEmail(string toEmail, string subject, string emailBody) {
try
{
string senderEmail = System.Configuration.ConfigurationManager.AppSettings["SenderEmail"].ToString();
string senderPassword = System.Configuration.ConfigurationManager.AppSettings["SenderPassword"].ToString();
SmtpClient client = new SmtpClient("smtp.gmail.com", 578);
client.EnableSsl = true;
client.Timeout = 100000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new NetworkCredential(senderEmail, senderPassword);
MailMessage mailMessage = new MailMessage(senderEmail, toEmail, subject, emailBody);
mailMessage.IsBodyHtml = true;
mailMessage.BodyEncoding = UTF8Encoding.UTF8;
client.Send(mailMessage);
return true;
}
catch (Exception ex) {
return false;
}
}
}
Web.config
<appSettings>
<add key="SenderEmail" value="abc#gmail.com" />
<add key="SenderPassword" value="********" />
</appSettings>
Try to use SmtpClient without object initializer:
SmtpClient client = new SmtpClient();
I have solved my problem because I was using wrong port number. When I use
SmtpClient client = new SmtpClient("smtp.gmail.com", 587);
instead of
SmtpClient client = new SmtpClient("smtp.gmail.com", 578);
I got email there.
you insert wrong port you can use simple 587 and also 25

RestSharp on Windows Phone no set-cookie in response

I have a problem with using the RestSharp client on the Windows Phone device. Starting form the beginning, I have the ASP.NET Web Api service hosted online. I have a request user address: POST: http://my-service-url.com/token where I send Email and Password as a body parameters and I get 201 status code and a cookie in the response. When I do it in fiddler everything works fine. I also have the functional test for my API which is using the RestSharp which is also working correctly:
[Given(#"I fill email and password with correct data and I click log in button")]
public void GivenIFillEmailAndPasswordWithCorrectDataAndIClickLogInButton()
{
//Delete user if he exists
_testUserHelper.DeleteTestUser(TestEmail);
//Create new activated user
Assert.IsTrue(_testUserHelper.CreateTestUser(TestEmail, TestPassword));
//Prepare client
var client = new RestClient(CarRentalsConstants.HostAddress);
var restRequest = new RestRequest("api/token", Method.POST) { RequestFormat = DataFormat.Json };
//Add parameters to request
restRequest.AddBody(new { Email = TestEmail, Password = TestPassword });
//Perform request
_response = client.Execute(restRequest);
}
[When(#"the log in login process finishes")]
public void WhenTheLogInLoginProcessFinishes()
{
Assert.AreEqual(HttpStatusCode.Created, _response.StatusCode, _response.Content);
Assert.IsNotNull(_response.Cookies.SingleOrDefault(q => q.Name == ".ASPXAUTH"););
}
The one above works properly, and the cookie is in the response object.
Now what I try to do on my windows phone looks like this:
var restRequest = new RestRequest("token", Method.POST) {RequestFormat = DataFormat.Json};
restRequest.AddBody(new {Email = email, Password = password});
myWebClient.ExecuteAsync(restRequest, (restResponse, handle) =>
{
switch (restResponse.StatusCode)
{
case HttpStatusCode.Created:
{
var cookie = restResponse.Cookies.SingleOrDefault(q => q.Name == ".ASPXAUTH");
successLogicDelegate(cookie);
}
break;
case HttpStatusCode.BadRequest:
{
HandleBadRequest(restResponse.Content, failureLogicDelegate);
}
break;
default:
msgBox.Show(StringResources.ServerConnectionError);
failureLogicDelegate(null);
break;
}
});
And in this case, the response returns the "Created" status code, but the cookie is then set to null. I have no idea what is happening here, but I am fairly certain that server is sending this cookie, so where does it get lost?
Any help will be really appreciated.

RestSharp on Windows Phone with Request Parameters

I'm working on Windows phone client for one service with Oauth1 API.
In API docs I have something like this:
url: http://example.com/iphone/json/users/
method: GET
parameters:
page_num=[int] - page number, >=1, default=1.
For default page num everything works well:
RestClient HabraClient = new RestClient("http://habrahabr.ru");
HabraClient.Authenticator = OAuth1Authenticator.ForProtectedResource("xxx", "yyyyyy", App.Tokens.Key, App.Tokens.Secret);
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
HabraClient.ExecuteAsync(TokenRequest, (response =>
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
When I execute this request I receive correct response with data.
But if I add parameter (uncomment TokenRequest.AddParameter("page_num", 2); ) I receive "Invalid signature". I have tried to send both int and string parameter.
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
TokenRequest.AddParameter("page_num", 2);
HabraClient.ExecuteAsync(TokenRequest, (response =>
{
try
{
if (response.StatusCode == HttpStatusCode.OK)
{
I receive message "Invalid signature". I have tried string parameter too:
TokenRequest.AddParameter("page_num", "2");
API provider told me, that I have a problem with signature base
string http://oauth.net/core/1.0/#sig_base_example
So, how can i view it? Or maybe you can help me to solve all this
problem?
I think you are breaking the request structure... better to check the request over Fiddler, but try to write something like
var TokenRequest = new RestRequest("/iphone/json/users/?page_num=2", Method.GET);
instead of
var TokenRequest = new RestRequest("/iphone/json/users/", Method.GET);
TokenRequest.AddParameter("page_num", 2);
Hope, it would help.

Resources