簡體   English   中英

UserManager SendEmailAsync沒有發送電子郵件

[英]UserManager SendEmailAsync No Email Sent

我使用以下代碼嘗試異步發送電子郵件,但沒有發送電子郵件,我不確定是什么做錯了。 我還在web.config中為電子郵件協議添加了第二段代碼。

SendEmailAsync代碼

await UserManager.SendEmailAsync(username.Id, "MTSS-B: Forgot Password", "Here is your new password. Please go back to the MTSS-B web tool and sign in. You will be prompted to create your own password.<br/><br/>" + tmpPass + "<br/><br/>MTSS-B Administrator");

Web.config代碼

<system.net>
<mailSettings>
  <smtp>
    <network host="smtp1.airws.org" userName="" password="" />
  </smtp>
</mailSettings>
</system.net>

**** ****更新

我測試了是否可以使用常規方法發送電子郵件,並且可以使用以下代碼發送電子郵件。

MailMessage m = new MailMessage(new MailAddress(ConfigurationManager.AppSettings["SupportEmailAddr"]), new MailAddress(model.Email));
m.Subject = "MTSS-B: Forgot Password"; 
m.Body = string.Format("Here is your new password. Please go back to the MTSS-B web tool and sign in. You will be prompted to create your own password.<br/><br/>Password: " + tmpPass + "<br/><br/>MTSS-B Administrator"); 
m.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient("smtp2.airws.org"); 
smtp.Send(m);

在您的應用程序中,您可能在App_Start文件夾中有一個名為IdentityConfig.cs的文件。 該文件可能具有以下類似的功能:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        // Plug in your email service here to send an email.
        return Task.FromResult(0);
    }
}

將其更改為:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        SmtpClient client = new SmtpClient();
        return client.SendMailAsync(ConfigurationManager.AppSettings["SupportEmailAddr"], 
                                    message.Destination, 
                                    message.Subject, 
                                    message.Body);
    }
}

根據自己的喜好自定義發送代碼。

Joe的解決方案引導了我很多,謝謝! 但要為此做出貢獻,您必須包含以下命名空間:

using System.Configuration;
using System.Net.Mail;

我做了很多嘗試后,我已經改變了他的解決方案,我已經達到了一些有效的代碼(它仍然必須被重新修改,但它不會改變這個想法),這就是我的SendAsync方法的樣子:

public Task SendAsync(IdentityMessage message) {
    //SmtpClient client = new SmtpClient();
    //return client.SendMailAsync(ConfigurationManager.AppSettings["SupportEmailAddr"],
    //                            message.Destination,
    //                            message.Subject,
    //                            message.Body);

    SmtpClient client = new SmtpClient();
    client.Port = 587;
    client.Host = "smtp.gmail.com";
    client.EnableSsl = true;
    //client.Timeout = 10000;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Credentials = new NetworkCredential("mailName@gmail.com", "mailPassword");

    return client.SendMailAsync("mailName@gmail.com", message.Destination, message.Subject, message.Body);
}

您可以看到Joe的解決方案在頂部進行了評論,然后,對SmtpClient進行了大量配置(由於我正在進行的一些測試,超時被評論,如果它符合您的需要,您可以取消注釋)。

之后,郵件以異步方式發送,請注意發件人(Joe從AppSettings變量中獲取)與憑證中指定的相同(您必須創建一個gmail [或您想要的wathever郵件服務]帳戶並使用它用於創建憑據的名稱和密碼)。

這應該夠了吧! 請記住,gmail可能會在嘗試以這種方式連接到您的新郵件帳戶時使您的生活變得復雜,要解決此問題,您必須登錄該帳戶並轉到您的帳戶配置並激活“安全性較低的應用程序訪問”(或者類似於,我說西班牙語,所以我的牽引可能不那么好......)。

編輯22/04/16:看起來這個解決方案在處理代理服務器時無法正常工作,應該有一種方法來配置它。 在我的情況下,我發現禁用代理並繼續下去會更便宜,但對於那些負擔不起的人來說,期望在實現這一點時遇到這個障礙。

我認為您正在使用Macrosoft ASP.NET身份和SMTP電子郵件客戶端服務器。 然后你的完整配置如下:

Web.config文件

<system.net>
<mailSettings>
  <smtp from="xyz@gmail.com">
    <network host="smtp.gmail.com" userName="xyz" defaultCredentials="false" password="xyz" port="587" enableSsl="true" />
  </smtp>
</mailSettings>
</system.net>

創建一個SmtpEmailService.cs類

public class SmtpEmailService : IIdentityMessageService
{
    readonly ConcurrentQueue<SmtpClient> _clients = new ConcurrentQueue<SmtpClient>();

    public async Task SendAsync(IdentityMessage message)
    {
        var client = GetOrCreateSmtpClient();
        try
        {
            MailMessage mailMessage = new MailMessage();

            mailMessage.To.Add(new MailAddress(message.Destination));
            mailMessage.Subject = message.Subject;
            mailMessage.Body = message.Body;

            mailMessage.BodyEncoding = Encoding.UTF8;
            mailMessage.SubjectEncoding = Encoding.UTF8;
            mailMessage.IsBodyHtml = true;

            // there can only ever be one-1 concurrent call to SendMailAsync
            await client.SendMailAsync(mailMessage);
        }
        finally
        {
            _clients.Enqueue(client);
        }
    }


    private SmtpClient GetOrCreateSmtpClient()
    {
        SmtpClient client = null;
        if (_clients.TryDequeue(out client))
        {
            return client;
        }

        client = new SmtpClient();
        return client;
    }
}

IdentityConfig.cs

// Configure the application user manager used in this application. 
//UserManager is defined in ASP.NET Identity and is used by the application.
public class ApplicationUserManager : UserManager<User>
{
    public ApplicationUserManager(IUserStore<User> store, IIdentityMessageService emailService)
        : base(store)
    {
        this.EmailService = emailService;
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<User>(context.Get<ApplicationDbContext>()), new SmtpEmailService());
        .
        .
        .
        .
        return manager;
    }
}

如果您正在使用依賴注入(DI),那么配置它。 我正在使用UnityContainer( UnityConfig.cs ),所以我的配置是:

container.RegisterType<IIdentityMessageService, SmtpEmailService>();

最后從控制器中使用它:

public async Task<IHttpActionResult> TestSmtpMail()
{
    var subject = "Your subject";
    var body = "Your email body it can be html also";
    var user = await UserManager.FindByEmailAsync("xxx@gmail.com");
    await UserManager.SendEmailAsync(user.Id, subject, body);
    return Ok();
}

您可能會收到以下錯誤:

SMTP服務器需要安全連接或客戶端未經過身份驗證。

然后允許較少的安全應用允許gmail帳戶使其他應用可以訪問

有關詳細信息和SendGrid客戶端,請訪問此處

大。 謝謝。 我有錯誤,因為ConfigurationManager.AppSettings["SupportEmailAddr"]為空。 您必須在web.config文件中設置它。 您有一個名為: <appSettings>. 這也是ConfigurationManager.AppSettings所指的內容。 ["SupportEmailAddr"]正在查看名為SupportEmailAddr的特定設置。 在你的web.config中它看起來像這樣:

<appSettings>
    <add key="SupportEmailAddr" value="someone@example.com" />
</appSettings>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM