Cannot embed inline image in outlook when image is in barcode - c#

I have created one barcode image and convert it in data stream and embed it inline and pass it through smtp mail. Now recipient can able to see that barcode in webmail, but cannot able to see it outlook it is coming as red cross (x).
Any help is highly appreciated.
private string MyMethod(string myInputStr)
{
var myBarcodeObj = new Barcode();
string myString = string.Format("{0}\t", myInputStr);
byte[] myGeneratedCode = myBarcodeObj.GenerateCode(myString);
string myBase64ImageString = ConvertBytesToBase64(myGeneratedCode );
objBEorder.ERPOrder.ImgBarcode = new System.Web.UI.WebControls.Image()
{
ImageUrl = "data:image/jpg;base64," + myBase64ImageString
};
}
private string ConvertBytesToBase64(byte[] imageBytes)
{
return Convert.ToBase64String(imageBytes);
}

HTML images are rendered by Word in Outlook, and it does not support embedded ("data:image/jpg;base64) images.
Add the image as an attachment and set its Content-ID MIME header. The HTML body should refer to the image thorugh the cid attribute (<img src="cid:xyz">)

Related

showing a large pdf file embedded on a browser

I am trying to show a pdf file embedded in my browser window. My code shows a small pdf file on the browser, but it does not show the large pdf file. Below is my code:
Model class:
public class FileModel
{
public int FileModelId { get; set; }
public byte[]? FileName { get; set; }
public string? Url { get; set; }
public string InlineMarkup
{
get
{
return String.Format("data:application/pdf;base64,{0}", Convert.ToBase64String(this.FileName));
}
}
}
My controller class Index method:
public async Task<IActionResult> Index()
{
using (MemoryStream stream = new MemoryStream())
{
string filePath = Path.Combine("FilledPDFFiles//Package2022.pdf");
string filePath2 = Path.Combine(_environment.WebRootPath, "FilledPDFFiles//Package2022.pdf");
byte[] bytes = System.IO.File.ReadAllBytes(filePath2);
FileModel profile = new FileModel
{
Url = filePath,
FileName = bytes
};
return View(profile);
}
My razor View:
#model AckPackage.Models.FileModel
<embed src="#Model.InlineMarkup" width="100% " height="1000px" type="application/pdf">
Above code works fine if the pdf file is around 373 KB. I am trying to embed a 2330 KB file on the web browser. Is their any way to display large pdf files. Below is my directory structure
Hello Md Farid Uddin Kiron,
I tried your solution, but getting this error. The pdf file size is around 3000 KB. Please see the screen shot:
below are the chrome browser settings:
error in pdf file. i put a new pdf file and I can open that file, but as soon as I run my code, the file becomes corrupt and cannot be viewed. below is the screen shot:
I am trying to embed a 2330 KB file on the web browser. Is their any
way to display large pdf files.
Well, seems you are having issue on displaying large PDF file on brwser. Obviously, you can. In fact, the way is much cleaner and efficient no matter how large the pdf is. I have checked with up to 10,000 KB size. Here is the implementation below:
Embed Large PDF:
Controller:
public IActionResult DisplayLargePdf()
{
using (MemoryStream stream = new MemoryStream())
{
string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"1000px\" height=\"600px\">";
embed += "If you are unable to view file, you can download from here";
embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
embed += "</object>";
TempData["Embed"] = string.Format(embed, "/YourFolderName/YourFileName.pdf");
return View();
}
}
View:
#Html.Raw(TempData["Embed"])
Output:
Browser Seettings:
If your browser restricts you, in that scenario, you should configure your browser setting. For Edge you can configure as following.
In addition, if you would like to download in that scenario you could have a try following code snippet:
Download Large Pdf:
public ActionResult DownloadlargePDF()
{
string physicalPath = "wwwroot/YourFolderName/YourPDFFileName.pdf";
byte[] pdfBytes = System.IO.File.ReadAllBytes(physicalPath);
MemoryStream stream = new MemoryStream(pdfBytes);
string mimeType = "application/pdf";
return new FileStreamResult(stream, mimeType)
{
FileDownloadName = "AnyNameYouWantToSet.pdf"
};
}
Update:
Please get rid of System.IO.File.WriteAllBytes(path + "/Cambridge-IELTS-15-General.pdf", stream.ToArray()); and the string path = Path.Combine(_environment.ContentRootPath, "Documents"); line it will resolve your issue. The key part is <object data which would display PDF for you. I have tested just google chrome as well and working accordingly.

Embed byte array data as image to email

I have tried to embed a base64 type and not working. The image not displayed in the email.
string imreBase64DataHeader = LogoFromByteArray(_org.O_Logo);
image = "<img src='data:image/png;base64," + imreBase64DataHeader + "' alt='img' />";
body += string.Format("<div>{0}</div> <br/><br/>", image);
Note: I have a pdf attachment in the email already.
The logo is saved in the db as byte array and I need to add this in the email signature.
Thank you in advance for the help.
Base64 images are not supported in Outlook for desktop. Instead, you need to save the image on the disk and then attach it to the email. Then in the message body you can refer to such attachments by using the cid: prefix:
.Attachments.Add "C:\Users\JoeSchmo\Pictures\ImageName.jpg", olByValue, 0
.HTMLBody = "<BODY><IMG src=""cid:ImageName.jpg"" width=200> </BODY>"
You may also consider setting the following properties on the attachment:
Const PR_ATTACH_MIME_TAG = "http://schemas.microsoft.com/mapi/proptag/0x370E001E"
Const PR_ATTACH_CONTENT_ID = "http://schemas.microsoft.com/mapi/proptag/0x3712001E"
Const PR_ATTACHMENT_HIDDEN = "http://schemas.microsoft.com/mapi/proptag/0x7FFE000B"
Set oPA = Attachment.PropertyAccessor
oPA.SetProperty PR_ATTACH_MIME_TAG, "image/jpeg"
oPA.SetProperty PR_ATTACH_CONTENT_ID, "cidName"
oPA.SetProperty PR_ATTACHMENT_HIDDEN, True
Read more about this in the Embed Images in New Messages using a Macro article.
You have to first convert byte array to base64encoded string.
Try this code.
string imageTag = "<img id ='Icon' src='data:image/*;base64,"+(Convert.ToBase64String(imageByte))+"' >";
Also if you are using outlook as your email client you might need to download the image in the email preview.

How to Save Images In Folder After cropping using Croppie (Jquery Image cropper)

I'm Trying to save the image after cropping into folder &image path to the database using croppie but it convert to base64 & i also dont know how to send this data to controller & how can i save the image into a folder & its path to the database.
I already try to save file.write function but it was not sending back to image data to the controller
public ActionResult AddProduct(Tbl_Product product,HttpPostedFileBase file_photo)
{
string name = null;
string ext = null;
if (ModelState.IsValid==true)
{
if (file_photo != null)
{
name = Path.GetFileNameWithoutExtension(file_photo.FileName);
ext = Path.GetExtension(file_photo.FileName);
string path = Path.Combine(Server.MapPath("~/ProductImages"), name + ext);
file_photo.SaveAs(path);
}
product.ProductImage = name + ext;
product.CreatedDate = DateTime.Now;
_unitofwork.GetRepositoryInstance<Tbl_Product>().Add(product);
return RedirectToAction("Product");
}
else
{
ViewBag.CategoryList = GetCategory();
return View();
}
}
i want to save image in folder & path to database but it shows base64 image
I have written a complete post on using croppie.js with c#
A function to set croppie,
Function to crop the Image,
Then send the image date to the web method by ajax,
Convert image data to image and save it in the folder.
Here is the link,
https://shaktisinghcheema.com/image-upload-with-cropping/
Also, you may run into an issue of timeout when sending image data to web method,
Here is the link of solution to it:
Error while sending base64 string through json
I hope this might help someone who lands on this question.
In croppie, after cropping the image you will get result in base64 format, keep this base64 in some hidden field like below,
$('#imagebase64').val(base64_data);
And in you controller action method, use the following code to store image in folder.
if (product.imagebase64 != null)
{
try
{
var base64Data = Regex.Match(product.imagebase64, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
byte[] imageBytes = Convert.FromBase64String(base64Data);
string filename = DateTime.Now.ToString("ddMMyyyy_hhmmss"); // You can write custom name here
string path = Path.Combine(Server.MapPath("~/ProductImages"), filename + ".jpg");
System.IO.File.WriteAllBytes(path, imageBytes);
}
catch (Exception ex)
{
}
}

Web beacon trafficking with MimeKit

Is there any possible way to create a web beacon/bug with mimekit? I have taken a look on how to embed images within the message body in MimeKit but I can't seem to figure out how to transform this into a web beacon/bug, does anybody know a way how to do this?
My code:
private string makeMailContents(Klant klant, Mail mail)
{
var builder = new BodyBuilder();
var path = Path.Combine("wwwroot/trackers/track_open.png");
var img = builder.LinkedResources.Add(path);
byte[] data = Convert.FromBase64String(mail.Content);
string decoded = Encoding.UTF8.GetString(data);
Type mt = mail.GetType();
PropertyInfo mp;
string code;
string final = "";
img.ContentId = MimeUtils.GenerateMessageId();
return string.Format(#"<img src=""cid:{0}"">", img.ContentId);// this does not load anything, I want this to be the url to the image
}
fixed it, I just had to return the following:
return string.Format(#"<img src=""{0}"">", "http://localhost:5000/api/mail/track/open");
for some reason this only works with string.Format. You don't need MimeKit related functions to do this.
NOTE
The request only works once, at least in chrome, I believe that this is because of the cache

Image object (as a mail attachment) filepath

I am creating an add in for outlook 2007, that embeds smileys to the body of an email.
And the method i am using is as follows:
if (!string.IsNullOrEmpty(mail.HTMLBody) && mail.HTMLBody.ToLower().Contains("</body>"))
{
int mailBodyLength;
if (mail.Body == null)
{
mailBodyLength = 0;
}
else
{
mailBodyLength = mail.Body.Length;
}
//Get Image + Link
Image imagePath = image;
object linkAddress = "http://www.pentavida.cl";
//CONTENT-ID
const string SchemaPR_ATTACH_CONTENT_ID = #"http://schemas.microsoft.com/mapi/proptag/0x3712001E";
string contentID = Guid.NewGuid().ToString();
//Attach image
mail.Attachments.Add(imagePath, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, mailBodyLength, Type.Missing);
mail.Attachments[mail.Attachments.Count].PropertyAccessor.SetProperties(SchemaPR_ATTACH_CONTENT_ID, contentID);
//Create and add banner
string banner = string.Format(#"<br/><a href=""{0}"" ><img src=""cid:{1}"" ></a></body>", linkAddress, contentID);
mail.HTMLBody = mail.HTMLBody.Replace("</body>", banner);
mail.Save();
}
In this line : mail.Attachments.Add(imagePath, Microsoft.Office.Interop.Outlook.OlAttachmentType.olByValue, mailBodyLength, Type.Missing);
I am adding an image object (imagePath) but its throwing an exception, it worked when i put a full path of an image in the method, now i am passing through an image that was got from my resources folder. I am assuming that the method is failing because it needs a path of the image and not the Image object. How do i get the Image path name from this Image object to pass into this method?
I have an image that i got from my resources folder, i need the path of that image. How do i get that path?
Image imagePath = image;
I need the image path because i am adding the image to a new mail in outlook.
But when i pass through the Image object it throws an exception of:
Member not found. (Exception from HRESULT: 0x80020003 (DISP_E_MEMBERNOTFOUND))
But passing a string works fine.
thanks in advance.

Categories

Resources