I have a PDF being generated by PDFTK (PDFToolkit). I am trying to add the ReturnedPDF which gets saved to the downloads folder to a MailMessage in C#.
The PDF downloads with no problem; however, attaching isn't going so well.
var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
var newpdffer = PDFHelper.ReturnPDF(pdfContents, "100-" + genUUID.Text + ".pdf");
Returns my PDF filled in just fine (as a downloaded file)... however, I can't seem to figure out how to attach it in MemoryStream. I am simply trying to attach it and email it.
I receive the email - but I get an attachment with nothing in it. SEE MY CODE BELOW:
var doc = new Document();
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);
doc.Open();
//doc.Add(new Attachment(thispdfnew));
//doc.Add(new Paragraph("Second Paragraph"));
writer.CloseStream = false;
doc.Close();
memoryStream.Position = 0;
string toemailaddress = email.Text;
string youremailadd = youremail.Text;
MailMessage mm = new MailMessage();
mm.To.Add(new MailAddress(youremail.Text));
MailAddress addressBCC = new MailAddress(email.Text);
mm.Bcc.Add(addressBCC);
mm.Subject = "New form Completed "+Preparedby.Text;
mm.Body = "To view the message, please use an HTML compatible email viewer!";
mm.Attachments.Add(new Attachment(memoryStream, "100-" + genUUID.Text + ".pdf"));
SmtpClient client = new SmtpClient();
client.Port = 587;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("postmaster#this.com", "343543");
client.Host = "smtp.mailchimp.org";
client.Send(mm);
I've spent the last day googling and trying to figure out how to get the generated PDF into the Mailstream message but can't seem to figure it out. I am using PDFTK which uses iTextSharp to parse the PDF.
Related
` Here is my workbook I created. If I save this file on hard disc, all is working okey. But looks like XLWorkbook doesnt support .xls (I got an exception). But with xlsx all is okey.
var workbook = new XLWorkbook();
var worksheet = workbook.Worksheets.Add("TestWorksheet");
var currentRow = 1;
worksheet.Cell(currentRow, 1).Value = "Test Name";
worksheet.Cell(currentRow, 2).Value = "Test 1";
worksheet.Cell(currentRow, 3).Value = "Test 2";
worksheet.Cell(currentRow, 4).Value = "Test 3";
worksheet.Cell(currentRow, 5).Value = "Test 4";
//workbook.SaveAs(path + "newFile.xlsx");
Then am trying to send it via email.
try
{
MemoryStream ms = new MemoryStream();
Console.WriteLine(ms.Length);
workbook.SaveAs(ms);
Console.WriteLine(ms.Length);
MailAddress from = new MailAddress(emailfFrom, "Me");
MailAddress to = new MailAddress(emailTo);
MailMessage m = new MailMessage(from, to);
m.Subject = "Test";
m.Body = "<h2>Some text here</h2>";
m.IsBodyHtml = true;
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, "file.xlsx", "application/excel");
m.Attachments.Add(attach);
SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);
smtp.Credentials = new NetworkCredential(emailfFrom, password);
smtp.EnableSsl = true;
smtp.Send(m);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
When I check the email - I got the message and the file. But When I load the file that I got by email, and try to open it I have an error that the file type was wrong or file was destroyed. And it is empty inside and no worksheet that I created.
And also when I loaded this file it was without extention. I added extention .xlsl by hands but it didnt help.
Please help. This is something with memory stream or with Content type of attachment? I tried different ("application/excel", etc.).
Thank you.
You need to reset the position of the memory stream after writing to it so that the stream is read from the beginning when sending the e-mail.
I.e. add this line just after workbook.SaveAs(ms); and it will work as expected:
workbook.SaveAs(ms);
ms.Position = 0;
I am creating a pdf using itextsharp. The pdf created normally and post it to the browser so the user can easily save the file to his computer . Now i want this generated pdf automatically send it also with email . I have try to convert the doc before post it to context and attach it to an email but with no any success. My code is:
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/pdf";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=mypdf.pdf");
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
string imagepath = Server.MapPath(".") + "/assets/myimages/myimage.png";
Document Doc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
HTMLWorker htmlparser = new HTMLWorker(Doc);
PdfWriter pdfwriter= PdfWriter.GetInstance(Doc, HttpContext.Current.Response.OutputStream);
Doc.Open();
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
image.ScalePercent(106f,90f);
Doc.Add(image);
//adding elements using itextshart pdf
AddPDf(pdfwriter,Doc);
//to add html in pdf
// htmlparser.Parse(stringReader);
OnEndPage(pdfwriter, Doc);
Doc.Close();
email_send(Doc.ToString());
HttpContext.Current.Response.End();
public void email_send( string filename)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("reciever#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment((Server.MapPath(filename.ToString())));
mail.Attachments.Add(attachment);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypass");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
}
The error i get is :
Could not find file
{"Could not find file 'C:\\Admin\\iTextSharp.text.Document'.":"C: \\Admin\\iTextSharp.text.Document"}
The reason for the error is that you're passing the Doc object reference to your email_send method, instead of the file path.
I made a somewhat similar emailing solution by reading the document to a MemoryStream and passing that as the attachment.
public void email_send(Document d)
{
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");
mail.From = new MailAddress("myemail#gmail.com");
mail.To.Add("reciever#gmail.com");
mail.Subject = "Test Mail - 1";
mail.Body = "mail with attachment";
System.IO.MemoryStream ms = new System.IO.MemoryStream();
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(d, ms);
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
Attachment attach = new Attachment(ms, ct);
mail.Attachments.Add(attach);
SmtpServer.Port = 587;
SmtpServer.Credentials = new System.Net.NetworkCredential("myemail#gmail.com", "mypass");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
writer.Flush();
writer.Dispose();
ms.Dispose();
}
Call it email_send(Doc).
I need to send email message with attachment. I'm using below code:
MailMessage msg = new MailMessage("adrFrom", "adrTo", "header", "body");
SmtpClient client = new SmtpClient("hostName", 25);
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("accountName", "password");
Attachment atch = new Attachment(filePath, MediaTypeNames.Application.Octet);
atch.Name = "FileName.docx";
msg.Attachments.Add(atch);
client.Send(msg);
Message is received, and attachment is there too, but file name looks like ' =?utf-8?B?dXRHRDBZTFJnOUdBMFlzZzBKelF1TkNoPz0NCiA9P3V0Zi04P0I/TG1S?=\', also there is no extension(.docx) and file content looks like it's in the Base64 encoding.
How can I send e-mail message with .docx file saving it extension and name?
Add Contentype to your Attachment
System.Net.Mime.ContentType contentType = new System.Net.Mime.ContentType();
contentType.MediaType = System.Net.Mime.MediaTypeNames.Application.Octet;
contentType.Name = "test.docx";
msg.Attachments.Add(new Attachment("I:/files/test.docx"), contentType);
I have found a solution
The problem was in Russian letters in the file name. Without it everything works fine.
I am able to send an attachment in a mail but the attachment content is blank and size is being shown as 0 bytes.
After doing some search over the internet found that we need to reset the memory stream position to 0 in order to start from start.
I tried that as well but it seems it is not working. Can you please help?
Please find below my code snippet:
NOTE: I am able to save the workbook and Data is present in the saved workbook.
MemoryStream memoryStream = new MemoryStream();
StreamWriter writer = new StreamWriter(memoryStream);
writer.Write(xlWorkbook);
writer.Flush();
memoryStream.Position = 0;
MailMessage mail = new MailMessage();
SmtpClient SmtpServer = new SmtpClient("smtpclient");
mail.From = new MailAddress("from#gmail.com");
mail.To.Add("To#gmail.com");
mail.Subject = "Entry";
mail.Body = "Hello, PFA ";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(memoryStream,"xls");
attachment.ContentDisposition.FileName = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
mail.Attachments.Add(attachment);
SmtpServer.Port = 465;
SmtpServer.UseDefaultCredentials = false;
SmtpServer.Credentials = new System.Net.NetworkCredential("Username", "password");
SmtpServer.EnableSsl = true;
SmtpServer.Send(mail);
writer.Dispose();
I think the attachment is confusing the mail system. Microsoft's recommendation is to specify the content type as an octet. Below is a replacement for initializing the attachment. The reset of your code looks fine.
string filename = "Input" + DateTime.Now.ToString("yyyyMMdd_hhss") + ".xls";
attachment = new System.Net.Mail.Attachment(memoryStream, filename, MediaTypeNames.Application.Octet);
I have one form through which ,Sender text his email-id and password and selects attachment
using fileupload,recipients's email id i am getting from database table,email is reaching to recipients fine..but
problem is that when i attach a attachment ,attachment's size goes 0 except 1st email-id
,which i am getting from table....i have pasted code..
foreach (string email_to in list_emails)
{
MailMessage mail = new MailMessage();
mail.To.Add(email_to);
mail.Subject = "UPDATES FROM ATTENDANCE S/W";
mail.From = new MailAddress(txtFrom.Text.ToString());
mail.Body = txtMessage.Text;
if (FileUpload1.HasFile)
{
string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
Attachment myAttachment =
new Attachment(FileUpload1.FileContent, fileName);
mail.Attachments.Add(myAttachment);
}
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.UseDefaultCredentials = false;
smtp.Credentials = new System.Net.NetworkCredential(txtFrom.Text.ToString(), txtPasswd.Text.ToString());
smtp.EnableSsl = true;
smtp.Send(mail);
}
This is happening because FileContent is a Stream and so when you read from it the position of that Stream is left at the end. Consider something like this. At the top of the loop store the bytes, you don't need to keep reading them from the Stream anyway:
bool hasFile = FileUpload1.HasFile;
int fileLen = FileUpload1.PostedFile.ContentLength;
Stream stream = FileUpload1.FileContent;
byte[] file = new byte[fileLen];
stream.Read(file, 0, fileLen);
and then down in the loop, leverage the variable:
new Attachment(new MemoryStream(file) ...
and you'll want to change the if statement to leverage the bool:
if (hasFile)