azure - Azure 上缺少电子邮件附件,可在本地使用

标签 azure azure-web-app-service sendgrid mailmessage

我已经实现了类似于以下问题的内容,我可以让它在我的服务器上本地工作,但是当我部署到 Azure 时,它​​不起作用。我没有收到任何错误:只是一封没有附件的电子邮件。

Sending attachments using Azure blobs

使用 SendGrid 发送的文件类型是否有限制(文件大小仅为 56k)? Azure App 服务是否必须处于特定级别,还是可以在 Basic 上完成? blob URL definitley 存在,并且我按照上一个问题中的建议将流设置为零。

MailMessage mm = new MailMessage("receiver address", "someone");
            mm.From = new MailAddress("myAddress", "My Name");
            mm.Subject = content.Subject;
            mm.Body = content.Body;
            mm.IsBodyHtml = true;
            mm.BodyEncoding = UTF8Encoding.UTF8;
            mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

            var attachmentAsStream = _storageAccessService.GetAssetAsStreamForEmail("myContainer", "fileThatExists.pdf");

            var attachment = new Attachment(attachmentAsStream, "File.pdf", MediaTypeNames.Application.Pdf);
                mm.Attachments.Add(attachment);


public MemoryStream GetAssetAsStreamForEmail(string containerName, string fileName)
        {
            // Create the blob client.
            CloudBlobClient blobClient = StorageAccountReference().CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
            var memoryStream = new MemoryStream();

            try
            {
                using (var stream = new MemoryStream())
                {
                    blob.DownloadToStream(memoryStream);
                    memoryStream.Seek(0, SeekOrigin.Begin);
                }

            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Failed to download Email Atatchment: "+ ex.Message));

            }
            memoryStream.Position = 0;
            return memoryStream;
        }

using (SmtpClient client = new SmtpClient())
                {
                    client.Port = 587;
                    client.Host = "smtp.sendgrid.net";
                    client.EnableSsl = true;
                    client.Timeout = 10000;
                    client.DeliveryMethod = SmtpDeliveryMethod.Network;
                    client.UseDefaultCredentials = false;
                    client.Credentials = new System.Net.NetworkCredential("hidden", "hidden");

                    await client.SendMailAsync(message);
                }
<小时/>

更新

根据下面 Yasir 的建议进行更新。从 Azure 下载 blob 作为流似乎只能在本地工作。但是,如果我更改为以 ByteArray 形式下载,那么它在任何地方都可以工作......

public MemoryStream GetAssetAsStreamForEmail(string containerName, string fileName)
        {
            // Create the blob client.
            CloudBlobClient blobClient = StorageAccountReference().CreateCloudBlobClient();

            // Retrieve reference to a previously created container.
            CloudBlobContainer container = blobClient.GetContainerReference(containerName);

            CloudBlockBlob blob = container.GetBlockBlobReference(fileName);

            try
            {
                blob.FetchAttributes();
                var fileStream = new byte[blob.Properties.Length];
                for (int i = 0; i < blob.Properties.Length; i++)
                {
                    fileStream[i] = 0x20;
                }

                blob.DownloadToByteArray(fileStream, 0) ;
                MemoryStream bufferStream = new MemoryStream(fileStream);

            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Failed to download Email Atatchment: " + ex.Message));

            }
            return null;
        }

最佳答案

以下代码适用于我使用 Azure 函数中的 Sendgrid 发送电子邮件。我附加了 Blob 存储中的 CSV 文件。它应该也适合你。您所要做的就是确保将 pdf 文件作为 byte[] 读取。

    public interface IEmailAttachment
    {
        string Name { get; }
        byte[] FileData { get; }
    }

    public static void Send(MailMessage mailMessage, IEnumerable<IEmailAttachment> attachments)
    {
    try
    {
        // Get the configuration data
        string server = ConfigReader.EmailServer;
        int port = ConfigReader.EmailPort;
        string username = ConfigReader.SendGridUserName;
        string password = ConfigReader.SendGridPassword;
        smtpClient.EnableSsl = false;
        smtpClient.Credentials = new NetworkCredential(username, password);

        // Create the SMTP Client
        SmtpClient smtpClient = new SmtpClient(server, port);

        // Prepare the MailMessage
        mailMessage.From = new MailAddress(ConfigReader.FromEmail);

        var toEmails = ConfigReader.ToEmail.Split(',');

        foreach (var toEmail in toEmails)
        {
            mailMessage.To.Add(toEmail);
        }

        var ccEmails = ConfigReader.EmailCc.Split(',');

        foreach (var ccEmail in ccEmails)
        {
            mailMessage.CC.Add(ccEmail);
        }


        // Add attachments
        List<MemoryStream> files = new List<MemoryStream>();

        if (attachments != null)
        {
            foreach (IEmailAttachment file in attachments)
            {
                MemoryStream bufferStream = new MemoryStream(file.FileData);
                files.Add(bufferStream);

                Attachment attachment = new Attachment(bufferStream, file.Name);
                mailMessage.Attachments.Add(attachment);
            }
        }

        mailMessage.IsBodyHtml = true;

        // Send the email
        smtpClient.Send(mailMessage);

        foreach (MemoryStream stream in files)
        {
            stream.Dispose();
        }
    }
    catch (Exception)
    {
        throw;
    }
}

关于azure - Azure 上缺少电子邮件附件,可在本地使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49925744/

相关文章:

Azure Web 作业在应用程序服务中的辅助插槽中交换

azure - 如何修复 'renew' Azure网站生产槽?

node.js - Google Drive API 在电子邮件中发送 PDF 附件

azure - Terraform 创建 Azure IoT 设备配置服务注册组

Azure 备份 - 文件系统一致性、应用程序一致性和崩溃一致性

c# - 运行 Azure Web 应用程序时,是否需要将应用程序见解遥测添加到应用程序

java - Sendgrid 无法附加多个文件且未显示错误代码

Javascript Azure Function 使用 SendGrid 发送电子邮件

asp.net-mvc - Azure AD 不为 Chrome 用户提供 objectidentifier 声明

azure - 如何获取 Azure RM 资源(包括 Azure 中的所有资源)的创建日期