c# SmtpClient class not able to send email using gmail

前端 未结 7 1073
-上瘾入骨i
-上瘾入骨i 2020-11-27 16:24

I\'m having trouble sending email using my gmail account. Im pulling my hair out.

The same settings work fine in Thunderbird.

Here\'s the code. I\'ve also tr

7条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 17:02

    It works fine in my case:

    private void btnTestConnection_Click(object sender, EventArgs e)
         {
        btnTestConnection.Enabled = false;
        SmtpClient ss = new SmtpClient(txtSmtpHostName.Text.Trim(), Convert.ToInt32(numSmtpHostPort.Value));
        ss.EnableSsl = chkSmtpSecureType.Checked;
        ss.Timeout = 10000;
        ss.DeliveryMethod = SmtpDeliveryMethod.Network;
        ss.UseDefaultCredentials = false;
        ss.Credentials = new NetworkCredential(txtSmtpAccount.Text.Trim(), txtSmtpPassword.Text);
    
        MailMessage mm = new MailMessage(txtSmtpFromEmail.Text.Trim(), "test@domain.com", "subject", "my body");
        mm.BodyEncoding = UTF8Encoding.UTF8;
        mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
        ss.SendCompleted += (s, b) =>
        {
            ss.Dispose();
            mm.Dispose();
        };
        try
        {
            ss.Send(mm);
            ss.Dispose();
            mm.Dispose();
            MessageBox.Show("Connection successfully");
        }
        catch (Exception ep)
        {
            MessageBox.Show("Connection error: " + ep.Message, "Smtp Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        btnTestConnection.Enabled = true;
    }
    

提交回复
热议问题