2017-12-28 10 views
0

내가 ASP.NET 코어에서 작업 및 이메일 기능을 MailKit을 사용하고 응답하는 데 실패합니다. 이전에 사용한 방법은 더 이상 작동하지 않습니다.Gmail은 MailKit

public class SmtpOptions 
    { 
     public string Server { get; set; } = "smtp.gmail.com"; //Gmail limited to 2000 emails per day 
     public int Port { get; set; } = 465; //default for SSL using GMail 
     public string User { get; set; } = "[email protected]"; //must match server domain 
     public string Password { get; set; } = "myPwd"; 
     public bool UseSsl { get; set; } = true; //gmail requires SSL 
     public bool RequiresAuthentication { get; set; } = true; //gmail requires authentication 
     public string PreferredEncoding { get; set; } = string.Empty; 
    } 

및 EmailSender.cs 클래스 :

내가 SmtpOptions.cs 클래스가 함수 호출에 사용되는

public class EmailSender 
    { 
     public EmailSender() 
     { 
     } 

     public async Task SendEmailAsync(
      SmtpOptions smtpOptions, 
      string to, 
      string from, 
      string subject, 
      string plainTextMessage, 
      string htmlMessage, 
      string replyTo = null) 
     { 
      if (string.IsNullOrWhiteSpace(to)) 
      { 
       throw new ArgumentException("no to address provided"); 
      } 

      if (string.IsNullOrWhiteSpace(from)) 
      { 
       throw new ArgumentException("no from address provided"); 
      } 

      if (string.IsNullOrWhiteSpace(subject)) 
      { 
       throw new ArgumentException("no subject provided"); 
      } 

      var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage); 
      var hasHtml = !string.IsNullOrWhiteSpace(htmlMessage); 
      if (!hasPlainText && !hasHtml) 
      { 
       throw new ArgumentException("no message provided"); 
      } 

      var m = new MimeMessage(); 

      m.From.Add(new MailboxAddress("", from)); 
      if (!string.IsNullOrWhiteSpace(replyTo)) 
      { 
       m.ReplyTo.Add(new MailboxAddress("", replyTo)); 
      } 
      m.To.Add(new MailboxAddress("", to)); 
      m.Subject = subject; 

      //m.Importance = MessageImportance.Normal; 
      //Header h = new Header(HeaderId.Precedence, "Bulk"); 
      //m.Headers.Add() 

      BodyBuilder bodyBuilder = new BodyBuilder(); 
      if (hasPlainText) 
      { 
       bodyBuilder.TextBody = plainTextMessage; 
      } 

      if (hasHtml) 
      { 
       bodyBuilder.HtmlBody = htmlMessage; 
      } 

      m.Body = bodyBuilder.ToMessageBody(); 

      using (var client = new SmtpClient()) 
      { 
       await client.ConnectAsync(
        smtpOptions.Server, 
        smtpOptions.Port, 
        smtpOptions.UseSsl) 
        .ConfigureAwait(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 
       if (smtpOptions.RequiresAuthentication) 
       { 
        await client.AuthenticateAsync(smtpOptions.User, smtpOptions.Password) 
         .ConfigureAwait(false); 
       } 

       await client.SendAsync(m).ConfigureAwait(false); 
       await client.DisconnectAsync(true).ConfigureAwait(false); 
      } 

     } 

     public async Task SendMultipleEmailAsync(
      SmtpOptions smtpOptions, 
      string toCsv, 
      string from, 
      string subject, 
      string plainTextMessage, 
      string htmlMessage) 
     { 
      if (string.IsNullOrWhiteSpace(toCsv)) 
      { 
       throw new ArgumentException("no to addresses provided"); 
      } 

      if (string.IsNullOrWhiteSpace(from)) 
      { 
       throw new ArgumentException("no from address provided"); 
      } 

      if (string.IsNullOrWhiteSpace(subject)) 
      { 
       throw new ArgumentException("no subject provided"); 
      } 

      var hasPlainText = !string.IsNullOrWhiteSpace(plainTextMessage); 
      var hasHtml = !string.IsNullOrWhiteSpace(htmlMessage); 
      if (!hasPlainText && !hasHtml) 
      { 
       throw new ArgumentException("no message provided"); 
      } 

      var m = new MimeMessage(); 
      m.From.Add(new MailboxAddress("", from)); 
      string[] adrs = toCsv.Split(','); 

      foreach (string item in adrs) 
      { 
       if (!string.IsNullOrEmpty(item)) { m.To.Add(new MailboxAddress("", item)); ; } 
      } 

      m.Subject = subject; 
      m.Importance = MessageImportance.High; 

      BodyBuilder bodyBuilder = new BodyBuilder(); 
      if (hasPlainText) 
      { 
       bodyBuilder.TextBody = plainTextMessage; 
      } 

      if (hasHtml) 
      { 
       bodyBuilder.HtmlBody = htmlMessage; 
      } 

      m.Body = bodyBuilder.ToMessageBody(); 

      using (var client = new SmtpClient()) 
      { 
       await client.ConnectAsync(
        smtpOptions.Server, 
        smtpOptions.Port, 
        smtpOptions.UseSsl).ConfigureAwait(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 
       if (smtpOptions.RequiresAuthentication) 
       { 
        await client.AuthenticateAsync(
         smtpOptions.User, 
         smtpOptions.Password).ConfigureAwait(false); 
       } 

       await client.SendAsync(m).ConfigureAwait(false); 
       await client.DisconnectAsync(true).ConfigureAwait(false); 
      } 

     } 

    } 

: 언급 한 바와 같이

public async void ContactMessage(string title, string message, string toEmail) 
     { 
      string thisMessage = "No Message Provided"; 
      if (!String.IsNullOrEmpty(message)) { thisMessage = message; } //in case empty form 
      string thisTitle = title; 
      //create email objects 
      EmailSender emailSender = new EmailSender(); 
      SmtpOptions smtpOptions = new SmtpOptions(); //default settings ok 
      string fromEmail = smtpOptions.User; 

      string subjectLine = "Message Title"; 

      await emailSender.SendEmailAsync(smtpOptions, toEmail, fromEmail, subjectLine, thisMessage, ""); 
     } 

, 이 방법은 이전에는 효과가 있었지만 현재는 Gmail이 응답하지 않습니다. IMAP 및 POP를 확인하고 사용하도록 설정했습니다.

특정 예외가 읽기 : "System.Net.Internals.SocketExceptionFactory.ExtendedSocketEception : '연결된 당사자가 일정 기간 후에 제대로 응답하지 않았거나 연결된 호스트가 있기 때문에 연결이 실패하여 연결 시도가 실패했습니다. " '

이 코드를 배포하지만 테스트 환경에서이 오류가 발생되지 않았습니다 응답하지 못했습니다. 방화벽이 다른 시스템으로 이동하면 "Mailkit.Security.Authentication; MailKit 인증이 너무 약함"이라는 오류가 발생합니다.

Yahoo! smtp는 위의 코드가 작동하도록 허용하여 Mailkit과 Gmail 간의 호환성이 변경된 것처럼 보입니다. Gmail을 사용하기위한 Mailkit 구성은 무엇입니까?

+0

:

1)의 OAuth에게 EmailSender.cs 클래스 내에서 2.0 자격 증명 또는 2) 변경 이메일 계정 설정을 얻기는 보안 수준이 낮은 앱

