使用asp.net,C#发送电子邮件

时间:2017-03-21 18:01:59

标签: c# asp.net email smtp

在我的网络应用程序中,我有一个表格向该组人发送电子邮件,我想发送一份副本,但我有例外说:

  

指定的字符串不是电子邮件地址所需的格式。

那是我的代码:

protected void SendButton_Click(object sender, EventArgs e)
{
    string smtpAddress = "smtp.office365.com";
    int portNumber = 587;
    bool enableSSL = true;

    string emailFrom = from.Text;
    string password = PassTextBox.Text;
    string emailTo = toddl.SelectedValue.ToString();
    string subject = subject_txt.Text;

    string body = txtBody.Text;

    using (MailMessage mail = new MailMessage())
    {
        mail.From = new MailAddress(emailFrom);
        mail.To.Add(emailTo);
        mail.Subject = subject;
        mail.Body = body;
        MailAddress copy1 = new MailAddress(ccddl1.SelectedValue.ToString());
        if(copy1!=null)
        {
            mail.CC.Add(copy1);
        }
        MailAddress copy2 = new MailAddress(ccddl2.SelectedValue.ToString());
        if (copy2 != null)
        {
           mail.CC.Add(copy2);
        }

        mail.IsBodyHtml = true;
        // Can set to false, if you are sending pure text.
        if (syllabus_attach.HasFile)
        {
            string FileName = Path.GetFileName(syllabus_attach.PostedFile.FileName);
            mail.Attachments.Add(new Attachment(syllabus_attach.PostedFile.InputStream, FileName));
        }
        if (course_exam_attach.HasFile)
        {
            string FileName = Path.GetFileName(course_exam_attach.PostedFile.FileName);
            mail.Attachments.Add(new Attachment(course_exam_attach.PostedFile.InputStream, FileName));
        }
        if (answer_key_attach.HasFile)
        {
            string FileName = Path.GetFileName(answer_key_attach.PostedFile.FileName);
            mail.Attachments.Add(new Attachment(answer_key_attach.PostedFile.InputStream, FileName));
        }


        using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))

        {
            smtp.UseDefaultCredentials = true;
            smtp.Credentials = new NetworkCredential(emailFrom, password);
            smtp.EnableSsl = enableSSL;

            smtp.Send(mail);
        }


        string script = "alert(\"Request Sent Successfully!\");";
        ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);
    }
}

1 个答案:

答案 0 :(得分:0)

您应该将CC代码更改为

if(!String.IsNullOrWhitespace(ccddl1.SelectedValue.ToString())
{
    mail.CC.Add(new MailAddress(ccddl1.SelectedValue.ToString());
}

if (!String.IsNullOrWhitespace(ccddl2.SelectedValue.ToString())
{
   mail.CC.Add(new MailAddress(ccddl2.SelectedValue.ToString()));
}