从文本框中获取电子邮件地址并发送

时间:2012-12-20 09:02:51

标签: c#

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'不能是空字符串。参数名称:地址)

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

2 个答案:

答案 0 :(得分: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);

另外,我会实现一种方法来验证输入的电子邮件地址,以避免无效地址:)

答案 1 :(得分:0)

检查:

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

而不是

if (txtEmail.Text != null)