简体   繁体   English

具有Button_Click事件的C#电子邮件

[英]C# Email with Button_Click Event

I'm trying to create a Button_Click event that sends an email to a gmail account. 我正在尝试创建一个Button_Click事件,该事件将电子邮件发送到gmail帐户。 This is the error I'm getting: 这是我得到的错误:

Unable to read data from the transport connection: net_io_connectionclosed. 无法从传输连接中读取数据:net_io_connectionclosed。

It's pointing out Line 63 which is: 指出第63行是:

client.Send(mail);

Here is the code: 这是代码:

protected void Button2_Click(object sender, EventArgs e)
{
    System.Net.Mail.MailMessage mail = new System.Net.Mail.MailMessage();
    SmtpClient client = new SmtpClient();
    client.Port = 465;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Host = "smtp.gmail.com";
    mail.IsBodyHtml = true;
    mail.To.Add(new MailAddress("yourclassroomconnection@gmail.com"));
    mail.From = new MailAddress("yourclassroomconnection@gmail.com");
    mail.Subject = "New Order";
    string bodyTemplate = Label2.Text;
    mail.Body = bodyTemplate;
    client.Send(mail);
}

Any idea where I'm going wrong? 知道我哪里出错了吗?

You can use below code as a small test. 您可以将以下代码用作小测试。 Try sending email with minimal option. 尝试使用最少的选项发送电子邮件。 Then add other options like html support. 然后添加其他选项,例如html support。 So you can narrow down the problem when you're experimenting a new thing. 因此,当您尝试新事物时,可以缩小问题的范围。

       try {
        MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("your_email_address@gmail.com");
            mail.To.Add("to_address");
            mail.Subject = "Test Mail";
            mail.Body = "This is for testing SMTP mail from GMAIL";

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("username", "password");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);

        } catch (Exception ex)
        {

        }

You need to generate app specific password and use it here instead of your gmail password. 您需要生成应用专用密码 ,然后在此处使用它而不是Gmail密码。

Please read this tutorial also. 请同时阅读本教程。 http://csharp.net-informations.com/communications/csharp-smtp-mail.htm http://csharp.net-informations.com/communications/csharp-smtp-mail.htm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM