Handling E-mail with HTML, CDO, and SMTP, Part Two

Handling E-mail with HTML, CDO, and SMTP, Part Two

n part one, I showed you how to create a basic SMTP e-mail system on an intranet.  In this portion, you will use Active Server Pages code to read the mail from the mailbox and put all the relevant fields into an Access database. If you haven’t already done so, you should read part one. This article picks up where the previous one left off, so you’ll need the code, server configuration, and mail message described in that article to successfully follow part two.

Create a Database in Access 97
Later in the article, you’ll need an Access 97 database that has been configured tostore the e-mail messages. You can download mine, or create your own right now. To create your own, make sure you have the latest Data Access Components installed (MDAC 1.5c or 2.0). Open Access 97 and from the File menu, click New. Then click Blank Database and click OK. In the File New Database dialog box, save the database as smtpdb.mdb. Next, click the Tables tab and then click New. In the New Table dialog box, click Design View and then click OK. Finally, add these fields:

Field Name           Data Type          
ID AutoNumber
From Text
Email Text
Subject Text
MessageText Memo
DateTime Date/Time

From the File menu, click Save and save the table as maillist. When asked to create a Primary Key, click Yes. Then exit Access, saving any changes.

Build the Web Project
Now that you have a database in which to store the e-mail messages, you need to move into your development environment to create the code. I wrote these instructions using the Release Candidate 1 version of Visual InterDev 6. The precise steps may vary in the final release version and certainly have changed from VID 1.0. First, run Visual InterDev 6 and from the File menu, click New Project. In the New Project dialog box, click the New tab and click New Web Project. In the Name box, type smtp and click Open. In the Web Project Wizard?s Step 1 of 4, type the name of the Web server and click Next. After VID contacts the server, in Step 2 of 4, type smtp in the Name box and then click Next. We?ll leave the design work till later. Click Finish. VID goes to work setting up the project files.

Construct the Web Page
With the environment in place, you can create the main Web page and add code to view the e-mail information. From the Project menu, click Add Web Item>Active Server Page and click ASP Page. In the Name field, type smtp.asp and click Open (see Figure 1). Click on the Source tab of the smtp.asp window. You may have to rearrange and resize some windows to get a good view. After the BODY tag, add this code (if you’re copying and pasting, depending on your source, you may need to Paste as HTML):

<%  Set objSession = server.CreateObject("CDONTS.Session")  objSession.LogonSMTP "Service", "[email protected]"  set objFolder= objSession.inbox  set objMessages = objFolder.messages  response.write "Version=" & objSession.version & "
" response.write "Name=" & objFolder.name & "
" response.write "Class=" & objFolder.class & "
" response.write "Application=" & objFolder.application & "
" response.write "Parent=" & objFolder.parent & "
" response.write "Session=" & objFolder.session & "
" response.write "Number of messages=" & objMessages.count & "
" %>

After saving your changes, open the smtp.asp page in the Web browser. You?ll see the information that is available via the Collaboration Data Objects for NT Server (CDONTS). In this case it shows that there is one e-mail message (see Figure 2).

The previous code shows the extent to which you are dealing with parent objects, child objects, and collections in CDONTS.   An inbox contains folders, and messages reside inside the folder. You’ll notice that the next snippet contains a collection of messages, and within it, a collection of recipients. You use  foreach to loop through and retrieve whatever is available in the collections.

View the Message Contents
Now that you know you can see into the directory where the e-mail is stored(c:InetpubMailrootpassable.com), you can start looking at the actual message contents.You create an HTML table, including the headers and then loop through the messages. As you work through the loop, you parse the message to get the various items?the sender’s name, the subject, e-mail address, message text, and more.

In smtp.asp, add this code below the previous code:

  <%  for i = 1 to objMessages.count  response.write ""  response.write ""  response.write ""  Set objAddrEntry = objMessages.item(i).Sender   response.write ""  response.write ""  response.write ""  response.write ""  response.write ""  response.write ""  set recip = objMessages.item(i).recipients  response.write ""  next  %>  
Sender Subject Address Text Received Sent Imp. Size Recipients
" & objMessages.item(i).sender & "" & objMessages.item(i).subject & "" & objAddrEntry.Address & "" & objMessages.item(i).text & "" & objMessages.item(i).timereceived & "" & objMessages.item(i).timesent & "" & objMessages.item(i).importance & "" & objMessages.item(i).size & "" for each person in recip response.write person & "
" next response.write "

