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

时间:2017-01-24 08:13:51

标签: c# email smtp msg

我想帮助我编码。我正在尝试向电子邮件发送消息但我在尝试单击按钮并发送消息后仍然收到错误。以下是编码:

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

当项目一直停在此处时,给出错误行:

  

{&#34;参数&#39;地址&#39;不能是一个空字符串。\ r \ nParameter name:addresses&#34;}。

任何帮助都将不胜感激。

4 个答案:

答案 0 :(得分:2)

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

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

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

编辑:我看到你的编辑,我认为异常消息&#34;参数&#39;地址&#39;不能是一个空字符串。\ r \ nParameter name:addresses&#34;非常清楚

答案 1 :(得分:1)

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

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

验证电子邮件ID的方法:

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

答案 2 :(得分:1)

错误信息非常清楚 - 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 Forms提供了许多验证输入的方法,如User Input Validation in Windows Forms

中所述

您可以处理txtBoxToEmail 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; } 事件以检查有效地址,并阻止用户离开控件,直到地址正确为止。事实上,文档的示例是电子邮件验证! :

stateScore = Math.min(...newStateScores);

该示例使用Validating组件在违规输入旁边显示感叹号和错误用户界面。

您可以在ErrorProvider

中找到有关ErrorProvider的更多信息

答案 3 :(得分:0)

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

相关问题