Skip to main content
 首页 » 编程设计

c#之如何从 C# 程序发送电子邮件

2024年02月01日33telwanggs

我需要从我的程序发送一封电子邮件我写了这段代码但它没有工作错误是

" Le serveur SMTP requiert une connexion sécurisée ou le client n'était pas authentifié. La réponse du serveur était : 5.7.0 Must issue a STARTTLS command first. e2sm19845644wix.15 - gsmtp "

英文翻译:

"The SMTP server requires a secure connection or the client was not authenticated The server response was : 5.7.0 Must issue a STARTTLS command first e2sm19845644wix.15 - gsmtp"

private void button3_Click(object sender, EventArgs e) 
{ 
    try 
    {    
         MailMessage mail = new MailMessage(); 
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 
 
         SmtpServer.Credentials = new System.Net.NetworkCredential("oussabdalla@gmail.com", "xxx"); 
        mail.From = new MailAddress("oussabdalla@gmail.com"); 
        mail.To.Add(textBox4.Text); 
        mail.Subject = "Attention"; 
        mail.Body = textBox1.Text + textBox2.Text + textBox3.Text + "est absent de " + comboBox5.SelectedValue + "a" + comboBox4.SelectedValue; 
 
        SmtpServer.Port = 587; 
 
 
 
        SmtpServer.Send(mail); 
        SmtpServer.EnableSsl = true; 
        MessageBox.Show("mail Send"); 
 
    } 
    catch (Exception ex)   
    { 
        MessageBox.Show(ex.ToString()); 
    } 
} 

我按照建议更改了我的代码并得到了一个新错误

" Le délai d'attente de l'opération a expiré "

翻译:

"The transaction timeout has expired"

private void button3_Click(object sender, EventArgs e) 
{ 
        try 
        { 
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); 
            MailMessage mail = new MailMessage(); 
            SmtpServer.Credentials = new System.Net.NetworkCredential("oussabdalla@gmail.com", "xxxxx"); 
            SmtpServer.UseDefaultCredentials = false; 
 
        mail.From = new MailAddress("oussabdalla@gmail.com"); 
        mail.To.Add(textBox4.Text); 
        mail.Subject = "Attention"; 
        mail.Body = textBox1.Text + textBox2.Text + textBox3.Text + "est absent de " + comboBox5.SelectedValue + "a" + comboBox4.SelectedValue; 
 
        SmtpServer.Port = 465; 
 
        SmtpServer.EnableSsl = true; 
 
        SmtpServer.Send(mail); 
 
        MessageBox.Show("mail Send"); 
 
    } 
    catch (Exception ex)   
    { 
        MessageBox.Show(ex.ToString()); 
    } 
} 

请您参考如下方法:

调用SmtpServer.Send(mail);前需要设置SmtpServer.EnableSsl = true;才能生效。

由于我对法语的了解有限,我会说该消息要求您使用 STARTTLS 使用安全连接。

Google 表示,当您使用端口 587 时,您需要使用 TLS,如所述 here .因此,您可能会考虑使用端口 465,这表示使用 SSL 而不是 587-TLS 端口。

Here is another post这很好地解释了如何通过 gmail 发送电子邮件的示例。它还清楚地表明,您需要在分配实际凭据之前设置 UseDefaultCredentials = false!