我有2个aspx.cs页面。 第一页用于登录,登录后我拨打方法发送和发送电子邮件作为用户所在的警报。 登录后,您将转到第二页。 我想在第二页中创建另一个按钮,当你按下它时,它会再次发送电子邮件(第1页的相同发送方法)。 我是否可以在第2页中调用第1页的“发送”方法,或者我必须在每个页面中编写整个方法?
这是第1页代码:
public partial class UserLogin : System.Web.UI.Page
{
private string _employee;
private string _userName;
private string _loginDatetime;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LoginBtn_Click(object sender, EventArgs e)
{
_employee = employeeBox.Text;
_userName = userBox.Text;
_loginDatetime = DateTime.Now.ToString();
SendMail("your_email@gmail.com", "your_email@gmail.com", "your_email@gmail.com", "Login Alert",
"Hello " + _employee + ",<Br>User \"" + _userName + "\" just log to the website on the following date: " + DateTime.Now);
Response.Redirect("http://localhost:21361/UserDeposit.aspx?_employee=" + employeeBox.Text + "&_userName=" + userBox.Text + "&_loginDatetime=" + _loginDatetime);
}
protected string SendMail(string toList, string from, string ccList, string subject, string body)
{
MailMessage message = new MailMessage();
SmtpClient smtpClient = new SmtpClient();
string msg;
try
{
MailAddress fromAddress = new MailAddress(from);
message.From = fromAddress;
message.To.Add(toList);
if (!string.IsNullOrEmpty(ccList))
message.CC.Add(ccList);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
smtpClient.Host = "smtp.gmail.com";
smtpClient.Port = 587;
smtpClient.EnableSsl = true;
smtpClient.UseDefaultCredentials = true;
smtpClient.Credentials = new NetworkCredential("your_email@gmail.com", "password");
smtpClient.Send(message);
msg = "Successful";
Response.Write("<script>alert('" + msg + "')</script>");
}
catch (Exception ex)
{
msg = ex.Message;
Response.Write("<script>alert('" + msg + "')</script>");
}
return msg;
}
}
这是第2页的代码:
public partial class UserDeposit : System.Web.UI.Page
{
string _employeeName;
string _userName;
string _loginTime;
DateTime time;
protected void Page_Load(object sender, EventArgs e)
{
_employeeName = Request.QueryString["_employee"];
EmployeeName.Text = _employeeName;
_userName = Request.QueryString["_userName"];
UserName.Text = _userName;
_loginTime = Request.QueryString["_loginDatetime"];
time = DateTime.Parse(_loginTime);
}
protected void Button1_Click(object sender, EventArgs e)
{
//call here the "send mail" method??
}
}
答案 0 :(得分:2)
3:你没有在任何页面中使用send方法,而是把它放在一个单独的类中。
这是正确的编程实践。
答案 1 :(得分:1)
您需要执行以下任一方法之一:
创建一个基页类并继承所有基页类 适当的aspx页面。 (首选方法)
创建一个静态类并将它们放在那里。
答案 2 :(得分:0)
您可以像这样SendMail
方法static
:
public static string SendMail(string toList, string from, string ccList, string subject, string body)
现在你可以从任何地方调用它,只需在前面附加类名,如下所示:
UserLogin.SendMail(toList, from, ccList, subject, body);