C# 使用 Azure 和 Fire&Forget 异步发送电子邮件或 SMS

标签 c# azure azure-queues

我正在寻找一种简单的方法来发送和忘记 Twilio SMS 或电子邮件,我认为 Azure 队列或总线正是这样做的。但后来我开始阅读每一个,似乎它们被设计用来做一些更复杂的事情。

问题:
实现“Fire&Forget”方法/调用的最佳方法是什么,以便我知道我发送了一封电子邮件,但我的应用程序不需要停止等待消息实际离开。

最佳答案

这是一个使用 SendGrid 发送邮件的同步版本。您可以非常轻松地将其转换为异步。

public void SendMail(MailAddress @from, MailAddress[] to, string subject, AlternateView[] alternateMessageBodyViews, Attachment[] attachments)
    {
        _validationService.StringIsNullOrEmpty(subject, "subject");
        _validationService.Null(from, "from");
        _validationService.StringIsNullOrEmpty(from.Address, "from.Address");
        _validationService.Null(to, "to");


        /* Important Notice
         * SendGrid has 20480000 bytes limitation for the total message size. Approx. 19.5 MB
         * BUT attachments are Base64 encoded therefore 15MB of attachments will actually become 20 MB when encoded.
         * Therefore we need to cut down the attachments total ( cumulative ) size to 12 MB which will make 16 MB after base64
         * Combined with other message information like message headers, attachments headers, etc. will keep us away from the 19.5MB limit
         */
        long approximateTotalMessageMaxSizeInBytes = 0;

        MailMessage mailMsg = new MailMessage();
        // From
        mailMsg.From = new MailAddress(from.Address, from.DisplayName);

        approximateTotalMessageMaxSizeInBytes += Convert.ToBase64String(Encoding.UTF8.GetBytes(from.Address)).Length;
        approximateTotalMessageMaxSizeInBytes += Convert.ToBase64String(Encoding.UTF8.GetBytes(from.DisplayName)).Length;
        // To
        foreach (MailAddress toMailAddress in to)
        {
            mailMsg.To.Add(new MailAddress(toMailAddress.Address, toMailAddress.DisplayName));

            approximateTotalMessageMaxSizeInBytes += Convert.ToBase64String(Encoding.UTF8.GetBytes(toMailAddress.Address)).Length;
            approximateTotalMessageMaxSizeInBytes += Convert.ToBase64String(Encoding.UTF8.GetBytes(toMailAddress.DisplayName)).Length;
        }

        // Subject and multipart/alternative Body
        mailMsg.Subject = subject;
        approximateTotalMessageMaxSizeInBytes += Convert.ToBase64String(Encoding.UTF8.GetBytes(subject)).Length;

        if (alternateMessageBodyViews != null)
        {
            foreach (AlternateView alternateView in alternateMessageBodyViews)
            {
                mailMsg.AlternateViews.Add(alternateView);
                approximateTotalMessageMaxSizeInBytes += (long)(alternateView.ContentStream.Length * 1.33);
            }
        }

        if (attachments != null)
        {
            foreach (Attachment attachment in attachments)
            {
                mailMsg.Attachments.Add(attachment);
                approximateTotalMessageMaxSizeInBytes += (long)(attachment.ContentStream.Length * 1.33);
            }
        }


        if (approximateTotalMessageMaxSizeInBytes > long.Parse(ConfigurationManager.AppSettings["TotalMessageMaxSizeInBytes"]))
        {
            throw new MailMessageTooBigException(
                string.Format("Message total bytes limit is {0}. This message is approximately {1} bytes long.",
                    approximateTotalMessageMaxSizeInBytes));
        }


        try
        {
            _mailSender.Send(mailMsg);
        }
        catch(Exception exception) // swallow the exception so the server do not blow up because of a third party service.
        {
            _logger.Exception("SendGridMailService", _currentUserProvider.CurrentUserId, exception);
        }

        string logFrom = string.Format("{0} <{1}>", from.DisplayName, from.Address);
        string[] logTo = to.Select(t => string.Format("{0} <{1}>", t.DisplayName, t.Address)).ToArray();
        string[] atts = (attachments == null) ? null : attachments.Select(att => att.Name).ToArray();

        _logger.SendEmail(
            _currentUserProvider.CurrentSystemUser.UserName,
            logFrom,
            logTo,
            subject,
            atts);
    }

还有一个简单的异步 EAP 风格版本,来自 here :

 public void SendAsyncMail()
    {
        MailMessage mail = new MailMessage();

        mail.From = new MailAddress("Enter from mail address");
        mail.To.Add(new MailAddress("Enter to address #1"));
        mail.To.Add(new MailAddress("Enter to address #2"));
        mail.Subject = "Enter mail subject";
        mail.Body = "Enter mail body";

        SmtpClient smtpClient = new SmtpClient();
        Object state = mail;

        //event handler for asynchronous call
        smtpClient.SendCompleted += new SendCompletedEventHandler(smtpClient_SendCompleted);
        try
        {
            smtpClient.SendAsync(mail, state);
        }
        catch (Exception ex)
        {

        }
    }
    void smtpClient_SendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
    {

        MailMessage mail = e.UserState as MailMessage;

        if (!e.Cancelled && e.Error != null)
        {
            //message.Text = "Mail sent successfully";
        }
    }

第三个 TAP 样式来自 here :

var message = new MailMessage("from", "to", "subject", "body"))
var client = new SmtpClient("host");
client.SendCompleted += (s, e) => {
                           client.Dispose();
                           message.Dispose();
                        };
client.SendAsync(message, null);

对于 Twilio SMS API,您可以从教程开始 here 。完整的异步支持。

关于C# 使用 Azure 和 Fire&Forget 异步发送电子邮件或 SMS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25097380/

相关文章:

c# - 动态 LINQ 查询嵌套对象

azure - 删除 Cosmos DB 容器是否会消耗 RU?

java - 如何验证java中的azure上是否存在队列?

entity-framework - Azure 应用服务上的 EF Core (1.0.0) 迁移

amazon-web-services - 无服务器部署到 AWS、Azure 或 GCP

azure - 是否可以更改/更新 Azure 队列中的过期时间?

azure - 如何获取 Azure Log Analytics 中特定 Azure 存储队列中的消息计数

c# - 如何传递对函数的引用

c# - VS2012代码分析工具如何全局排除某条消息的错误?

c# - "Non-nullable field is uninitialized"的编译器错误,即使已在InitializeComponents函数中对其进行了初始化