我正在尝试发送一封电子邮件,其中发件人和收件人电子邮件地址(以及主题和正文内容)根据提供给该方法的值而变化。最好用代码本身来解释:
public void EmailNotification(int emailAction)
{
MailAddress to;
MailAddress from;
string subject;
string body;
switch (emailAction)
{
case 1:
// Comment approved
to = new MailAddress("someone@theirdomain.com");
from = new MailAddress("no-reply@thisdomain.com");
subject = "Comment approved";
body = @"The comment you posted has been approved";
break;
case 2:
// Comment rejected
to = new MailAddress("someone@theirdomain.com");
from = new MailAddress("no-reply@thisdomain.com");
subject = "Comment rejected";
body = @"The comment you posted has been rejected";
break;
}
MailMessage message = new MailMessage(from, to);
message.Subject = subject;
message.Body = body;
SmtpClient client = new SmtpClient();
try
{
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in EmailNotification: {0}", ex.ToString());
}
}
所以问题是,由于范围如何与开关一起工作,to、from、subject 等的值在开关之外无法识别,即使我已经在开关之外声明了它们(可能是错误的?)。
我是 .NET 新手,因此对于如何完成此类事情的任何建议将不胜感激。