Send email attachment created in HttpContext.Current.Response - c#

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).

Related

gridview.rendercontrol returns System.Web.UI.HtmlTextWriter

I am trying to send grid in my email, It sends email with a only System.Web.UI.HtmlTextWriter, It does not populate grid.
here is my code:
System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
StringBuilder emailBody = new StringBuilder();
StringWriter emailStringWriter = new StringWriter();
HtmlTextWriter htmlGrid = new HtmlTextWriter(new HtmlTextWriter(new StringWriter(emailBody, CultureInfo.InvariantCulture)));
mail.Dispose();
mail = new System.Net.Mail.MailMessage();
mail.To.Add('abc#xyz.com');
mail.From = 'def#yzy.com';
mail.Subject = 'grid example';
myGrid.RenderControl(htmlGrid);
mail.Body = htmlGrid.ToString();
mail.IsBodyHtml = true;
smtp = new System.Net.Mail.SmtpClient(ConfigurationManager.AppSettings["smtpSetting"].ToString());
smtp.Port = 25;
smtp.Send(mail);
mail.Dispose();
I received the email but grid was not there , only this text was there: System.Web.UI.HtmlTextWriter
You need to declare a StringBuilder for your HtmlTextWriter.
StringBuilder sb = new StringBuilder();
HtmlTextWriter htmlGrid = new HtmlTextWriter(new StringWriter(sb, CultureInfo.InvariantCulture));
You may need to flush the writer(not certain), but you will use sb.ToString() to get the rendered html.
mail.Body = sb.ToString();

How to send dymanically generated html as a email attachment in C#

I am using following code to send email but it is failed if I used html attachment.
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.StreamWriter writer2 = new System.IO.StreamWriter(ms);
writer2.Write("<html><head></head><body>Invoice 1</body></html>");
writer2.Flush();
writer2.Dispose();
MailMessage mm = new MailMessage();
mm.To.Add("test#gmail.com");
mm.CC.Add("test2#gmail.com");
mm.From = new MailAddress("test3#gmail.com");
mm.Subject = "नोटिस";
mm.Body = sb.ToString();
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Html);
System.Net.Mail.Attachment attach = new System.Net.Mail.Attachment(ms, ct);
attach.ContentDisposition.FileName = "myFile.html";
mm.Attachments.Add(attach);
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "rcms.pdf"));
ms.Close();
mm.IsBodyHtml = true;
only one line needed.
var a = System.Net.Mail.Attachment.CreateAttachmentFromString("‌​'"+sb.ToString()+"'<‌​/body>", "notices.html");

Use XMLSerializer to stream directly into a MailMessage Attachment

I am using an XMLSerializer and I need to write it straight into a Mail Message Attachment preferably without saving it into a file first.
My code
var smtp = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587)
{
Credentials = new System.Net.NetworkCredential("email#gmail.com", "password"),
EnableSsl = true
};
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(XmlRoot));
ser.Serialize(ms, model);
var attachment = new System.Net.Mail.Attachment(ms, "file.xml", "application/xml");
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.To.Add("tothisemail#gmail.com");
message.Subject = String.Format("{0}", some subject name);
message.From = new System.Net.Mail.MailAddress("email#gmail.com");
message.Body = "empty content";
message.Attachments.Add(attachment);
smtp.Send(message);
What's happening is the email is successfully sent but the xml file it writes to is completely empty.
ser.Serialize(ms, model);
ms.Position = 0;
var attachment = new System.Net.Mail.Attachment(ms, "file.xml", "application/xml");
Writing to then reading from a MemoryStream

Attach Generated PDFTK/iTextSharp PDF to MemoryStream to Mail

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.

Email Attachment from memory stream is coming as blank in C#

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);

Categories