使用Gmail SMTP服务器C#ASP.NET联系表单。更新的代码?

时间:2016-12-18 19:31:07

标签: c# asp.net email smtp contact-form

似乎有相当多的重复,但它已经存在了很多年,从那以后,Gmail已经更新了它的安全功能,其中大多数代码都会返回错误。

是否有更新的代码来实现此目的。

我使用的代码是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Net.Mail;
using System.Net;
namespace uni{

public partial class contact : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void SendMail()
    {
        var fromAddress = "";// Gmail Address from where you send the mail
        var toAddress = mail.Value.ToString();
        const string fromPassword = "";//Password of gmail address
        string subject = "User Query";
        string body = "From: " + n.Text + "\n";
        body += "Email: " + em.Text + "\n";
        body += "Query: \n" + mssg.Text + "\n";

        var smtp = new System.Net.Mail.SmtpClient();
        {
            smtp.Host = "smtp.gmail.com";
            smtp.Port = 587;
            smtp.EnableSsl = true;
            smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
            smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
            smtp.Timeout = 20000;
        }

        smtp.Send(fromAddress, toAddress, subject, body);
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
            con.Open();
            string inscmd = " Insert into Feedback (Name, Email, Message) values (@Name, @Email, @Message)";
            SqlCommand insert = new SqlCommand(inscmd, con);
            insert.Parameters.AddWithValue("@Name", n.Text);
            insert.Parameters.AddWithValue("@Email", em.Text);
            insert.Parameters.AddWithValue("@Feedback", mssg.Text);

            try
            {
                insert.ExecuteNonQuery();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert(' Your query was successfully submitted.')", true);
                con.Close();

                try
                {
                    SendMail();
                    Response.Redirect("Thanks.html");
                }
                catch (Exception) { }
            }
            catch (SqlException)
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert(' There was some error please try again.')", true);
            }
        }
        catch (Exception)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "alertmessage", "javascript:alert(' There was some error please try again.')", true);
        }
    }
}

0 个答案:

没有答案