Issue on sending embedded image to gmail jquery c# mvc - image

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

Related

Sending URL Link to Email 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?

How to download the model as a JSON file?

My model is held in a JavaScript object on the client side, where the user can edit its properties via the UI controls. I want to offer the user an option to download a JSON file representing the model they're editing. I'm using MVC core with .net 6.
What I've tried
Action method (using Newtonsoft.Json to serialize the model to JSON):
public IActionResult Download([FromForm]SomeModel someModel)
{
var json = JsonConvert.SerializeObject(someModel);
var characters = json.ToCharArray();
var bytes = new byte[characters.Length];
for (var i = 0; i < characters.Length; i++)
{
bytes[i] = (byte)characters[i];
}
var stream = new MemoryStream();
stream.Write(bytes);
stream.Position = 0;
return this.File(stream, "APPLICATION/octet-stream", "someFile.json");
}
Code in the view to call this method:
<button class="btn btn-primary" onclick="download()">Download</button>
And the event handler for this button (using jQuery's ajax magic):
function download() {
$.ajax({
url: 'https://hostname/ControllerName/Download',
method: 'POST',
data: { someModel: someModel },
success: function (data) {
console.log('downloading', data);
},
});
}
What happened
The browser console shows that my model has been posted to the server, serialized to JSON and the JSON has been returned to the browser. However no file is downloaded.
Something else I tried
I also tried a link like this to call the action method:
#Html.ActionLink("Download", "Download", "ControllerName")
What happened
This time a file was downloaded, however, because ActionLink can only make GET requests, which have no request body, the user's model isn't passed to the server and instead the file which is downloaded represents a default instance of SomeModel.
The ask
So I know I can post my model to the server, serialize it to JSON and return that JSON to the client, and I know I can get the browser to download a JSON-serialized version of a model, but how can I do both in the same request?
Edit: What I've done with the answer
I've accepted Xinran Shen's answer, because it works as-is, but because I believe that just copying code from Stack Overflow without understanding what it does or why isn't good practice, I did a bit of digging and my version of the saveData function now looks like this:
function saveData(data, fileName) {
// Convert the data to a JSON string and store it in a blob, a file-like
// object which can be downloaded without it existing on the server.
// See https://developer.mozilla.org/en-US/docs/Web/API/Blob
var json = JSON.stringify(data);
var blob = new Blob([json], { type: "octet/stream" });
// Create a URL from which the blob can be downloaded - see
// https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL
var url = window.URL.createObjectURL(blob);
// Add a hidden hyperlink to the page, which will download the file when clicked
var a = document.createElement("a");
a.style = "display: none";
a.href = url;
a.download = fileName;
document.body.appendChild(a);
// Trigger the click event on the hyperlink to download the file
a.click();
// Release the blob's URL.
// Browsers do this when the page is unloaded, but it's good practice to
// do so as soon as it's no longer needed.
window.URL.revokeObjectURL(url);
// Remove the hidden hyperlink from the page
a.remove();
}
Hope someone finds this useful
First, Your code is right, You can try to access this method without ajax, You will find it can download file successfully,But You can't use ajax to achieve this, because JavaScript cannot interact with disk, you need to use Blob to save the file. change your javascript like this:
function download() {
$.ajax({
url: 'https://hostname/ControllerName/Download',
method: 'Post',
data: { someModel: someModel },,
success: function (data) {
fileName = "my-download.json";
saveData(data,fileName)
},
});
}
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var json = JSON.stringify(data),
blob = new Blob([json], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
I think you may need FileStreamResult, also you need to set the MIME type to text file or json file.
// instead of this
return this.File(stream, "APPLICATION/octet-stream", "someFile.json");
// try this
return new FileStreamResult(stream, new MediaTypeHeaderValue("text/plain"))
{
FileDownloadName = "someFile.txt"
};
// or
return new FileStreamResult(stream, new MediaTypeHeaderValue("application/json"))
{
FileDownloadName = "someFile.json"
};
Reference: https://www.c-sharpcorner.com/article/fileresult-in-asp-net-core-mvc2/

How I can catch and save to file data from form sended by AJAX in ColdFusion

I have the followign JavaScript code:
function upload(blob) {
var xhr = new XMLHttpRequest();
var url = "test.cfm";
xhr.onload=function(e) {
if(this.readyState === 4) {
console.log("Server returned: ",e.target.responseText);
}
};
var fd=new FormData();
fd.append("randomname",blob);
xhr.open("POST",url,true);
xhr.send(fd); }
How can I catch it on server side by ColdFusion and Save blob object to File?
Can someone please some code sample. Thx.
PS. I am pretty new in CF.
Since you are using formdata, you can access the form variable with ajax, just like you would with normal http requests.
#form.randomname#
#form['randomname']#
So you could save the content in a file with
<cfscript>
fileWrite( 'c:\myfile.txt', form.randomname );
</cfscript>

dojo ajax request to spring mvc,getting http 400

before starting let me say that I am new to dojo and this is my first project in dojo:
when I am trying to send json data from rest client (some chrome ext) it working for me,I mean to say that my spring mvc part is working, but when i am trying to send the same json from dojo code I am getting http 400 exception
my dojo code:
postCreate : function() {
this.inherited(arguments);
var form = dom.byId("contactSubmit");
on(form, "click", function(evt) {
var box0 = registry.byId("inputEmail");
var box1 = registry.byId("inputName");
var box3 = registry.byId("message");
alert("values are: " + box0.get("value"));
jsonData = {"email":"some#gmail.com","inputName":"some name","message":"some msg"};
request.post("/pool/conta", {
data: jsonData,
handleAs: "json",
headers: {
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json"
}
}).then(function(text){
alert("values are send"+text);
});
});
}
the jason data that I am sending from rest client is which is working:
{"email":"some#gmail.com","inputName":"some name","message":"some msg"}
my spring mvc method is below:
#RequestMapping(value="/conta", method = RequestMethod.POST)
public #ResponseBody Contact getShopInJSON(#RequestBody Contact contact2) {
Contact contact = new Contact();
contact.setEmail("pro#gmail.com");
contact.setInputName("pro");
contact.setMessage("msg");
System.out.println("***********************"+contact2.getEmail());
return contact;
}
pool is name of application
The json data as passed in post request requires string to be crypted with "\" so that the javascript can handle the double codes as is within string(double quoted string).
Thus, the line
jsonData = {"email":"some#gmail.com","inputName":"some name","message":"some msg"};
would work if written as below
jsonData = " {\"email\":\"some#gmail.com\",\"inputName\":\"some name\",\"message\":\"some msg\"} " ;
Its working now, I have used toJson from dojo/_base/json" utility before passing it to request.post

Dot Net Nuke Ajax Response Returning HTML

I can't seem to get a JSON response from an Ajax post within a Dot Net Nuke site. It returns HTML as a response instead.
I was able to get this to work in a normal test site just fine and am wondering if anybody may know what I need to do.
Below is the code I'm testing with for now:
JavaScript:
$("#ClearTaxFormButton").click(function (e) {
e.preventDefault();
var testValue = 7;
$.ajax({
type: "GET",
url: "localhost/mywebsite/tabid/100/Default.aspx/SumbitByAjaxTest",
data: '{ "taxRate":' + testValue + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
//$("#Result").text(msg.d);
alert(msg.d);
}
});
});
C# Function:
//just using ths for testing
[WebMethod]
public static string SumbitByAjaxTest(string taxRate)
{
return taxRate;
}
Like I said, this exact code (aside from a different URL) works fine in a normal .NET site but when I move it over to the Dot Net Nuke site, it returns HTML.
Any ideas??
DNN's service layer allows you to follow a Webapi like approach, I think you'll find that easier for controlling the data to/from.
Here's an example of a controller for an open source articles module
https://dnnsimplearticle.codeplex.com/SourceControl/latest#cs/services/DnnSimpleArticleController.cs
Something like
public HttpResponseMessage GetAllArticles(int portalId, bool sortAsc)
{
try
{
//todo: get the latest X articles?
var articles = ArticleController.GetAllArticles(portalId, sortAsc);
//because of the circular reference when cerealizing the taxonomy within content items we have to build out our article view models manually.
var cleanArticles = new List<ArticleViewModel>();
foreach (Article a in articles)
{
var newArt = new ArticleViewModel
{
ArticleId = a.ArticleId,
Body = WebUtility.HtmlDecode(a.Body),
CreatedByUser = a.CreatedByUser,
CreatedByUserId = a.CreatedByUserId,
CreatedOnDate = a.CreatedOnDate,
Description = WebUtility.HtmlDecode(a.Description),
LastModifiedByUser = a.LastUpdatedByUser,
LastModifiedByUserId = a.LastModifiedByUserId,
LastModifiedOnDate = a.LastModifiedOnDate,
ModuleId = a.ModuleId,
Title = a.Title,
url = DotNetNuke.Common.Globals.NavigateURL(a.TabID, "", "&aid=" + a.ArticleId)
};
cleanArticles.Add(newArt);
}
var articleViewModels = new ArticleViewModels
{
Articles = cleanArticles
};
return Request.CreateResponse(HttpStatusCode.OK, articles);
}
catch (Exception exc)
{
DnnLog.Error(exc); //todo: obsolete
return Request.CreateResponse(HttpStatusCode.BadRequest, "error in request"); //todo: probably should localize that?
}
}

Resources