【问题标题】:SendGrid: How to attach a file from Azure blob storage?SendGrid:如何从 Azure Blob 存储附加文件?
【发布时间】:2014-02-28 14:16:42
【问题描述】:

我想将 Windows Azure blob 存储中的 blob 附加到使用 SendGrid 发送的电子邮件中。我想指定附件的文件名(真正的文件名只是胡言乱语),afaik 迫使我将附件添加为流。

我的代码如下所示:

var msg = SendGrid.GetInstance();
// Code for adding sender, recipient etc...
var storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["storage"].ConnectionString);
var blobClient = storageAccount.CreateCloudBlobClient();
var container = blobClient.GetContainerReference(typeName);
var blob = container.GetBlockBlobReference("somefile.png");
var ms = new MemoryStream();
blob.DownloadToStream(ms);
msg.AddAttachment(ms, "originalfilename.png");

文件从存储读取到内存流并添加附件似乎工作正常,但收到电子邮件后附件为 0 字节。

提前谢谢你。

【问题讨论】:

  • 周末我意识到这(很可能)是与 SendGrid 相关的问题。将附件缓冲区的内容保存到文件中可以正常工作。我已经在 SendGrid 板上发布了这个,希望那里的任何人都能对此有所了解。 CopyTo 和 Write(缓冲区到缓冲区)都产生相同的结果。附件缓冲区正确,但接收到的文件不正确。

标签: azure stream azure-storage email-attachments sendgrid


【解决方案1】:

这可能已经解决了,但是您需要确保使用 Seek 将流“倒回”到开头。示例代码如下。

stream.Seek(0, SeekOrigin.Begin);
sendGrid.AddAttachment(stream, "name");

【讨论】:

  • 谢谢。我们实际上通过链接到附件而不是发送它们来解决它。因此也节省带宽:)
  • 不错的一个。我的回答是否解决了您最初发布的问题?如果是这样,您可以将其标记为答案吗?谢谢 :)
  • 如果我再次遇到这个问题,我会试一试。不再参与这个项目了:(
【解决方案2】:

尽管我不确定 AddAttachment API 的工作原理,但请注意,您的 MemoryStream 的位置将在下载结束时设置为其长度。因此,您可能需要在调用 AddAttachment 之前从头搜索它。

var ms = new MemoryStream();
blob.DownloadToStream(ms);
ms.Position = 0;
msg.AddAttachment(ms, "originalfilename.png");

【讨论】:

    【解决方案3】:

    我找到了一种将文件直接从 Azure 流式传输到 SendGrid 电子邮件消息对象的方法。这是相关的sn-p:

    var client = new SendGridClient(apiKey);
    var mailFrom = new EmailAddress(from.Email, from.Name);
    var mailTo = new EmailAddress(to.Email, to.Name);
    var msg = MailHelper.CreateSingleEmail(mailFrom, mailTo, subject, bodyText, bodyHtml);
        
    // Attach file from Azure if fileName is set
    if (fileName != null) {
        // Initialize the Azure blob client
        var container = new BlobContainerClient(_azureConnectionString, _azureContainerName);
        var blob = container.GetBlobClient(fileName);
        
        // Validate the file exists in Azure
        if (!await blob.ExistsAsync()) return NotFound("File not found");
                    
        // Stream the file directly from Azure into the email attachment
        await msg.AddAttachmentAsync(fileName, blob.OpenRead());
    }
        
    var response = await client.SendEmailAsync(msg);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-25
      • 1970-01-01
      • 2018-03-13
      • 2017-08-18
      • 2020-10-15
      • 2020-06-17
      • 2020-12-03
      • 2021-12-08
      相关资源
      最近更新 更多