vndpal
vndpal

Reputation: 757

How to send file (at URL) as attachement via Mail in MVC .Net

I have an API which gives me path to a file http://bts.myurl.com/ThisIsMyPdf.pdf. Now I have a button which onto clicking share this file to users via mail. This is the code which i have used for sending the report:

var filePath = "http://bts.myurl.com/ThisIsMyPdf.pdf";  
Utilities.SendEmail("[email protected]", "subject", "[email protected]", "", "", "body", filePath);

But this is giving exception as URI Formats are not supported.

Some other approaches include the file to be download first before sending as attachment but again i don't want it to be downloaded.

I believe there are other ways to achieve this, if any please share.

Upvotes: 2

Views: 2654

Answers (1)

vndpal
vndpal

Reputation: 757

As suggested by @dlatikay, hereby sharing a working code for the above problem.

//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.domainName.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();

Upvotes: 2

Related Questions