【问题标题】:Sending Email in C# does not work在 C# 中发送电子邮件不起作用
【发布时间】:2013-09-25 23:59:42
【问题描述】:

我正在编写一个可以用 C# 发送消息的 windows 窗体。

我曾经有过这个工作并发送消息,但现在我的程序在发送消息时只是挂起。

这里是发送消息的代码:

private void sendEmail()
    {
        string host = "";
        int port = 0;

        host = checkFromAddress(ref port);

        try
        {
            // Create the email to send
            System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
            message.To.Add(recipient1.Text);
            message.Subject = "subject";
            message.From = new System.Net.Mail.MailAddress(userName.Text);
            message.Body = "Test Messge";

            // Setup smtp information related to the host used
            System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
            smtp.Host = host;
            smtp.Port = port;
            smtp.EnableSsl = true;
            smtp.Credentials = new System.Net.NetworkCredential(userName.Text, password.Text);

            // Send the message
            smtp.Send(message);
        }
        catch (Exception)
        {
            MessageBox.Show("Please check email settings and try again");
        }
    }

在表单中输入用户名和密码,根据用户的凭据确定主机和端口。

我调试程序,当它到达 smtp.Send(message) 时,它只是挂起,我无法调出表单。我必须停止调试或终止进程。

任何想法为什么它不起作用?

【问题讨论】:

  • 你试过让它超时吗?
  • 我知道 MailAddress(userName.Text) 中的构造函数要求变量是电子邮件地址而不是名称?除此之外,我建议减少组件的方法。设置一些你肯定知道应该有效的字符串文字,然后向后工作。
  • 感谢您的建议,如果我让它超时,我会看看会发生什么。
  • 我的错,这是我遇到的主机端口问题。我访问了多个站点以获取服务器信息,其中一个站点的端口号一定是错误的。

标签: c# winforms email smtp


【解决方案1】:

您是否验证了所有传入的值都是有效的?可能要检查的是主机/端口。此外,“发件人”和“收件人”是否获得有效的电子邮件地址?这些看起来有点可疑。

【讨论】:

  • 我现在正在检查这些。我认为输入的地址可能是问题,超时导致我在那里输入错误消息,因此存在一些设置问题
猜你喜欢
  • 1970-01-01
  • 2018-09-21
  • 1970-01-01
  • 2016-02-11
  • 2012-08-01
  • 2018-10-30
  • 2017-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多