Skip to main content
 首页 » 编程设计

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

2024年02月05日48exmyth

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

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

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

{"The parameter 'addresses' cannot be an empty string.\r\nParameter name: addresses"}.

如有任何帮助,我们将不胜感激。

请您参考如下方法:

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

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

如果还是不清楚,请用try-catch包裹你的代码并评估异常细节

编辑:我看到了您的编辑,我认为异常消息“参数‘地址’不能为空字符串。\r\n参数名称:地址”非常清楚