View the page again in your browser. This time, you see the contents of the message and some of the other key information about the message such as the time the message was received (see Figure 3).

Having shown that you have access to the e-mail message, you can now take the data from the message and insert it into the Access database.

Insert the E-Mail Into the Database
Although you created the Access database earlier, you still need to configure it so you can write your e-mail message(s) in it. In Visual InterDev, create the database connection. In Windows Explorer, drag the Access database, smtpdb.mdb and drop it in the Visual InterDev Project Explorer. Edit your global.asa file to point the Web server to the database file on the server. For instance:

connstr="DBQ=c:inetpubWWWROOTsmtpsmtpdb.mdb;"    connstr=connstr & "DefaultDir=c:inetpubWWWROOTsmtp;"    connstr=connstr & "Driver={Microsoft Access Driver (*.mdb)};"    connstr=connstr & "FIL=MS Access;"    connstr=connstr & "ImplicitCommitSync=Yes;"    connstr=connstr & "MaxBufferSize=512;"    connstr=connstr & "MaxScanRows=8;"    connstr=connstr & "PageTimeout=5;"    connstr=connstr & "SafeTransactions=0;"    connstr=connstr & "Threads=3;"    connstr=connstr & "UID=admin;"    connstr=connstr & "UserCommitSync=Yes;"    Session("DataConn_ConnectionString") = connstr    Session("DataConn_ConnectionTimeout") = 15    Session("DataConn_CommandTimeout") = 30    Session("DataConn_RuntimeUserName") = "admin"    Session("DataConn_RuntimePassword") = ""

Still in Visual InterDev, open smtp.asp and add this code, which writes the information from the e-mail file into a new database record.

<%  Set OBJdbConnection = Server.CreateObject("ADODB.Connection")   OBJdbConnection.Open Session("DataConn_ConnectionString")  Set smtpdb = Server.CreateObject("ADODB.Recordset")  smtpdb.ActiveConnection = OBJdbConnection  smtpdb.CursorType = 1 ' adOpenKeyset  smtpdb.LockType = 3 ' adLockOptimistic  smtpdb.Source = "maillist"  smtpdb.Open  for i = 1 to objMessages.count  smtpdb.AddNew  smtpdb("From") = trim(objMessages.item(i).sender)  smtpdb("Subject") = trim(objMessages.item(i).subject)  smtpdb("MessageText") = trim(objMessages.item(i).text)  smtpdb("Email") = trim(objAddrEntry.Address)   smtpdb("DateTime") = objMessages.item(i).timesent  smtpdb.Update   smtpdb.MoveFirst  ' objMessages.item(i) ' Uncomment to delete the message  next  %>

Run smtp.asp again. Unless there’s an error, the results on screen may not look anydifferent from the previous run. However, when you open the Access database, you?llsee that a record has been inserted (see Figure 4).

Notice that I’ve commented out objMessages.item(i) from the previous code snippet. That’s to avoid deleting messages during testing.  To avoid duplicate items in the database, you need to uncomment the line. Of course, in a serious production environment you would probably want to test for a successful insertion or copy the mail message to another directory as a backup.

Clean Up the Code
You complete the script by logging off your e-mail access session and then setting the objects to Nothing.

<%  objSession.Logoff  Set OBJdbConnection=Nothing  Set smtpdb =Nothing  Set objSession=Nothing  Set objFolder= Nothing  Set objAddrEntry = Nothing  %>

In these two articles, you’ve seen that you can use HTML, Active Server Pages, and CDONTS to send e-mail messages to the SMTP server. You can selectively retrieve messages from a mail folder, display the contents on a Web page and store each message as a record in a database. From here, you could generate mail lists, sort and analyze the e-mail or automatically post  messages directly on a Web page. You could even use a component such as AspHTTP to turn the e-mail message into a CGI form and submit the contents to yet another application across the Web.

Click here for the full source code and Access database used in this article.

devx-admin

devx-admin

Share the Post:
Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India,

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with

Software Development

Top Software Development Companies

Looking for the best in software development? Our list of Top Software Development Companies is your gateway to finding the right tech partner. Dive in and explore the leaders in

India Web Development

Top Web Development Companies in India

In the digital race, the right web development partner is your winning edge. Dive into our curated list of top web development companies in India, and kickstart your journey to

