我正在使用itextsharp创建一个pdf。 pdf正常创建并将其发布到浏览器,以便用户可以轻松地将文件保存到他的计算机。现在我希望这个生成的pdf自动发送它与电子邮件。我已经尝试转换文档,然后将其发布到上下文并将其附加到电子邮件但没有任何成功。我的代码是:
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);
}
我得到的错误是:
Could not find file
{"Could not find file 'C:\\Admin\\iTextSharp.text.Document'.":"C: \\Admin\\iTextSharp.text.Document"}
答案 0 :(得分:0)
错误的原因是您将Doc
对象引用传递给email_send
方法,而不是文件路径。
我通过将文档读取到MemoryStream
并将其作为附件传递给我做了一个类似的电子邮件解决方案。
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();
}
称之为email_send(Doc)
。