Asp.net核心1.0从Gmail发送电子邮件

时间:2017-04-28 00:09:51

标签: c# asp.net asp.net-mvc-5 asp.net-core

我是ASP.Net Core的新手,我希望在用户从gmail帐户注册时发送确认电子邮件。我在VS13的一个项目中使用了相同的gmail帐户并取得了很大的成功。但是现在我无法发送。没有错误,我发送的邮箱中没有出现任何电子邮件。

 public async Task SendEmailAsync(string email, string subject, string message)
    {
        var emailMessage = new MimeMessage();

        emailMessage.From.Add(new MailboxAddress("Rentals Rated", "*******@gmail.com"));

        emailMessage.To.Add(new MailboxAddress("", email));
        emailMessage.Subject = subject;
        emailMessage.Body = new TextPart("plain") { Text = message };

        using (var client = new SmtpClient())
        {
            var credentials = new NetworkCredential
            {
                UserName = "********@gmail.com", 
                Password = "******" 
            };
      //      client.LocalDomain = "gmail.com";
            await client.ConnectAsync("smtp.gmail.com", 587, SecureSocketOptions.Auto).ConfigureAwait(false);
            await client.AuthenticateAsync(credentials);
            await client.SendAsync(emailMessage).ConfigureAwait(false);
            await client.DisconnectAsync(true).ConfigureAwait(false);
        }
    }

^我当前的尝试

在VS13中,这是我的工作代码。与问题不太相关,但可能会激发想法。谢谢!

public static void sendEmail(string email, string emailSubject, string emailBody, string firstName)
    {
        MailAddress fromAddress = new MailAddress("*****@gmail.com", "****");
        MailAddress toAddress = new MailAddress(email, firstName);
        const string fromPassword = "*******";

        SmtpClient smtp = new SmtpClient();
        smtp.Host = "smtp.gmail.com";
        smtp.Port = 587;
        smtp.EnableSsl = true;
        smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
        smtp.UseDefaultCredentials = false;
        smtp.Credentials = new System.Net.NetworkCredential(fromAddress.Address, fromPassword);

        MailMessage message = new MailMessage(fromAddress, toAddress);
        message.Subject = emailSubject;
        message.Body = emailBody;
        smtp.Send(message);
    }

注意 调试时,ConnectAsync(...);之后的三行永远不会被击中。

删除异步方法并使用

            client.Connect("smtp.gmail.com", 587, false);
            client.Authenticate(credentials);
            client.Send(emailMessage);
            client.Disconnect(true);

工作正常

0 个答案:

没有答案