USA Web Development

Top Web Development Companies in USA

Looking for the best web development companies in the USA? We’ve got you covered! Check out our top 10 picks to find the right partner for your online project. Your

Clean Energy Adoption

Inside Michigan’s Clean Energy Revolution

Democratic state legislators in Michigan continue to discuss and debate clean energy legislation in the hopes of establishing a comprehensive clean energy strategy for the state. A Senate committee meeting

Chips Act Revolution

European Chips Act: What is it?

In response to the intensifying worldwide technology competition, Europe has unveiled the long-awaited European Chips Act. This daring legislative proposal aims to fortify Europe’s semiconductor supply chain and enhance its

Revolutionized Low-Code

You Should Use Low-Code Platforms for Apps

As the demand for rapid software development increases, low-code platforms have emerged as a popular choice among developers for their ability to build applications with minimal coding. These platforms not

Cybersecurity Strategy

Five Powerful Strategies to Bolster Your Cybersecurity

In today’s increasingly digital landscape, businesses of all sizes must prioritize cyber security measures to defend against potential dangers. Cyber security professionals suggest five simple technological strategies to help companies

Global Layoffs

Tech Layoffs Are Getting Worse Globally

Since the start of 2023, the global technology sector has experienced a significant rise in layoffs, with over 236,000 workers being let go by 1,019 tech firms, as per data

Huawei Electric Dazzle

Huawei Dazzles with Electric Vehicles and Wireless Earbuds

During a prominent unveiling event, Huawei, the Chinese telecommunications powerhouse, kept quiet about its enigmatic new 5G phone and alleged cutting-edge chip development. Instead, Huawei astounded the audience by presenting

Cybersecurity Banking Revolution

Digital Banking Needs Cybersecurity

The banking, financial, and insurance (BFSI) sectors are pioneers in digital transformation, using web applications and application programming interfaces (APIs) to provide seamless services to customers around the world. Rising

FinTech Leadership

Terry Clune’s Fintech Empire

Over the past 30 years, Terry Clune has built a remarkable business empire, with CluneTech at the helm. The CEO and Founder has successfully created eight fintech firms, attracting renowned

The Role Of AI Within A Web Design Agency?

In the digital age, the role of Artificial Intelligence (AI) in web design is rapidly evolving, transitioning from a futuristic concept to practical tools used in design, coding, content writing

Generative AI Revolution

Is Generative AI the Next Internet?

The increasing demand for Generative AI models has led to a surge in its adoption across diverse sectors, with healthcare, automotive, and financial services being among the top beneficiaries. These

Microsoft Laptop

The New Surface Laptop Studio 2 Is Nuts

The Surface Laptop Studio 2 is a dynamic and robust all-in-one laptop designed for creators and professionals alike. It features a 14.4″ touchscreen and a cutting-edge design that is over

5G Innovations

GPU-Accelerated 5G in Japan

NTT DOCOMO, a global telecommunications giant, is set to break new ground in the industry as it prepares to launch a GPU-accelerated 5G network in Japan. This innovative approach will

AI Ethics

AI Journalism: Balancing Integrity and Innovation

An op-ed, produced using Microsoft’s Bing Chat AI software, recently appeared in the St. Louis Post-Dispatch, discussing the potential concerns surrounding the employment of artificial intelligence (AI) in journalism. These

Savings Extravaganza

Big Deal Days Extravaganza

The highly awaited Big Deal Days event for October 2023 is nearly here, scheduled for the 10th and 11th. Similar to the previous year, this autumn sale has already created

Cisco Splunk Deal

Cisco Splunk Deal Sparks Tech Acquisition Frenzy

Cisco’s recent massive purchase of Splunk, an AI-powered cybersecurity firm, for $28 billion signals a potential boost in tech deals after a year of subdued mergers and acquisitions in the

Iran Drone Expansion

Iran’s Jet-Propelled Drone Reshapes Power Balance

Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

Solar Geoengineering

Did the Overshoot Commission Shoot Down Geoengineering?

The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

Remote Learning

Revolutionizing Remote Learning for Success

School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

Revolutionary SABERS Transforming

SABERS Batteries Transforming Industries

Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

Build a Website

How Much Does It Cost to Build a Website?

Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

Battery Investments

Battery Startups Attract Billion-Dollar Investments

In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1