使用此代码使用C#发送电子邮件但不起作用

时间:2015-02-02 20:48:31

标签: c#

这是无效的代码。任何人都可以建议如何使它工作?

protected void Button1_Click1(object sender, EventArgs e)
{
    try
    {
        MailMessage mailMsg = new MailMessage();
        mailMsg.To.Add("ashishbhatt1501@.com");

        string from = email.Text;
        MailAddress mailAddress = new MailAddress(from);
        mailMsg.From = mailAddress;


        mailMsg.Subject = "subject";
        mailMsg.Body = comments.Text;


        SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);
        System.Net.NetworkCredential credentials =
           new System.Net.NetworkCredential("myemail", "password");
        smtpClient.Credentials = credentials;

        smtpClient.Send(mailMsg);
        Page.RegisterStartupScript("UserMsg", "<script>alert('Mail sent thank you...');if(alert){ window.location='SendMail.aspx';}</script>");
    }
    catch (Exception ex)
    {
        Console.WriteLine("{0} Exception caught.", ex);
    }
}

1 个答案:

答案 0 :(得分:0)

电子邮件格式无效。我建议您通过正则表达式运行您的电子邮件字符串,并仅在RegEx返回true时执行其余代码。

var regex = new Regex("\w[-._\w]*\w@\w[-._\w]*\w\.\w{2,3}");
if (regex.Match("abd@abd.com")){
    do something .... 
}