2016-07-05 62 views
2

我正在使用Gmail的Gmail(已经设置在我的Gmail帐户允许它)。但是每次有一台不同的电脑尝试这样做时,gmail说有人试图使用我的帐户并询问是否是我(因此我的确认电子邮件未发送)。尝试使用SMTP与Gmail邮箱

using Microsoft.AspNet.Identity; 
using System; 
using System.Configuration; 
using System.Net; 
using System.Net.Mail; 
using System.Threading.Tasks; 

namespace Prac.Services 
{ 
public class EMail : IIdentityMessageService 
{ 

    #region Private Fields 

    private static string FromAddress; 
    private static string strSmtpClient; 
    private static string UserID; 
    private static string Password; 
    private static string SMTPPort; 
    private static bool bEnableSSL; 

    #endregion 

    #region Interface Implementation 

    public async Task SendAsync(IdentityMessage message) 
    { 
     await configSendGridasync(message); 
    } 

    #endregion 

    #region Send Email Method 
    public async Task configSendGridasync(IdentityMessage message) 
    { 
     GetMailData(); 
     dynamic MailMessage = new MailMessage(); 
     MailMessage.From = new MailAddress(FromAddress); 
     MailMessage.To.Add(message.Destination); 
     MailMessage.Subject = message.Subject; 
     MailMessage.IsBodyHtml = true; 
     MailMessage.Body = message.Body; 

     SmtpClient SmtpClient = new SmtpClient(); 
     SmtpClient.Host = strSmtpClient; 
     SmtpClient.EnableSsl = bEnableSSL; 
     SmtpClient.Port = Int32.Parse(SMTPPort); 
     SmtpClient.Credentials = new NetworkCredential(UserID, Password); 

     try 
     { 
      try 
      { 
       SmtpClient.Send(MailMessage); 

      } 
      catch (Exception ex) 
      { 

      } 
     } 
     catch (SmtpFailedRecipientsException ex) 
     { 
      for (int i = 0; i <= ex.InnerExceptions.Length; i++) 
      { 
       SmtpStatusCode status = ex.StatusCode; 
       if ((status == SmtpStatusCode.MailboxBusy) | (status == SmtpStatusCode.MailboxUnavailable)) 
       { 
        System.Threading.Thread.Sleep(5000); 
        SmtpClient.Send(MailMessage); 
       } 
      } 
     } 

    } 

    #endregion 

    #region Get Email provider data From Web.config file 
    private static void GetMailData() 
    { 
     FromAddress = ConfigurationManager.AppSettings.Get("FromAddress"); 
     strSmtpClient = ConfigurationManager.AppSettings.Get("SmtpClient"); 
     UserID = ConfigurationManager.AppSettings.Get("UserID"); 
     Password = ConfigurationManager.AppSettings.Get("Password"); 
     //ReplyTo = System.Configuration.ConfigurationManager.AppSettings.Get("ReplyTo"); 
     SMTPPort = ConfigurationManager.AppSettings.Get("SMTPPort"); 
     if ((ConfigurationManager.AppSettings.Get("EnableSSL") == null)) 
     { 
     } 
     else 
     { 
      if ((System.Configuration.ConfigurationManager.AppSettings.Get("EnableSSL").ToUpper() == "YES")) 
      { 
       bEnableSSL = true; 
      } 
      else 
      { 
       bEnableSSL = false; 
      } 
     } 
    } 
    #endregion 

} 

}

+0

“发件人地址”,用户名和密码都必须来自同一个用户帐户。确保“发件人地址”与“用户ID”相匹配。 – jdweng

回答