Himanshu N Tatariya
Himanshu N Tatariya

Reputation: 278

Send Attachment in Email on Windows Azure with c#

I am trying to send email from AZURE. I successfully send without attachment email. When I send email with attachment, Below issue I face while download attachment.

For attachment I upload PDF file on blob and download it and then add attachment. My code as below.

var account = new CloudStorageAccount(new StorageCredentials("accountName", "keyvalue"), true);
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container =blobClient.GetContainerReference("containername");
CloudBlockBlob blobread = container.GetBlockBlobReference(Session["UploadPDFFile"].ToString());
MemoryStream msRead = new MemoryStream();                                
using (msRead)
{
  msRead.Position = 0;
  blobread.DownloadToStream(msRead);

  objMailMessgae.Attachments.Add(new System.Net.Mail.Attachment(msRead,    Session["UploadPDFFile"].ToString(), "pdf/application"));

   try
   {
     objSmtpClient.Send(objMailMessgae);
   }
   catch (Exception ex) {
            string s = ex.Message;
        }
    }

Upvotes: 2

Views: 2165

Answers (1)

Gaurav Mantri
Gaurav Mantri

Reputation: 136146

You would need to reset the memory stream's position to 0 after you have read blob's content into it. So essentially your code would be:

var account = new CloudStorageAccount(new StorageCredentials("accountName", "keyvalue"), true);
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container =blobClient.GetContainerReference("containername");
CloudBlockBlob blobread = container.GetBlockBlobReference(Session["UploadPDFFile"].ToString());
MemoryStream msRead = new MemoryStream();                                
using (msRead)
{
  blobread.DownloadToStream(msRead);
  msRead.Position = 0;

  objMailMessgae.Attachments.Add(new System.Net.Mail.Attachment(msRead,    Session["UploadPDFFile"].ToString(), "pdf/application"));

   try
   {
     objSmtpClient.Send(objMailMessgae);
   }
   catch (Exception ex) {
            string s = ex.Message;
        }
    }

Give it a try. It should work.

Upvotes: 2

Related Questions