|
Because of the wide range of Base Classes available to
the ASP.NET Framework, a number of typical tasks that normally would take
the Classic ASP developer many lines of code now become very simple and
easy to implement.
One of these common tasks is sending email from the contents
of form fields, and validation of the entries both for required fields
and data type, such as a correctly formatted, valid email address. It's
very easy in .NET. However, virtually every example I have seen on the
web is either from BETA 1, or it assumes that your mail attachment
already resides on the server, which, obviously, is pretty useless
to most developers who are trying to provide an email utility page that
can be used by clients from their browser!
The class used to send SMTP email is MailMessage,
which is in the System.Web.Mail namespace (don't confuse this with
System.Web.Utils from Beta 1). We use the ASP.NET Validation Controls
to perform validation of various types on our formfields. What I'll do
here is provide an annotated ASPX page that accepts a mailserver, From
and To email addresses, a Subject and Message body, and an optional Attachment,
as well as providing the user the choice of sending Text or HTML mail
format. We'll also make each field - except the Attachment field - a required
field, and we will also perform basic email Regular Expression validation
on the From and To email fields. The SMTP Send function also has a simplified
overloaded method for "quickies" that looks like this:
public static void Send(string
from, string to, string subject, string messageText)
The method signature above will use the default SMTP service on the server
to send out mail. However, since we want to offer attachments, mail format
and custom mail server options, we'll be explicitly setting the properties
of our MailMessage instance, and calling its base Send() method instead.
Since this is server-side code, we need to upload the file to the server
before we attach it to the MailMessage object. So you'll see code here
that not only sends out an email message, but also uses the input type="file"
control along with the required form encoding - enctype="multipart/form-data"
which allows us to employ the attachment.PostedFile.SaveAs(sPathFile)
method of the formfield "attachment" member. Here is the code for the entire,
self-contained page:
<%@ Page Language="C#"
debug="true" %>
<%@ Import NameSpace="System.Web.Mail" %>
<script runat="server">
protected void Page_Load(Object Sender, EventArgs e) {
if(!Page.IsPostBack)
Info.Text = "Sending E-Mail using C# ";
}
protected void Send_Email(Object Sender, EventArgs e) {
string sPath = "";
string fileTitle ="";
MailMessage mail = new MailMessage();
mail.To = Request.Form["to"];
mail.From = Request.Form["from"];
if(Request.Form["format"].Equals("text"))
mail.BodyFormat = MailFormat.Text;
else
mail.BodyFormat = MailFormat.Html;
mail.Subject = Request.Form["subject"];
mail.Body = Request.Form["body"];
SmtpMail.SmtpServer = Request.Form["server"];
if(Request.Form["attachment"]!="")
sPath="d:\\temp\\";
fileTitle = attachment.PostedFile.FileName;
fileTitle = fileTitle.Substring(fileTitle.LastIndexOf("\\")
+ 1);
attachment.PostedFile.SaveAs(sPath+ fileTitle);
mail.Attachments.Add(new MailAttachment(sPath+fileTitle));
System.IO.File.Delete(sPath+ fileTitle);
try{ SmtpMail.Send(mail); }
catch(Exception MailEx){Info.Text+=MailEx.Message;}
finally{
Info.Text = "Info Sent...<br><br>" + "<a
href=\"sendMail.aspx\">Send Another?</a>";
}
}
</script>
<html>
<head>
<title>Sending E-Mail using C#</title>
<style>
a { font-size:11pt; font-family:Verdana; font-weight:normal; color:salmon;
}
</style>
</head>
<body bgcolor="white">
<basefont face=Verdana>
<p align="center" >
<asp:label id="Info" runat="server" />
</p>
<% if(!Page.IsPostBack) { %>
<p align="center">All fields required.</p>
<form method="post" runat="server" enctype="multipart/form-data"
>
<table width="60%" border="0" align="center"
cellpadding="2" cellspacing="2" bgcolor="#FFCC66">
<tr ><td width="20%" align="right">MailServer
:</td>
<td><input type="text" name="server" id="server"
runat="server">
<asp:RequiredFieldValidator id="serverRequired" runat="server"
ControlToValidate="server"
ErrorInfo="<small>Email server required.</small>"
Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr >
<td width="20%" align="right">From :</td>
<td><input type="text" name="from" id="from"
runat="server">
<asp:RegularExpressionValidator id="fromEmail" runat="server"
ControlToValidate="from"
ValidationExpression=".*@.*\..*"
ErrorInfo="<small>Invalid email address.</small>"
Display="Dynamic">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator id="fromRequired" runat="server"
ControlToValidate="from"
ErrorInfo="<small>From Email required.</small>"
Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">To : </td>
<td><input type="text" name="to" id="to"
runat="server">
<asp:RegularExpressionValidator id="toEmail" runat="server"
ControlToValidate="to"
ValidationExpression=".*@.*\..*"
ErrorInfo="<small>Invalid email address.</small>"
Display="Dynamic">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator id="toRequired" runat="server"
ControlToValidate="to"
ErrorInfo="<small>To email address required.</small>"
Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="right">Mail Format : </td>
<td>
<select name="format">
<option value="text">Text</option>
<option value="html">HTML</option>
</select>
</td>
</tr>
<tr>
<td align="right">Subject : </td>
<td><input type="text" name="subject" id="subject"
style="width:400;" runat="server">
<asp:RequiredFieldValidator id="subjectRequired" runat="server"
ControlToValidate="subject"
ErrorInfo="<small>Email subject required.</small>"
Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td valign="top" colspan="2" align="center">Body
: </td>
</tr>
<tr>
<td colspan="2" align="center"><textarea
cols="5" rows="10" name="body" id="body"
style="width:400;" runat="server">
</textarea>
<asp:RequiredFieldValidator id="bodyRequired" runat="server"
ControlToValidate="body"
ErrorInfo="<BR><small>Email Info required.</small>"
Display="Dynamic">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td valign="top" align="right">Attachment
: </td>
<td><input type="File" id="attachment"
name="attachment" runat="server"></td>
</tr>
<tr>
<td colspan="2" align="center">
<input type="submit" OnServerClick="Send_Email"
runat="server" value="Send Mail " />
</td>
</tr>
</table>
</form>
<% } %>
</body>
</html>
You can see I've added the required form fields to
retrieve the MAILSERVER, FROM email, TO email, SUBJECT, MESSAGE BODY,
and the field type FILE to accept a local file attachment. We provide
the user with the option to send HTML or plaintext body format. Each
of the important form fields is validated - both for being REQUIRED
as well as with a RegularExpressionValidator control to confirm that
the email address entered matches the RFC specification for an email
address. You can play around with these server validation controls on
your own machine - try leaving an email field blank, or entering a bad
email address like "george@whosy" and you'll see them in action.
Note that we have a form on our page which uses the
"enctype="multipart/form-data" to get the attachment
from the input type="FILE" control into standard MIME multipart
mail format for the upload. We have formfield validator controls for
both required fields and for correct email addresses. If the page is
Postback (i.e., it's been submitted to the server), then we do our processing
- we set up our Mail class, check for the attachment, Save it to the
filesystem first with attachment.PostedFile.SaveAs(sPath+
fileTitle); and finally we add the attachment off the
filesystem to our server - side Mail attachment collection. Finally,
we delete the attachment, which is no longer needed, from the filesystem
and send out our mail. Be aware that you need to have the SMTP service
configured and turned on for all this to work. You should be able to
copy all the code above, and save it as SendMail.aspx, and have it work.
Enjoy.
Peter Bromberg is an independent consultant specializing in distributed .NET solutionsa Senior Programmer
/Analyst at in Orlando and a co-developer of the NullSkull.com
developer website. He can be reached at info@eggheadcafe.com
|