简体   繁体   English

如何使用c#发送电子邮件?

[英]How do I send an Email using c#?

I am trying to make a Windows Form that sends an email when the user clicks a button, but every time I try, an exception is being raised: Failure sending mail. 我试图制作一个Windows窗体,该窗体在用户单击按钮时发送电子邮件,但每次尝试时,都会引发异常:发送邮件失败。 What is wrong with my code? 我的代码有什么问题?

    private void button1_Click(object sender, EventArgs e)
    {
        SmtpClient smtpClient = new SmtpClient();
        NetworkCredential basicCredential =
            new NetworkCredential("username", "password");
        MailMessage message = new MailMessage();
        MailAddress fromAddress = new MailAddress("myemailadress@gmail.com");

        smtpClient.Host = "smpt.gmail.com";
        smtpClient.UseDefaultCredentials = false;
        smtpClient.Credentials = basicCredential;

        message.From = fromAddress;
        message.Subject = "your subject";
        //Set IsBodyHtml to true means you can send HTML email.
        message.IsBodyHtml = true;
        message.Body = "<h1>your message body</h1>";
        message.To.Add("towhomisend@yahoo.com");

        try
        {
            smtpClient.Send(message);
        }
        catch (Exception ex)
        {
            //Error, could not send the message
            MessageBox.Show(ex.Message);
        }
    }

使用"smtp.gmail.com"而不是"smpt.gmail.com"

1) Check whether SMTP settings are correct and server is configured correctly (Host & Port Settings) 1)检查SMTP设置是否正确以及服务器配置是否正确(主机和端口设置)

2)Check whether credentials(user name and password) are correct 2)检查凭据(用户名和密码)是否正确

3)Check whether firewall is blocking the request 3)检查防火墙是否阻止了请求

4).Check port 587 If it is blocked in firewall 4)。检查端口587是否在防火墙中被阻止

Port 587: This is the default mail submission port. 端口587:这是默认的邮件提交端口。 When a mail client or server is submitting an email to be routed by a proper mail server, it should always use this port. 当邮件客户端或服务器提交要由适当的邮件服务器路由的电子邮件时,它应始终使用此端口。

The 'smtpClient.Host = "smpt.gmail.com";' 'smtpClient.Host =“ smpt.gmail.com”;' part is incorrect. 部分不正确。

Change "smpt.gmail.com" to "smtp.gmail.com" 将“ smpt.gmail.com”更改为“ smtp.gmail.com”

"SMTP" - not - "SMPT" “ SMTP”-不-“ SMPT”

use "smtp.gmail.com" instead of "smpt.gmail.com" 使用"smtp.gmail.com" instead of "smpt.gmail.com"

That aside Confirm one more thing, You have to enable email from other program in your gmail. 除了再确认一件事,您必须在gmail中启用来自其他程序的电子邮件。 When you try to send once, you will get a notification in you email ID. 当您尝试发送一次时,您会在电子邮件ID中收到一条通知。 You have to enable it there. 您必须在那里启用它。

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

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