asp.net-core - C# 如何添加 Await 到此函数 - SendEmailAsync - Dot Net Core 中的 MailKit

标签 asp.net-core async-await mailkit

我有基于 MailKit 的代码。在哪里添加await关键字?

public async Task SendEmailAsync(string email, string subject, string mess)
{
    var message = new MimeMessage();
    message.From.Add(new MailboxAddress("Joey Tribbiani", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a8c2c7cdd1e8cedac1cdc6ccdb86cbc7c5" rel="noreferrer noopener nofollow">[email protected]</a>"));
    message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b1bab3bcb6beb7a092b4a0bbb7bcb6a1fcb1bdbf" rel="noreferrer noopener nofollow">[email protected]</a>"));
    message.Subject = "How you doin'?";

    message.Body = new TextPart("plain")
    {
        Text = @"Hey Chandler"
    };

    using (var client = new SmtpClient())
    {
        // For demo-purposes, accept all SSL certificates (in case the server supports STARTTLS)
        client.ServerCertificateValidationCallback = (s, c, h, e) => true;

        client.Connect("smtp.friends.com", 587, false);

        // Note: since we don't have an OAuth2 token, disable
        // the XOAUTH2 authentication mechanism.
        client.AuthenticationMechanisms.Remove("XOAUTH2");

        // Note: only needed if the SMTP server requires authentication
        client.Authenticate("joey", "password");

        client.Send(message);
        client.Disconnect(true);
    }
}

这是一个类似的实现(但我找不到使这项工作有效的凭据),所以我更改为上面的

    public async Task SendEmailAsync(string email, string subject, string message)
    {
        using (var client = new HttpClient { BaseAddress = new Uri("smtp.gmail.com") })
        {
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
                Convert.ToBase64String(Encoding.ASCII.GetBytes("api:key-*")));


            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("from", "postmaster@sandbox*.mailgun.org"),
                new KeyValuePair<string, string>("to", email),
                new KeyValuePair<string, string>("subject", subject),
                new KeyValuePair<string, string>("text", message)
            });

            await client.PostAsync("sandbox*.mailgun.org/messages", content).ConfigureAwait(false);
        }
    }

最佳答案

如果您使用 .Net core 和 MailKit,您应该引用 MailKit 库并通过它们发送。我用于发送电子邮件的 MailKit 类如下:

using System;
using System.Threading;
using MailKit.Security;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MimeKit;
using SmtpClient = MailKit.Net.Smtp.SmtpClient;

namespace App.Email
{
    public class MailKit : IMailKit
    {
        private readonly ILogger<MailKit> _logger;
        private readonly Settings _settings;

        public MailKit(ILogger<MailKit> logger, IOptions<Settings> settings)
        {
            _logger = logger;
            _settings = settings.Value;
        }

        /// <summary>
        /// Sends an email asynchronously using SMTP
        /// </summary>
        /// <param name="toEmailAddress"></param>
        /// <param name="subject"></param>
        /// <param name="bodyHtml"></param>
        /// <param name="bodyText"></param>
        /// <param name="retryCount"></param>
        /// <param name="toName"></param>
        public async void Send(string toName, string toEmailAddress, string subject, string bodyHtml, string bodyText, int retryCount = 4)
        {
            var message = new MimeMessage();

            message.From.Add(new MailboxAddress(_settings.MailKitFromName, _settings.MailKitFromAddress));

            message.To.Add(new MailboxAddress(toName, toEmailAddress));

            message.Subject = subject;
            var builder = new BodyBuilder
            {
                TextBody = bodyText,
                HtmlBody = bodyHtml
            };
            message.Body = builder.ToMessageBody();

            for (var count = 1; count <= retryCount; count++)
            {
                try
                {
                    using (var client = new SmtpClient())
                    {
                        client.LocalDomain = _settings.MailKitLocalDomain;
                        client.Authenticate(_settings.MailKitUsername, _settings.MailKitPassword);

                        SecureSocketOptions secureSocketOptions;

                        if (!Enum.TryParse(_settings.MailKitSecureSocketOption, out secureSocketOptions))
                        {
                            secureSocketOptions = SecureSocketOptions.Auto;
                        }

                        await client.ConnectAsync(_settings.MailKitHost, _settings.MailKitPort, secureSocketOptions).ConfigureAwait(false);
                        await client.SendAsync(message).ConfigureAwait(false);
                        await client.DisconnectAsync(true).ConfigureAwait(false);
                        return;
                    }
                }
                catch (Exception exception)
                {
                    _logger.LogError(0, exception, "MailKit.Send failed attempt {0}", count);
                    if (retryCount >= 0)
                    {
                        throw;
                    }
                    await Task.Delay(count * 1000);
                }
            }
        }
    }
}

界面

namespace App.Email
{
    public interface IMailKit
    {
        void Send(string toName, string toEmailAddress, string subject, string bodyHtml, string bodyText, int retryCount = 4);
    }
}

关于asp.net-core - C# 如何添加 Await 到此函数 - SendEmailAsync - Dot Net Core 中的 MailKit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41500453/

相关文章:

c# - 我应该如何从 ASP.NET Core View 访问我的 ApplicationUser 属性?

c# - 使用 ffmpeg 和 C# 创建转换队列

c# - TPL 数据流异步调度

c# - 是否可以使用 MailKit 修改/附加邮件而无需下载整个邮件?

c# - SocketException : No such host is known

c# - 使用 Mailkit 连接时何时应该使用 SecureSockOptions 或 useSsl

c# - 当 aspNetCore web.config 部分存在时,为什么无法加载 launchSettings.json 配置文件中的environmentVariables?

nginx - 在 kubernetes 集群内使用 nginx 反向代理组织 .net 核心应用程序的最佳方法是什么?

asp.net-core - 在 dotnet.exe 下运行时,IServerAddressesFeature 地址为空

vb.net - 如何调试等待语句?