如何使用SMTP发送邮件?

时间:2016-11-16 23:26:59

标签: c# asp.net smtp

到目前为止,我有这个用于电子邮件验证的CODE和一个使用SMTPClient发送邮件但是它不起作用,它不会发送到gmail声明。但我认为我的代码没有问题。我需要一些帮助才能发送邮件。

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("kennethmontealto91@gmail.com");
                m.To.Add(new MailAddress("kennethmontealto91@gmail.com"));
                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 = "kennethmontealto91@gmail.com",
                    Password = "********"
                };
                smtp.EnableSsl = true;
                smtp.Send(m);

2 个答案:

答案 0 :(得分:1)

更改您的smtp.Host = "yourdomainname.com";

答案 1 :(得分: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 = "kennethmontealto91@gmail.com",
                Password = "********"
            };
            smtp.EnableSsl = true;

            MailMessage m = new MailMessage();
            m.From = new MailAddress("kennethmontealto91@gmail.com");
            m.To.Add(new MailAddress("kennethmontealto91@gmail.com"));
            m.Subject = "Try";
            m.Body = "TEST";

            smtp.Send(m);
        }