如何通过MVC .Net中的邮件以附件形式发送文件(URL)

时间:2018-07-26 07:32:50

标签: c# file email pdf model-view-controller

我有一个API,可为我提供文件http://bts.myurl.com/ThisIsMyPdf.pdf的路径。 现在,我有一个按钮,可以单击以通过邮件将此文件共享给用户。这是我用于发送报告的代码:

var filePath = "http://bts.myurl.com/ThisIsMyPdf.pdf";  
Utilities.SendEmail("MyId@gmail.com", "subject", "To@gmail.com", "", "", "body", filePath);

但这给URI Formats are not supported.

以例外

其他一些方法包括先发送文件,然后再作为附件发送,但我又不想下载。

我相信还有其他方法可以实现这一目标,请分享。

1 个答案:

答案 0 :(得分:1)

如@dlatikay所建议,特此共享一个解决上述问题的有效代码。

//This  is the code get byte stream from the URL    
WebClient myClient = new WebClient();
        byte[] bytes = myClient.DownloadData("http://www.examle.com/mypdf.pdf");
        System.IO.MemoryStream webPdf = new MemoryStream(bytes);

//To Create the Attachment for sending mail.
System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Application.Pdf);
            Attachment attach = new Attachment(webPdf, ct);
            attach.ContentDisposition.FileName = "myFile.pdf";

            var smtp = new SmtpClient
            {
                Host = "email.thyrocare.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
            };
            using (var message = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
 //Here webpdf is the bytestream which is going to attach in the mail
                message.Attachments.Add(new Attachment(webPdf, "sample.pdf"));
                smtp.Send(message);
            }
            webPdf.Dispose();
            webPdf.Close();