从表单应用程序发送电子邮件(为什么不起作用)

sending an email from an forms Application (why dosen't it work)

我正在尝试学习如何使用 c# visual studio 表单应用程序发送简单的电子邮件。 (它也可以是我所关心的所有控制台应用程序)。这是我的代码(我看不出代码有什么问题,它应该可以正常工作?):

using System.Net.Mail;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            MailMessage mail = new MailMessage();
            SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

            mail.From = new MailAddress("(here is my email)");
            mail.To.Add("(here is my email)");
            mail.Subject = "toja";
            mail.Body = "ja";

            SmtpServer.Port = 587;
            SmtpServer.Credentials = new System.Net.NetworkCredential("(here is my email)", "(here is my password)");
            SmtpServer.EnableSsl = true;

            SmtpServer.Send(mail);
            MessageBox.Show("mail Send");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }

}

}

我使用以下方法从 C# Forms 应用程序发送电子邮件并且它有效。 也许您应该尝试添加 smtp.UseDefaultCredentials = false 属性 并设置凭据 属性?

// Create our new mail message
MailMessage mailMessage = new MailMessage();
mailMessage.To.Add("toAddress");
mailMessage.From = new MailAddress("fromAddress");
mailMessage.Subject = "subject";
mailMessage.Body = "body";

// Set the IsBodyHTML option if it is HTML email
mailMessage.IsBodyHtml = true;

// Enter SMTP client information
SmtpClient smtpClient = new SmtpClient("mail.server.address");
NetworkCredential basicCredential = new NetworkCredential("username", "password"); 
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = basicCredential;
smtpClient.Send(mailMessage);

如果使用 Gmail,您可以在此处找到 SMTP 服务器信息 https://support.google.com/a/answer/176600?hl=en。看起来地址是 smtp.gmail.com,端口是 465(对于 SSL)或 587(对于 TLS)。我建议您首先尝试使用默认端口 25 以确保您的电子邮件通过,然后在需要时调整到不同的端口。