Digital Colony!

Sending Email in ASP.NET Using SMTP Authentication (VB.NET)

If you don't need to use Authentication to send email, check out the code snippet Sending Email in ASP.NET 2.0 (VB.NET). If your web host requires that you use SMTP Authentication, some additional lines of code will need to be added.
Dim Message As MailMessage = New MailMessage()
Dim Smtp As New SmtpClient()
Dim SmtpUser As New System.Net.NetworkCredential()
'-- Build Message
Message.From = New MailAddress("larryking@cnn.com", "Larry King")
Message.To.Add(New MailAddress("oprah@oprah.com", "Oprah"))
Message.IsBodyHtml = False
Message.Subject = "Come on My Show Soon"
Message.Body = "Please be a guest on my show. - Larry"
'-- Define Authenticated User
SmtpUser.UserName = "larryking"
SmtpUser.Password = "suspenders"
SmtpUser.Domain = "mail.cnn.com"
'-- Send Message
Smtp.UseDefaultCredentials = False
Smtp.Credentials = SmtpUser
Smtp.Host = "mail.cnn.com"
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network
Smtp.Send(Message)

Labels: ,

 

Sending Email in ASP.NET 2.0 (VB.NET)

Way back in 2001, I wrote ASP.NET Email Using VB for ASP.NET 1.x. ASP.NET 2.0 now uses the System.Net.Mail instead of the System.Web.Mail Namespace.

Here is a quick snippet to get you started.
Dim Message As MailMessage = New MailMessage()
Dim Smtp As New SmtpClient()
'-- Build Message
Message.From = New MailAddress("larryking@cnn.com", "Larry King")
Message.To.Add(New MailAddress("oprah@oprah.com", "Oprah"))
Message.IsBodyHtml = False
Message.Subject = "Come on My Show Soon"
Message.Body = "Please be a guest on my show. - Larry"
'-- Send Message
'-- each web host is different 
'-- (adjust next 2 lines accordingly)
Smtp.Host = "localhost"
Smtp.DeliveryMethod = SmtpDeliveryMethod.Network
Smtp.Send(Message)
If your web host requires that you send the email using SMTP Authentication read Sending Email in ASP.NET Using SMTP Authentication (VB.NET).

Labels: , ,

 

IsNull in VB.NET

IsNull is not supported in VB.NET. Classic ASP users that used IsNull in VBScript should now use IsNothing.
If Not Request.Form("LastName") Is Nothing Then
   '-- Do something!
End If

Labels:

 

My First ADO.NET Table

This article was written in 2002 and is based upon ASP.NET 1.0.

The most common data centric task an ASP developer can do is create an HTML table from an SQL query. Below is an example of how to do this with ASP.NET. I'll be connecting to a SQL Server database, but with some slight modifications this code will work for an OLE-DB provider or OLE-ODBC driver. The 3 objects used in this example are SQLConnection, SQLCommand and the SQLDataReader.

Namespace

In order to access data objects a few namespaces are required. The first is System.Data. It contains the basic ADO.NET objects. The second namespace will depend upon your data source. If it is SQL Server then you will use the System.Data.SQLClient namespace. If it isn't then use System.Data.OleDb.
<%@Page Language="VB" %> 
<%@Import Namespace="System.Data" %> 
<%@Import Namespace="System.Data.SqlClient" %>

Connection

For SQL Server the object used to connect to the data source is SQLConnection. Ole-DB requires the OleDbConnection. Like the ADOB.Connection object in classic ADO, this also requires a connection string.
'-- SQL Server Example 
Dim strConnect As String 
strConnect = "server=localhost;database=elvis;uid=king;pwd=tcb;" 
Dim objConnection As New SQLConnection(strConnect) 
objConnection.Open 

Command

Now that I've connected to the data source, we will want to execute an SQL query against it. In this example I want a list of all Elvis movies. The SQLCommand object allows us to execute our SQL statement against the data source. Ole-DB users will use the OleDBCommand object.
Dim strSQL As String 
strSQL = "SELECT filmName, yearReleased FROM TCBFilms" 
Dim objCommand as New SQLCommand(strSQL,objConnection)

DataReader

The DataReader object is way to access the returned data quickly. It is similar to ADO's Recordset object. In the this example, I'll connect the DataReader to an asp:datagrid servers-side control. This will create an HTML table with column headers. No more iterating through the Recordset row-by-row writing HTML to the screen for each row. Ole-DB should use the OleDBDataReader object.
Dim objDataReader as SQLDataReader 
objDataReader = objCommand.ExecuteReader() 
myDataGrid.DataSource = objDataReader 
myDataGrid.DataBind() 
objConnection.Close()
<asp:datagrid id="myDataGrid" runat="server" />

Last Words

This is the just a basic example of using ADO.NET objects to create a database driven HTML table with ASP.NET. ADO.NET has many more powerful features including handling disconnected data and working with XML.

Labels: , , ,

 

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: , ,

 

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.