我有一个带有两个单选按钮的表单,根据检查的表单,将运行不同的进程。我希望在任一流程完成时发送电子邮件通知,但让主题和正文指出哪个流程已完成。
class SendMail
{
public void sendMail()
{
MailMessage dailyMail = new MailMessage("you@yourcompany.com", "user@hotmail.com");
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
dailyMail.Subject = "Daily load done";
dailyMail.Body = "The daily load process has completed.";
client.Send(dailyMail);
}
}
只是使用这个通用的sendMail方法,我应该保留dailyMail对象(对于一个进程)并创建一个monthlyMail对象(对于另一个进程)并在选择了正确的单选按钮的情况下触发相应的对象吗?
有没有更好的(阅读:更简单)方法来实现这一目标?谢谢。
答案 0 :(得分:2)
您可以将dailyMail对象传递给方法
class SendMail
{
public void sendMail(MailMessage dailyMail)
{
SmtpClient client = new SmtpClient();
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
client.Send(dailyMail);
}
}
然后,您可以在调用方法之前创建dailyMail对象并设置主题和正文。
var dailyMail = new MailMessage("you@yourcompany.com", "user@hotmail.com");
if(radioButton1.Checked)
{
dailyMail.Subject = "Daily load done";
dailyMail.Body = "The daily load process has completed.";
}
else
{
dailyMail.Subject = "Some other subject";
dailyMail.Body = "Some other method";
}
var sendMail = new SendMail();
sendMail.sendMail(dailyMail);
答案 1 :(得分:0)
如果没有看到更多代码,那么确定方法有点困难,但最好创建子类继承的基本邮件类。这些子类设置主题/正文/需要它的任何其他东西。
public abstract class MailBase
{
private SmtpClient _client;
public string To { get; set; }
public string From { get; set; }
public string Subject { get; set; }
public string Body { get; set; }
public MailBase()
{
_client = new SmtpClient();
_client.Port = 25;
_client.DeliveryMethod = SmtpDeliveryMethod.Network;
_client.UseDefaultCredentials = false;
_client.Host = "smtp.google.com";
}
protected void SendInternal()
{
//Send code
}
}
public class DailyMail : MailBase
{
public DailyMail(string to)
{
To = to;
From = "someemail@email.com";
Subject = "My Subject";
Body = "My body";
}
public void Send()
{
SendInternal();
}
}
然后您可以实例化该类型并调用Send
。
//Somewhere in code
var dailyMail = new DailyMail("user@email.com");
dailyMail.Send();
答案 2 :(得分:0)
此解决方案与其他解决方案类似,但利用以静态方法发送邮件的方式,因此呼叫更清洁,资源得到妥善处理。此外,如果需要添加更多单选按钮(或者如果要在其他类或项目中重用代码),UI /表示代码可以分开一些,以便将来更容易发送其他邮件消息。
public class Mailer
{
public static void Send(MailMessage mailMessage)
{
using (SmtpClient client = new SmtpClient())
{
client.Port = 25;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Host = "smtp.google.com";
client.Send(mailMessage);
}
}
}
在UI或表示层代码中:
private void HandleRadioSelection()
{
if (radioButton1.Checked)
{
this.SendMailMessage("Daily load done.", "The daily load process has completed.");
}
else
{
this.SendMailMessage("Some other subject", "Some other body");
}
}
private void SendMailMessage(string subject, string body)
{
using (MailMessage mailMessage = new MailMessage("you@yourcompany.com", "user@hotmail.com", subject, body))
{
Mailer.Send(mailMessage);
}
}