我创建了一个电子邮件应用,它向数据库中的所有用户发送电子邮件,但是我遇到了问题,如果用户的电子邮件无效,请尝试catch显示异常并停止向其他人发送信件。继承我的尝试捕获代码
try
{
foreach (string item in risto)
{
AlternateView avHtml = AlternateView.CreateAlternateViewFromString(htmlBody, null, MediaTypeNames.Text.Html);
MailMessage mail = new MailMessage(txtBEmail.Text, item, txtBTema.Text, rtxtBContent.Text);
mail.AlternateViews.Add(avHtml);
// SmtpServer = smtp.company.com; Ex: Gmail - smtp.gmail.com | Yahoo - smtp.yahoo.com
SmtpClient client = new SmtpClient("mail.mailExample.com");
client.Port = 587;
client.Credentials = new System.Net.NetworkCredential(txtBEmail.Text, txtBPass.Text);
client.EnableSsl = false;
client.Send(mail);
progressBar1.Visible = true;
progressBar1.Increment(1);
}
MessageBox.Show("Sent", MessageBoxButtons.OK);
txtBEmail.Text = "";
txtBPass.Text = "";
txtBTema.Text = "";
txtBPic.Text = "";
txtBLink.Text = "";
rtxtBContent.Text = "";
}
catch (Exception ex)
{
MessageBox.Show("Bad data" + ex);
txtBEmail.Text = "";
txtBPass.Text = "";
txtBTema.Text = "";
txtBPic.Text = "";
txtBLink.Text = "";
rtxtBContent.Text = "";
}
答案 0 :(得分:3)
每封电子邮件都需要单独的try / catch:
foreach (var mail in emails)
{
bool emailSent;
// Prepare single email here
try
{
// Try do send it here
// ....
client.Send(mail);
// If the code comes here, it means the mail was sent
emailSent = true;
}
catch
{
// log the exception
}
Debug.WriteLine($"Email to {mail} status: {emailSent}");
}
答案 1 :(得分:1)
整个循环周围有try
/ catch
构造。这意味着一旦一条消息失败,控制就会移动到catch块并且循环停止。
您需要将try
/ catch
放在循环中以捕获每个可能的异常并且能够继续循环下一个项目。