Xlsio Excel file as Mailkit attachement - c#

I'm using Mailkit to send email, and I would like to send a created Excel file (thanks to Xlsio) as an Email attachement.
I achieved to send the email, I see the attachement with good extension (.xlsx) but when I want to open it I have an error "Format or extention is not valid".
This is what I've coded for creating the Excel file
FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
workbook.SaveAs(stream, ExcelSaveType.SaveAsXLS);
FileAttachementDto file = new()
{
FileName = fileName,
File = stream, // Type of File property is Stream
};
What I'v coded for adding the file to the email attachements
var attachements = MimeEntity.Load(
new ContentType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
new MemoryStream(myFile.File.ReadAsBytes()));
bodyBuilder.Attachments.Add(attachements);
Thanks

Don't do this:
var attachements = MimeEntity.Load(
new ContentType("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet"),
new MemoryStream(myFile.File.ReadAsBytes()));
That is for parsing HTTP web responses.
Just do this instead:
var attachment = new MimePart ("application", "vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
FileName = "fileName.xls",
ContentTransferEncoding = ContentEncoding.Base64,
Content = new MimeContent (new MemoryStream (myFile.File.ReadAsBytes ()))
};

We suggest you to set the workbook version as Xlsx before saving the Excel document and remove the ExcelSaveType.SaveAsXLS parameter in SaveAs method of IWorkbook.
Code Snippet:
FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
workbook.Version = ExcelVersion.Xlsx;
workbook.SaveAs(stream);
FileAttachementDto file = new()
{
FileName = fileName,
File = stream, // Type of File property is Stream
};
​​​

Related

How to update the excel file cell data, when the file is created using a template in C#?

I am creating a new excel file using a template file, but I am unable to edit the contents in the new file created, please assist with the same.
Thanks in advance.
FileStream fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read);
using (ExcelPackage package = new ExcelPackage(fileStream))
{
package.Save();
}
string name = "filecreated.xlsx";
string fileType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
fileStream.Position = 0;
//return file
return File(fileStream, fileType, name);```
It Seems like you are opening the file in read only access mode
FileStream fileStream = new FileStream(filepath, FileMode.Open,
FileAccess.Read);
Will you please try like
FileInfo existingFile = new FileInfo(filepath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//As we have not modified the file, its useless to call Save()
//This will override the opened file
package.Save();
}

Missing Email Header after export to mht or eml with Exchange Web Services

i'm trying to export a email as mht or eml.
The export is working but the content is incomplete.
The Export only contains the content of the green box.
The Content from the red box is missing (sender, recipient, subject, sent).
string emlFileName = #"C:\export\email.eml";
string mhtFileName = #"C:\export\email.mht";
// Save as .eml.
using (FileStream fs = new FileStream(emlFileName, FileMode.Create, FileAccess.Write))
{
fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
}
// Save as .mht.
using (FileStream fs = new FileStream(mhtFileName, FileMode.Create, FileAccess.Write))
{
fs.Write(email.MimeContent.Content, 0, email.MimeContent.Content.Length);
}

Send mail with PDFDocument without filename in C#

i have the following Code :
How can i send the PDFDocument "doc" without saving it (without filename)?
To create an attachment object i need a filename (path), but i dont have one.
Just choose a name for the file
var stream = new MemoryStream();
doc.WriteToStream(stream);
stream.Position = 0;
var contentType = new ContentType(MediaTypeNames.Application.Pdf)
{
Name ="withoutfilename.pdf";
};
var attachment = new Attachment(stream, contentType);
mailMsg.Attachments.Add(attachment);

How to open save dialog box for saving pdf

I truly appreciate your suggestions. I am using MVC3 and I want user to save to his own path by opening a dialog with password protected. Can you guys please help me on this.
Below is my code:
mydoc.GenerateLetter(PdfData);
string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
using (MemoryStream m = new MemoryStream())
{
m.Write(mydoc.DocumentBytes, 0, mydoc.DocumentBytes.Length);
m.Seek(0, SeekOrigin.Begin);
string OutputFile = Path.Combine(WorkingFolder, PdfData.Name + ".pdf");
using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(m);
PdfEncryptor.Encrypt(reader, output, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS);
}
}
If you want to show a Save As dialog so that the user can choose the location to save the PDF file on his computer you could use the Content-Disposition HTTP header and set it to attachment. Also in an ASP.NET MVC application instead of saving the file to the server (which is what your code currently does), you should stream it to the client:
public ActionResult DownloadPdf()
{
var mydoc = ...
mydoc.GenerateLetter(PdfData);
byte[] pdf = mydoc.DocumentBytes;
var reader = new PdfReader(pdf);
using (var encrypted = new MemoryStream())
{
PdfEncryptor.Encrypt(reader, encrypted, true, "abc123", "secret", PdfWriter.ALLOW_SCREENREADERS);
return File(encrypted.ToArray(), "application/pdf", PdfData.Name + ".pdf");
}
}
Now when a user navigates to this controller action /SomeController/DownloadPdf he will be presented with a Save As dialog allowing him to download the encrypted PDF file and store it in a chosen location on his computer.

How to open a text file in read-only mode means there i can not perform write?

I am trying it too much time but can not achieve the goal. File is opened but its opened in write mode.
Code-
in txtpath.text, I am passing the path of the text:
System.IO.FileInfo fileObj= new System.IO.FileInfo(txtPath.Text);
fileObj.Attributes = System.IO.FileAttributes.ReadOnly;
System.Diagnostics.Process.Start(fileObj.FullName);
use the File.OpenRead method
string sFilename = "myfile.txt";
FileStream SR = File.OpenRead(sFilename);
Opening a file to only read it's contents:
// Open the stream and read it back.
using (FileStream fs = File.OpenRead(path))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b,0,b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
More about File.OpenRead: http://msdn.microsoft.com/en-us/library/system.io.file.openread.aspx
Setting a file's ReadOnly attribute and executing it:
File.SetAttributes(txtPath.Text, File.GetAttributes(txtPath.Text) | FileAttributes.ReadOnly);
System.Diagnostics.Process.Start(txtPath.Text);

Categories