2016-11-16 117 views
1

到目前爲止,我有這個代碼用於電子郵件驗證和郵件發送使用SMTPClient但它不會工作,它不會發送到gmail聲明。但我認爲我的代碼沒有問題。我需要一些幫助來發送郵件。如何使用SMTP發送郵件?

string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" 
     + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" 
     + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$"; 
      Regex ex = new Regex(validEmailPattern, RegexOptions.IgnoreCase); 

      if (ex.IsMatch(TextBox1.Text)) 
      { 

       MailMessage m = new MailMessage(); 
       m.From = new MailAddress("[email protected]"); 
       m.To.Add(new MailAddress("[email protected]")); 
       m.Subject = "Try"; 
       m.Body = "TEST"; 

       SmtpClient smtp = new SmtpClient(); 
       smtp.Host = "smtp.gmail.com"; 
       smtp.Port = 587; 
       smtp.Credentials = new System.Net.NetworkCredential() 
       { 
        UserName = "[email protected]", 
        Password = "********" 
       }; 
       smtp.EnableSsl = true; 
       smtp.Send(m); 
+0

你試圖從別人例如Hotmail或Yahoo發送電子郵件?您可能需要允許訪問您的Google帳戶才能通過Gmail發送給我。 – active92

回答

1

改變你smtp.Host = "yourdomainname.com";

+0

[email protected]意味着[email protected]? –

+0

否[email protected]首先在您的域名帳戶中創建webmail –

+0

Gmail帳戶在smtp.gmail.com中不起作用 –

0
Try this code after **smtp.EnableSsl = true;** 

string validEmailPattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|" 
    + @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)" 
    + @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$"; 
     Regex ex = new Regex(validEmailPattern, RegexOptions.IgnoreCase); 

     if (ex.IsMatch(TextBox1.Text)) 
     { 
      SmtpClient smtp = new SmtpClient(); 
      smtp.Host = "smtp.gmail.com"; 
      smtp.Port = 587; 
      smtp.Credentials = new System.Net.NetworkCredential() 
      { 
       UserName = "[email protected]", 
       Password = "********" 
      }; 
      smtp.EnableSsl = true; 

      MailMessage m = new MailMessage(); 
      m.From = new MailAddress("[email protected]"); 
      m.To.Add(new MailAddress("[email protected]")); 
      m.Subject = "Try"; 
      m.Body = "TEST"; 

      smtp.Send(m); 
     }