1
if (txtEmail.Text != null)
{
    try
    {
        SmtpClient sc = new SmtpClient("localhost", 587);
        sc.Host = "smtp.gmail.com";
        sc.Credentials = new NetworkCredential("MyEmail@gmail.com", 
                                               "MyPassword");
        sc.DeliveryMethod = SmtpDeliveryMethod.Network;
        sc.EnableSsl = true;
        MailMessage mailMessage = new MailMessage();
        mailMessage.From = new MailAddress("MyEmail@gmail.com");
        mailMessage.Subject = "Sending Test";
        mailMessage.Body = "this is a test message your UserName is"
                            + txtUserName.Text;
        mailMessage.IsBodyHtml = true;
        string mailBox = txtEmail.Text.Trim();
        mailMessage.To.Add(mailBox);
        sc.Send(mailMessage);
        lblMessage.Text = "Mail send...";
    }
    catch (Exception ex)
    {
        lblMessage.Text = ex.Message;
    }
}
else
{
    lblMessage.Text = "you should enter your email address";
}

好吧,首先对不起我的英语语言很差,但是我读了很多关于如何用 C# 发送电子邮件的文章,我知道该怎么做......

但是我的问题是,当我想发送输入到文本框中的电子邮件时,例如

(E-mailAddress.text) 转换成 MailAddress 或 MailMessage.Add,

它给了我一个例外,上面写着

(参数'addresses'不能为空字符串。参数名称:addresses)

并向我展示了用 E-mailAddress.text 填充的 MailAdress 或 MailMessage 对象,而不是像“abc@yahoo.com”这样的字符串,甚至更进一步,我无法发送电子邮件......如果有的话帮助我会很高兴

4

2 回答 2

1

首先我会改变

txtEmail.Text != null 

!string.IsNullOrEmpty(txtEmail.Text)

然后我会尝试这样做:

mailMessage.To.Add(new MailAddress(txtEmail.Text.Trim()));

代替

string mailBox = txtEmail.Text.Trim();
mailMessage.To.Add(mailBox);

我还将实施一种方法来验证输入的电子邮件地址以避免无效地址:)

于 2012-12-20T09:56:13.930 回答
0

检查:

if (txtEmail.Text.Trim() != String.Empty)

代替

if (txtEmail.Text != null)
于 2012-12-20T09:55:42.370 回答