자세한 내용은에 있습니다 허용하도록 이전에 작동했지만 코드 나 Gmail 설정에서 변경하지 않은 경우 Google 지원 팀에 문의해야한다고 생각하지 않습니까? StackOverflow는 프로그래밍 관련 질문 용이며 정확한 오류를 제공하지 않았습니다. – Tseng

+0

내가 충분히 명확하지 않은 경우 미안합니다. 이것은 코드 재사용의 예입니다. 전에는 WebForms 응용 프로그램에서 작동했지만 지금은 asp.net 코어 MVC를 시도하고 있습니다. 나는 ASP.NET Core에 익숙하지 않아서 프레임 워크의 차이점과 관련이 있다고 생각하기 때문에 여기에서 묻고 있습니다. 정확한 예외는 "System.Net.Internals.SocketExceptionFactory.ExtendedSocketException : '연결된 파티 일정 시간 후에 제대로 응답하지 않았기 때문에 연결 시도가 실패, 또는 ​​설정된 연결이 연결된 호스트가 응답하지 않았기 때문에 실패'" – coolhand

+0

더 나은을 답변에서 예외를 업데이트하십시오. 질문을 읽을 때 모든 사람이 모든 의견을 읽지는 않습니다. 또한 너무 많은 정보가 누락되었습니다. 로컬에서 테스트 할 때 또는 배포 후에 발생합니까? Webform 응용 프로그램이 정확히 동일한 코드로 실행됩니까? 또한 WinForms는 .NET Framework에서 실행되지만 ASP.NET Core는 기본적으로 .NET Core에서 실행됩니다..NET Framework 2.0 .NET Framework를 실행하면 동일한 오류가 발생합니까? – Tseng

답변

0

일반적으로 AUTH 메커니즘이 너무 약하다고 말하는 AuthenticationException이 발생하면 클라이언트가 PLAIN 또는 LOGIN 메커니즘을 사용하려고 시도 했으므로 서버는 SSL을 통해 해당 메커니즘 만 사용하도록 허용합니다.

SSL을 사용하는 포트 465 또는 세 번째 인수로 SecureSocketOptions.StartTls를 사용하는 포트 587에 연결하고 있는지 확인하십시오.