【发布时间】: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。