【问题标题】:Email Attachments missing on Azure, works locallyAzure 上缺少电子邮件附件,可在本地工作
【发布时间】:2018-09-30 05:35:02
【问题描述】:

我已经实现了类似于以下问题的东西,我可以让它在我的服务器上本地运行,但是当我部署到 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 azure-web-app-service sendgrid mailmessage


    【解决方案1】:

    以下代码适用于我使用来自 Azure 函数的 Sendgrid 发送电子邮件。我从 Blob Storage 附加了一个 CSV 文件。它也应该对你有用。您所要做的就是确保将 pdf 文件作为字节 [] 读取。

        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 作为 ByteArray 下载似乎可以通过 Stream
    猜你喜欢
    • 2012-01-03
    • 2012-09-18
    • 1970-01-01
    • 2012-04-26
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    相关资源
    最近更新 更多