ASP.NET Web Pages - WebMail Helper


WebMail Helper - One of the many useful ASP.NET Web helpers.


WebMail Helper

The WebMail Helper makes it easier to send emails, sending emails from a web application according to SMTP (Simple Mail Transfer Protocol).


Prerequisite: Email Support

To demonstrate how to use email, we will create an input page that lets users submit a page to another page and send an email about support issues.


First: Edit Your AppStart Page

If you have created the Demo application in this tutorial, you already have a page named _AppStart.cshtml with the following content:

_AppStart.cshtml

@{
WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId", "Email", true);
}

To start the WebMail Helper, add the WebMail properties shown below to your AppStart page:

_AppStart.cshtml

@{
WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId", "Email", true);
WebMail.SmtpServer = "smtp.example.com";
WebMail.SmtpPort = 25;
WebMail.EnableSsl = false;
WebMail.UserName = "[email protected]";
WebMail.Password = "password-goes-here";
WebMail.From = "[email protected]";

}

Property explanations:

SmtpServer:The name of the SMTP server used to send email.

SmtpPort:The port the server uses to send SMTP transactions (email).

EnableSsl:If the server uses SSL (Secure Socket Layer) encryption, the value is true.

UserName:The name of the SMTP email account used to send email.

Password:The password for the SMTP email account.

From:The email displayed in the sender address field (usually the same as UserName).


Second: Create an Email Input Page

Next, create an input page and name it Email_Input:

Email_Input.cshtml

<!DOCTYPE html>
<html>
<body>
<h1>Request for Assistance</h1>

<form method="post" action="EmailSend.cshtml">
<label>Username:</label>
<input type="text name="customerEmail" />
<label>Details about the problem:</label>
<textarea name="customerRequest" cols="45" rows="4"></textarea>
<p><input type="submit" value="Submit" /></p>
</form>

</body>
</html>

The purpose of the input page is to collect information, then submit the data to a new page that can send the information as an email.


Third: Create an Email Sending Page

Next, create a page for sending email and name it Email_Send:

Email_Send.cshtml

@{ // Read input
var customerEmail = Request["customerEmail"];
var customerRequest = Request["customerRequest"];
try
{
// Send email
WebMail.Send(to:"[email protected]", subject: "Help request from - " + customerEmail, body: customerRequest );
}
catch (Exception ex )
{
<text>@ex</text>
}
}

For more information about sending email in ASP.NET Web Pages applications, please check:WebMail Object Reference Manual。


Other Extensions