如何让我的PDF电子邮件附件正确附加为PDF?

时间:2016-06-17 11:03:06

标签: c# asp.net-mvc pdf email-attachments

下面我添加了电子邮件中显示的附件截图。

在任何PDF阅读器中都可以正常使用。

如何将其作为实际PDF呈现?我觉得好像错过了一些小事......

这是我的代码:

public ActionResult SendInvoice(SendInvoiceViewModel model)
{
    var Invoice = db.Invoices.FirstOrDefault(x => x.Id == model.Id);
    MemoryStream ms = new MemoryStream(Invoice.Document);

    Attachment Data = new Attachment(ms, MediaTypeNames.Application.Pdf);
    ContentDisposition Disposition = Data.ContentDisposition;
    Disposition.CreationDate = Invoice.Date;
    Disposition.ModificationDate = Invoice.Date;
    Disposition.ReadDate = Invoice.Date;

    SendInvoiceMail(model.EmailAddress, Invoice.Number, model.EmailMessage, Data);
}

private void SendInvoiceMail(string emailAddress, string invoiceNumber, string message, Attachment attachment)
{
    using (MailMessage Message = new MailMessage())
    {
        Message.From = new MailAddress("accounts@###########");
        Message.Subject = String.Format("Your store invoice {0}", invoiceNumber);
        Message.To.Add(new MailAddress(emailAddress));
        Message.Body = message;
        Message.Attachments.Add(attachment);

        SmtpClient smtp = new SmtpClient("mail.############", 587);
        smtp.Credentials = new NetworkCredential("info@##########", "##########");
        smtp.Send(Message);
    };
}

那我错过了什么?

Email Addtachment

2 个答案:

答案 0 :(得分:1)

尝试使用Attachment()构造函数的3参数版本。第二个参数允许您提供文件名。该文件名应以.pdf结尾。

答案 1 :(得分:0)

尝试

public ActionResult SendInvoice(SendInvoiceViewModel model)
{
    var Invoice = db.Invoices.FirstOrDefault(x => x.Id == model.Id);
    MemoryStream ms = new MemoryStream(Invoice.Document);

    //Construct a file name for the attachment
    var filename = string.Format("{0}.pdf", Invoice.Number);

    Attachment Data = new Attachment(ms, filename, MediaTypeNames.Application.Pdf);
    ContentDisposition Disposition = Data.ContentDisposition;
    Disposition.CreationDate = Invoice.Date;
    Disposition.ModificationDate = Invoice.Date;
    Disposition.ReadDate = Invoice.Date;

    SendInvoiceMail(model.EmailAddress, Invoice.Number, model.EmailMessage, Data);
}

包含附件的文件名。