ASP.NET WP – 添加电子邮件
ASP.NET WP – 添加电子邮件
在本章中,我们将介绍如何向网站添加电子邮件以及如何从网页发送电子邮件。您可能需要从您的网站发送电子邮件的原因有很多。
-
您可以向用户发送确认消息。
-
您也可以向自己发送通知。例如,当新用户在网站上注册时。
使用WebMail 助手发送电子邮件非常容易。要使用此 WebMail 助手,您必须能够访问 SMTP(SMTP 代表简单邮件传输协议)服务器。
-
SMTP 服务器是仅将消息转发到收件人服务器的电子邮件服务器。
-
如果您为您的网站使用托管服务提供商,那么他们将设置您的电子邮件,并且他们可以告诉您您的 SMTP 服务器名称是什么。
-
如果您在公司网络内工作,管理员或您的 IT 部门通常可以为您提供有关您可以使用的 SMTP 服务器的信息。
-
如果您在家工作,您甚至可以使用您的普通电子邮件提供商进行测试,他们可以告诉您他们的 SMTP 服务器的名称。
要使用 SMTP 服务器,您将需要以下内容;
-
SMTP 服务器的名称。
-
端口号多为 25。但是,您的 ISP 可能会要求您使用端口 587。
-
凭据,例如用户名、密码。
让我们看一个简单的例子,我们将在其中发送一封电子邮件。首先,我们需要创建一个新的 CSHTML 文件。
在名称字段中输入EmailRequest.cshtml并单击确定。
现在替换 EmailRequest.cshtml 文件中的以下代码。
<!DOCTYPE html> <html> <head> <title>Request for Assistance</title> </head> <body> <h2>Submit Email Request for Assistance</h2> <form method = "post" action = "ProcessRequest.cshtml"> <div> Your name: <input type = "text" name = "customerName" /> </div> <div> Your email address: <input type = "text" name = "customerEmail" /> </div> <div> Details about your problem: <br /> <textarea name = "customerRequest" cols = "45" rows = "4"></textarea> </div> <div> <input type = "submit" value = "Submit" /> </div> </form> </body> </html>
在上面的代码中可以看到,表单的 action 属性设置为ProcessRequest.cshtml,这意味着表单将提交到该页面。因此,让我们创建另一个 CSHTML 文件 ProcessRequest.cshtml 并替换以下代码。
@{ var customerName = Request["customerName"]; var customerEmail = Request["customerEmail"]; var customerRequest = Request["customerRequest"]; var errorMessage = ""; var debuggingFlag = false; try { // Initialize WebMail helper WebMail.SmtpServer = "smtp.mail.yahoo.com"; WebMail.SmtpPort = 465; WebMail.UserName = "[email protected]"; WebMail.Password = "**********"; WebMail.From = "[email protected]"; // Send email WebMail.Send(to: customerEmail, subject: "Help request from - " + customerName, body: customerRequest ); }catch (Exception ex ) { errorMessage = ex.Message; } } <!DOCTYPE html> <html> <head> <title>Request for Assistance</title> </head> <body> <p>Sorry to hear that you are having trouble, <b>@customerName</b>.</p> @if(errorMessage == ""){ <p>An email message has been sent to our customer service department regarding the following problem:</p> <p><b>@customerRequest</b></p> } else{ <p><b>The email was <em>not</em> sent.</b></p> <p>Please check that the code in the ProcessRequest page has correct settings for the SMTP server name, a user name, a password, and a "from" address.</p> if(debuggingFlag){ <p>The following error was reported:</p> <p><em>@errorMessage</em></p> } } </body> </html>
如果您使用 Yahoo 电子邮件提供商,则必须替换上述程序中的以下代码以使其运行。
// Initialize WebMail helper WebMail.SmtpServer = "smtp.mail.yahoo.com"; WebMail.SmtpPort = 465; WebMail.UserName = "[email protected]"; WebMail.Password = "**********"; WebMail.From = "[email protected]";
您需要在WebMail.Password属性中键入您自己的密码。
现在让我们运行应用程序并指定以下 URL – http://localhost:59795/EmailRequest,您将看到以下网页。
现在在所有提到的字段中输入一些信息,如下面的屏幕截图所示。
点击提交,邮件发送成功后,您将看到以下消息。