c# 发送邮件保存服务器,.net c#将生成的文件保存到服务器

博客讨论了如何使用iText库在C#中生成PDF文件,并避免硬编码保存路径,而是直接将PDF作为邮件附件发送。解决方案包括使用MemoryStream存储PDF内容,然后通过SMTP客户端发送邮件。此外,还提及了在Web应用程序中保存文件到服务器路径的方法。
摘要由CSDN通过智能技术生成

I am generating a PDF with the handy iText for C#. Now, I basically just need to generate this PDF and e-mail it. At the moment I can generate the file in PDF, but I don't want to hardcode a path to save the file. Example, I am saving the file like this:

string file = "C:\\Receipts\" + ConfirmationNumber + ".pdf";

Now, hardcoding a path like that is completely against best practices. How can I save the file properly, following best practice? Maybe to a folder inside the project itself? Thanks for any help.

Solutions1

do you have to write the file to disk? It's easy enough to send an iText created pdf directly to email from this

var doc = new Document();

MemoryStream memoryStream = new MemoryStream();

PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

doc.Open();

doc.Add(new Paragraph("First Paragraph"));

doc.Add(new Paragraph("Second Paragraph"));

writer.CloseStream = false;

doc.Close();

memoryStream.Position = 0;

MailMessage mm = new MailMessage("username@gmail.com", "username@gmail.com")

{

Subject = "subject",

IsBodyHtml = true,

Body = "body"

};

mm.Attachments.Add(new Attachment(memoryStream, "filename.pdf"));

SmtpClient smtp = new SmtpClient

{

Host = "smtp.gmail.com",

Port = 587,

EnableSsl = true,

Credentials = new NetworkCredential("username@gmail.com", "password")

};

smtp.Send(mm);

Talk1:

This worked much better. No need to save to the folder and keep giving it maintenance by deleting files. Thanks a lot!

Talk2:

Hi, I am also in same situation. I have a crystal report. i want to generate pdf from crystal report and send mail. As now its generating pdf and saving in local machine. i want to save in a server folder. Is there any way to do this?? I am using the following code to generate the pdf. RPT.ExportToHttpResponse(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, Response, true, "Quotation Report 00" );

Talk3:

You would have to contact the authors of iText to see if they have any interface for Crystal Reports. My answer here was over 3 years ago and was actually a reference to another SO user.

Solutions2

If you have HttpContext, you can use PhysicalApplicationPath.

string filePath = string.Format("{0}\\App_Data\\ExportImport\\{1}",

HttpContext.Current.Request.PhysicalApplicationPath, fileName);

If you do not have HttpContext, you can use AppDomainAppPath.

string filePath = string.Format("{0}App_Data\\ExportImport\\{1}",

HttpRuntime.AppDomainAppPath, fileName);

Talk1:

Thanks. Will try this :)

Talk2:

Make sure the folder exists in your web application before saving the file.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值