简体   繁体   English

c#发送邮件/邮件/ SMTP错误

[英]c# Send Mail/ Message/ SMTP Error

I would like some help with my coding please. 我需要一些编码方面的帮助。 I am trying to send an message to an email but I keep getting an error after I try to click on the button and send the message. 我正在尝试通过电子邮件发送消息,但是尝试单击按钮并发送消息后,我一直收到错误消息。 Below is the coding: 下面是代码:

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";
            }
        }
    }
}

The main problem seems to be this line: 主要问题似乎是这一行:

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

As the project keeps stopping here, giving the error line: 由于项目一直在此处停止,因此出现错误行:

{"The parameter 'addresses' cannot be an empty string.\\r\\nParameter name: addresses"}. {“参数'addresses'不能为空字符串。\\ r \\ n参数名称:地址”}。

Any help would be appreciated. 任何帮助,将不胜感激。

This line can fail only if txtBoxToEmail.Text is not a valid e-mail address 仅当txtBoxToEmail.Text不是有效的电子邮件地址时,此行才能失败

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

If it's still not clear, please wrap your code with try-catch and evaluate exception details 如果仍然不清楚,请用try-catch包装您的代码并评估异常详细信息

EDIT: I see your edit, i think the exception message "The parameter 'addresses' cannot be an empty string.\\r\\nParameter name: addresses" is pretty clear 编辑:我看到您的编辑,我认为异常消息“参数'地址'不能为空字符串。\\ r \\ n参数名称:地址”非常清楚

Its better to validate your EmailId before send mail. 在发送邮件之前最好先验证您的EmailId。 Kindly add below method and call it in your button click event like this : 请添加以下方法,并在您的按钮单击事件中调用它,如下所示:

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

Method to validate Email id : 验证电子邮件ID的方法:

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

The error message is pretty clear - the TO address text is empty. 错误消息非常清楚-TO地址文本为空。 This means that txtBoxToEmail.Text is empty. 这意味着txtBoxToEmail.Text为空。

You can avoid such problems in the future by checking the address before using it. 您可以通过在使用地址之前检查地址来避免将来出现此类问题。 You can easily check for empty strings with String.IsNullOrWhitespace , eg: 您可以使用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;
    }
...

You can add more elaborate checks, eg ensuring that the text contains a @ character. 您可以添加更多详细的检查,例如,确保文本包含@字符。

An even better solution though, would be to add validation to the controls and form itself, so that the user can't try to send an email without typing the correct input. 但是,更好的解决方案是将验证添加到控件中并自行形成表单,以便用户在没有输入正确输入的情况下无法尝试发送电子邮件。

Windows Forms provides many ways to validate input, as described in User Input Validation in Windows Forms . Windows窗体提供了许多验证输入的方法,如Windows窗体中的用户输入验证中所述。

You can handle the Validating event of txtBoxToEmail to check for a valid address and prevent the user from leaving the control until the address is correct. 您可以处理txtBoxToEmailValidating事件以检查有效地址,并防止用户在地址正确之前离开控件。 In fact, the documentation's example is an email validation! 实际上,文档的示例是电子邮件验证! :

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;
}

The sample uses the ErrorProvider component to display an exclamation mark and error UI next to the offending input. 该示例使用ErrorProvider组件在有问题的输入旁边显示感叹号和错误UI。

You can find more information about ErrorProvider in How to: Display Error Icons for Form Validation with the Windows Forms ErrorProvider Component 您可以在如何:使用Windows Forms ErrorProvider组件显示用于表单验证的错误图标中找到有关ErrorProvider的更多信息。

The good way is checking the value of txtBoxToEmail.Text. 好的方法是检查txtBoxToEmail.Text的值。 maybe it is null or empty. 可能为null或为空。 Then use .To.Add(new MailAddress(txtBoxToEmail.Text)); 然后使用.To.Add(new MailAddress(txtBoxToEmail.Text));

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

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