【问题标题】:c# Send Mail/ Message/ SMTP Errorc#发送邮件/消息/ SMTP错误
【发布时间】:2017-06-08 22:50:18
【问题描述】:

我需要一些关于我的编码的帮助。我正在尝试向电子邮件发送消息,但在尝试单击按钮并发送消息后,我一直收到错误消息。下面是代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Mail;


namespace CO6009DissertationV5
{

    public partial class frmSendMsg : Form
    {

        public frmSendMsg()
        {
            InitializeComponent();
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            SmtpClient client = new SmtpClient();
            client.Host = "smtp.gmail.com";
            client.Port = 587;
            client.EnableSsl = true;

            System.Net.NetworkCredential userpassword = new System.Net.NetworkCredential();
            userpassword.UserName = "user@gmail.com";
            userpassword.Password = "password";

            client.Credentials = userpassword;

            MailMessage msg = new MailMessage("user@gmail.com", "user@gmail.com");
            **msg.To.Add(new MailAddress(txtBoxToEmail.Text));**
            msg.Body = "<b> Sender's Name: </b>" + txtBoxName.Text + "<p><b> Sender's E-mail: </b>" + txtBoxEmail.Text + "<p><b>Sender's Subject: </b>" + txtBoxSubject.Text + "<p><b>Sender's Message: </b>" + "<p>" + txtBoxMsg.Text;
            msg.Subject = txtBoxSubject.Text;
            msg.IsBodyHtml = true;

            try
            {
                client.Send(msg);
                lblMsgStatus.Text = "<p> Message Successfully Sent </p>";
            }

            catch (Exception ex)
            {
                lblMsgStatus.Text = "Send failed";
            }
        }
    }
}

主要问题似乎是这一行:

msg.To.Add(new MailAddress(txtBoxToEmail.Text));

由于项目一直停在这里,给出错误行:

{"参数'addresses'不能为空字符串。\r\n参数名称:addresses"}.

任何帮助将不胜感激。

【问题讨论】:

  • 永远不要在此处粘贴带有您的用户/密码的代码!
  • 能否请您添加您收到的错误消息的文本?
  • 还要检查Sending email in .NET through Gmail 和许多其他已经问过的问题 - 很可能有人以前遇到过你的错误。
  • 该错误是不言自明的。看来您正在添加一个空邮件...
  • 错误很明显 - 文本框为空。检查文本框内容在发送消息之前,例如String.IsNullOrWhitespace。更好的是,使用 Windows 窗体验证来防止用户使用空地址框进行发送。检查User Input Validation in Windows Forms

标签: c# email smtp msg


【解决方案1】:

仅当 txtBoxToEmail.Text 不是有效的电子邮件地址时,此行才会失败

msg.To.Add(new MailAddress(txtBoxToEmail.Text));

如果仍不清楚,请使用 try-catch 包装您的代码并评估异常详细信息

编辑:我看到你的编辑,我认为异常消息“参数'地址'不能是空字符串。\r\n参数名称:地址”很清楚

【讨论】:

    【解决方案2】:

    最好在发送邮件之前验证您的 EmailId。请添加以下方法 并在您的按钮单击事件中调用它,如下所示:

         if (IsValidEmail(txtBoxToEmail.Text))
         {
                msg.To.Add(new MailAddress(txtBoxToEmail.Text));
         } 
    

    验证Email id的方法:

        static bool IsValidEmail(string email)
        {
            try
            {
                var addr = new System.Net.Mail.MailAddress(email);
                return addr.Address == email;
            }
            catch
            {
                return false;
            }
        }
    

    【讨论】:

    • 这和原始代码是一样的,包裹在一个try/catch中。这不执行任何类型的验证。 OP 已经将代码包装在 try/catch 块中。
    • @Panagiotis Kanavos 你能告诉原始代码中的空检查吗?
    • @Panagiotis Kanavos 我发布的答案将检查为空。
    • 我已经解释过了。这与 OP 使用的代码相同。它不能解决问题。 OP已经接收到一个异常并且已经产生了一条消息。验证意味着实际检查该值是否正常
    • Panagiotis Kanavo:很好。你能告诉我在原始代码中你在哪里可以找到对电子邮件 ID 的空检查吗? .我发布的上述代码将检查 null。这可能是一个很好的解决方案。如果您仍然认为此解决方案被否决。谢谢。我尝试在功能上给出一些更好的解决方案。
    【解决方案3】:

    错误信息非常清楚 - TO 地址文本为空。这意味着txtBoxToEmail.Text 是空的。

    您可以通过在使用前检查地址来避免将来出现此类问题。您可以使用String.IsNullOrWhitespace 轻松检查空字符串,例如:

    private void btnSend_Click(object sender, EventArgs e)
    {
        if (String.IsNullOrWhitespace(txtBoxToEmail.Text))
        {
            MessageBox.Show("To can't be empty!","Invalid Address",
                            MessageBoxButtons.OK,MessageBoxIcon.Error);
            return;
        }
    ...
    

    您可以添加更详细的检查,例如确保文本包含@ 字符。

    不过,更好的解决方案是向控件和表单本身添加验证,这样用户就无法在没有输入正确输入的情况下尝试发送电子邮件。

    Windows 窗体提供了多种验证输入的方法,如 User Input Validation in Windows Forms 中所述。

    您可以处理txtBoxToEmailValidating 事件以检查有效地址并防止用户在地址正确之前离开控件。实际上,文档的示例是电子邮件验证! :

    private void textBox1_Validating(object sender, 
                    System.ComponentModel.CancelEventArgs e)
    {
       string errorMsg;
       if(!ValidEmailAddress(textBox1.Text, out errorMsg))
       {
          // Cancel the event and select the text to be corrected by the user.
          e.Cancel = true;
          textBox1.Select(0, textBox1.Text.Length);
    
          // Set the ErrorProvider error with the text to display. 
          this.errorProvider1.SetError(textBox1, errorMsg);
       }
    }
    
    private void textBox1_Validated(object sender, System.EventArgs e)
    {
       // If all conditions have been met, clear the ErrorProvider of errors.
       errorProvider1.SetError(textBox1, "");
    }
    public bool ValidEmailAddress(string emailAddress, out string errorMessage)
    {
       // Confirm that the e-mail address string is not empty.
       if(String.IsNullOrWhitespace(emailAddress.Length))
       {
          errorMessage = "e-mail address is required.";
             return false;
       }
    
       // Confirm that there is an "@" and a "." in the e-mail address, and in the correct order.
       if(emailAddress.IndexOf("@") > -1)
       {
          if(emailAddress.IndexOf(".", emailAddress.IndexOf("@") ) > emailAddress.IndexOf("@") )
          {
             errorMessage = "";
             return true;
          }
       }
    
       errorMessage = "e-mail address must be valid e-mail address format.\n" +
          "For example 'someone@example.com' ";
          return false;
    }
    

    示例使用ErrorProvider 组件在有问题的输入旁边显示感叹号和错误用户界面。

    你可以在How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component找到更多关于ErrorProvider的信息

    【讨论】:

      【解决方案4】:

      最好的方法是检查 txtBoxToEmail.Text 的值。也许它是空的或空的。 然后使用 .To.Add(new MailAddress(txtBoxToEmail.Text));

      【讨论】:

        猜你喜欢
        • 2013-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-28
        • 1970-01-01
        • 1970-01-01
        • 2020-10-27
        相关资源
        最近更新 更多