Digital Colony!

ASP.NET Email Using VB

This article is for ASP.NET 1.x. For a 2.0 snippet read Sending Email in ASP.NET 2.0 (VB.NET).

By now we all know how to send server-side email using classic ASP. We either use Microsoft's CDONTS technology or a third-party component such as ServerObjects's ASPMail or Persist's ASPEmail. With ASP.NET server-side email is built-in and can be accessed using the System.Web.Mail namespace. In this article, I will demonstrate how to generate an email with form validation.

The Example

A lot of people post their resume on their web site. The advantage of having a resume available for recruiters and potential employers on a web site is valuable. The downside is you don't know who is reading your resume. A simple way to resolve that is to set up a form where the user requests that the resume be emailed to them. Then you can blind carbon copy yourself and you'll know exactly who showed interest. No more guessing if an employer pulled your resume, you'll have a receipt.

The Form

Elements we will want to capture are name, email, company, and the format of the resume they wish to receive. All fields will be required to successfully submit the form. Let's code the form using ASP.NET Web Form controls and attach validation controls.
<div id="requestResume" runat="server"> 
<!-- The values on this FORM will be posted back to the server. --> 
<!-- We will add the 'runat="server"' to the FORM and controls --> 
<form id="Form1" method="post" runat="server"> 
<table> 
<tr><td>Name</td>
<td><input type="text" id="txtName" 
value="" size="30" maxlength="50" 
runat="server" name="txtName"/> 
<!-- txtName is required. We will attach a 
RequiredFieldValidator by assigning 
txtName as the ControlToValidate --> 
<asp:RequiredFieldValidator id="valRequiredName" 
runat="server"     
ControlToValidate="txtName"     
ErrorMessage="* You must enter your Full Name."
     Display="dynamic".>
</td></tr> 
<tr><td>Email</td>
<td> <input type="text" id="txtEmail" 
value="" size="30" maxlength="50" 
runat="server" NAME="txtEmail"/> 
<!-- txtEmail is both required and must be a valid email address. -->
<asp:RequiredFieldValidator id="valRequiredEmail" 
runat="server"     
ControlToValidate="txtEmail"     
ErrorMessage="* You must enter your Email address."     
Display="dynamic"/>
<!-- txtEmail will be validated using Regular Expression. 
It is also attached to txtEmail via the ControlToValidate property. --> 
<asp:RegularExpressionValidator id="valValidEmail" 
runat="server"     
ControlToValidate="txtEmail"     
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"     
ErrorMessage="* You must enter a valid Email address"     
Display="dynamic"/> 
</td></tr> 
<tr><td>Company</td>
<td> <!-- txtCompany works exactly like txtName. --> 
<input type="text" id="txtCompany" value="" size="30" 
maxlength="50" runat="server" 
NAME="txtCompany"/> 
<asp:RequiredFieldValidator id="valRequiredCompany" 
runat="server"     
ControlToValidate="txtCompany"     
ErrorMessage="* You must enter your Company name."     
Display="dynamic"/>
</td></tr> 
<tr><td>Resume Format</td>
<td> 
<!-- The dropdown list of resume formats 
will be assigned on the server --> 
<asp:DropDownList id="selResume" Runat="server"/>
</td></tr> 
<tr>
<td></td>
<td> 
<!-- When the FORM is submitted it will 
execute the "btnSubmit_OnClick" 
Subroutine on the server. --> 
<asp:button type="submit" name="btnSubmit" 
onclick="btnSubmit_OnClick" 
text="Request Resume" 
runat="server"/> </td></tr> 
</table> 
</form> 
</div>

Server-Side Code (VB.NET)

Regardless of what language you utilize, the above FORM will be coded the same way. To proceed on the server-side code, we need to pick a language. C# and Visual Basic are the two most popular at this time. Let's proceed in VB. The first line imports the ASP.NET code needed to perform sending email.
<%@ Import Namespace="System.Web.Mail" %> 
<script language="VB" runat="server">     
Sub Page_Load()         
'=== When the page first loads populate the Resume Format dropdown         
If NOT IsPostBack() Then            
   Call populateResumeFormats()            
   selResume.DataValueField = "Value"            
   selResume.DataTextField = "Key"            
   selResume.DataBind()         
End If     
End Sub     

Public Sub populateResumeFormats         
'=== create a HashTable to populate the dropdown.         
   Dim dropResume As New HashTable(4)         
   dropResume.Add("Word 97 (.RTF)", "resume.rtf")         
   dropResume.Add("HTML", "resume.htm")         
   dropResume.Add("Word 2002", "resume.doc")         
   dropResume.Add("Text", "resume.txt")         
   selResume.DataSource = dropResume     
End Sub     

Sub btnSubmit_OnClick(o as Object, e as EventArgs)         
'=== The Page.IsValid call checks all the validation controls. 
'=== If they all pass then the form is valid.         
If Page.IsValid Then             
'=== no longer display the FORM, display a status message. 
   requestResume.InnerHTML = "You will receive an email shortly with my resume.
 Thank you for your interest."             
   Call sendResume         
End If     
End Sub     

Sub sendResume        
'=== create a MailMessage         
  Dim resumeEmail as New MailMessage         
  Dim strResumeFilePath as String         
