-4
在我的web應用程序我有一個表格發送電子郵件到一羣人,我想送的翻版,但我有一個例外,那說:發送電子郵件使用asp.net,C#
指定的字符串不是電子郵件地址所需的格式。
這是我的代碼:
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);
}
}
例外意味着要麼'ccddl1.SelectedValue.ToString()'或'ccddl2.SelectedValue .ToString()'不能被解析爲電子郵件地址。您應該在調用MailAddress(string)之前檢查這兩個值,以確保它們已設置並且是有效的地址,而不是檢查「copy1」或「copy2」是否爲空。 –
似乎錯誤非常直截了當。在發佈堆棧溢出問題之前,確保你進行了基本的調試。 – mason