'=== To, CC, BCC, From, Subject are self-explainatory         
  resumeEmail.To = txtEmail.value
  resumeEmail.BCC = "larryking@cnn.com"         
  resumeEmail.From = "larryking@cnn.com"         
  resumeEmail.Subject = "Resume for Larry King"         
  resumeEmail.BodyFormat = MailFormat.text         
  resumeEmail.Body = txtName.value & ", attached is a copy of my resume. 
I look forward to working with you. - MAS "         
'=== for this example all versions of the resume reside in the 
/resume directory           
  strResumeFilePath = Server.MapPath("/") & "\resume\" & selResume.SelectedItem.value         
'=== create an attachment and add the file path to that attachment         
  Dim resumeAttachment as New MailAttachment(strResumeFilePath)            
  resumeEmail.Attachments.Add(resumeAttachment)         
'=== send the email         
  SmtpMail.Send(resumeEmail)     
End Sub </script>

Last Words

Pretty straightforward isn't it? Now you have a working resume mailer. The employer can specify the preferred format, and the potential employee gets to track who is viewing the resume.

This article was written in 2001 for ASP.NET 1.0. Forgive the non XHTML.

Labels: , ,

AddThis Social Bookmark Button

14 Comments:

Anonymous Anonymous said...

thanks so much. i was trying to figure out how to properly bind a hashtable all morning. couldn't find the code anywhere else. I didn't think to pass the dropdown value/text fields as actual strings and not hashtable.keys or hashtable.values. Duh!

6/08/2007 9:55 AM

Anonymous Anonymous said...

Is there a way to do something very similar to this but have a plain HTML form post to an asp.net page that will validate one field of the html form and then create an e-mail message and send it? I have to use an HTML page for the form because of our CMS system. Any comments are much appreciated. Thank you.

7/23/2007 2:43 PM

Blogger MAS said...

Yes you can. Think of how it was done in Classic ASP. Setup a page with Request.Form lines for each field. Perform validation. If validation fails, either Redirect user to original page or provide error message with a link to return to original form.

7/23/2007 2:52 PM

Anonymous Anonymous said...

Can I ask "how" to do the validation? I'm pretty new with asp.net and vb.net. I've figured out the code to make the e-mail and pull the fields but getting the validation to say if fieldx is equal to variable y then create e-mail and send, if not then response .redirect to notsent.html. Thank you for your responses and help.

7/23/2007 5:50 PM

Blogger MAS said...

It's been a while since I've coded VB.NET. Forgive the syntax.

string firstName
firstName = Request.QueryString("firstName").ToString();

if firstName == "John" Then
SendEmail
else
Response.Redirect "startOver.html"
end If

7/23/2007 6:01 PM

Blogger chinni said...

BY USING THIS CODE I WAS SUCCEDED IN LOCAL SERVER.BUT WHEN I AM TRYING TO UPLOAD MY PROJECT TO FTP SERVER IT CAUSING A ERROR

7/26/2007 3:26 AM

Blogger MAS said...

"Causing an Error" - can you be more specific?

7/26/2007 5:57 AM

Anonymous Todd said...

I know this is an older article but if you're still answering questions I have one.

Email seems so easy in .NET. In fact the too easy part is bothering me. I set the .UseDefaultCredentials = False and supplied my own 'bad' credentials and it's still sending emails. As long as I get the hostname of the SMTP Server correct the mail is sent. I'm setting the .Credentials = smtpUser so I don't know how on earth they're getting thru. Does it have something to do with having outlook open? I plan on deploying this in a more secure environment and I was hoping to trigger some credential issue while developing.

Any thoughts would be appreciated.

4/14/2008 8:36 PM

Blogger MAS said...

Todd -- I'm not an email expert, but I believe the protocol has always been too open. This is why SPAM continues to be a problem, whereas credit card transactions have been safe for years.

Back in the early 1990s, I "sent" emails from Elvis using my university's email system on Sun workstations and it let me.

4/15/2008 6:48 AM

Blogger SHIHAB said...

thank you very much, it is most helpful for me.

6/23/2008 11:47 PM

Blogger Navaneethakrishnan.T said...

Can you please tell me, how to find the forwarded and Spam/Junk emails which the mail is sent through our coding.

8/07/2008 11:45 AM

Blogger MAS said...

SPAM is marked by the recipient, not the sender. And every email recipient could have their own customer SPAM filters. Therefore, there is no way to detect SPAM from the sender perspective.

8/07/2008 11:55 AM

Blogger Navaneethakrishnan.T said...

Thanks for you reply, Can we track the Forwarded emails.?

8/07/2008 11:59 AM

Blogger MAS said...

Forward is also done on the client, so no.

If you wanted to track the number of times a message was read, you could embed an image in the message and then count the number of hits that image received on your web server. Some email clients won't display images, so the count will be lower than the actual read.

8/07/2008 12:02 PM

 

Post a Comment

 

Digital Colony Copyright © 1999-2008 XHTML   508
This site uses Blogger, which is not 100% XHTML compliant.
Try...Catch Disclaimer: For brevity many examples do not include error handling. That is your responsibility.