Classic ASP Active Server Pages Examples, code, tutorials, scriptsClassic ASP Script to Archive or Save Emails to Database and Attached Files to Folder

Here is my Classic ASP script for archiving emails into a database. There is nothing original in it--I pieced it together by following the manual on and other examples. It is set up for use with MySQL so if you're using a different database, you'll need to change the database connection. Also note that the field data is prepared for MySQL and that may need to be changed if using a different database. This script requires the professional version of Jmail component by Dimac - if your host does not have it, they might install it for you. It also uses Persits ASPJpeg to get image file dimensions. You may want to add a filter to save emails only from whitelisted email addresses. I chose not to have the script delete emails from the mail server, but to be safe, test before actual use. The way it is designed to work is to see if the message id number is already in the database and if not, then to process the email.

If you find this script to be useful, please rate:
Codango PHP, ASP .NET, JSP Scripts, Resources, Reviews
Click to Read Reviews
What do you think?
For MySQL Database Tables:
-- Table structure for table `archivedemails`

CREATE TABLE IF NOT EXISTS `archivedemails` (
`MailDate` varchar(100) NOT NULL,
`FromName` varchar(255) NOT NULL,
`FromAddress` varchar(2552) NOT NULL,
`ToAddress` varchar(255) NOT NULL,
`Subject` varchar(255) NOT NULL,
`MsgBody` text NOT NULL,
`msgBodyB` text NOT NULL,
`msgBodyC` text NOT NULL,
`msgBodyD` text NOT NULL,
`msgBodyE` text NOT NULL,
`FileName` varchar(255) NOT NULL,
`FileType` varchar(255) NOT NULL,
`MsgUID` int(11) NOT NULL,

-- Table structure for table `emailfiles`

`Fmsg` int(11) NOT NULL,
`Fname` varchar(255) CHARACTER SET utf8 NOT NULL,
`Fext` varchar(30) CHARACTER SET utf8 NOT NULL,
`Fsize` int(11) NOT NULL DEFAULT '0',
`Fwidth` int(11) NOT NULL DEFAULT '0',
`Fheight` int(11) NOT NULL,
`FileDel` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT 'OK',

The Script:

<%@LANGUAGE = VBScript%>

Archive Emails In Database<br />

strconnect = "Driver={MySQL ODBC 5.1 Driver};Server=DATABASEHOST;uid=USERID;pwd=PASSWORD;database=DATABASENAME;"

on error resume next

dim adoConn
dim adoRS
dim counter

set adoConn = Server.CreateObject("ADODB.Connection")
adoConn.Open strconnect

if adoConn.errors.count = 0 then


Dim webmail
Set webmail = Server.CreateObject("JMail.POP3")

Function getAttachments()
Set Attachments = msg.Attachments
For mm = 0 To Attachments.Count - 1

Set at = Attachments(mm)
response.write at.Name & MsgUID

dim fs
dim strMyFilePath, strTempFolder
strMyFilePath ="C:\YOURPATH\wwwroot\files\"  'permanent file path
strTempFolder ="C:\YOURPATH\wwwroot\files\temp\" 'temporary file path
'check if attached file already exists in folder
set fs=Server.CreateObject("Scripting.FileSystemObject")
if fs.FileExists(strMyFilePath&at.Name)=true then 'folder for attached files
'response.write("File exists!")

newFname = Replace(at.Name, StripFileExt(at.Name), "")
'new file name:
prepFname=newFname & Month(now())&"_"&Day(now())&"_"&Year(now())&"_"&Minute(now())&"_"&Second(now())& StripFileExt(at.Name)
at.SaveToFile(strTempFolder & at.Name ) 'path to temp folder for new files
'move renamed file to permanent folder
fs.MoveFile strTempFolder& at.Name,strMyFilePath&prepFname


'response.write("File does not exist!")
end if
set fs=nothing
if FileDel="" then
end if
filesSQL ="INSERT INTO emailfiles (`Fmsg`, `Fname`, `Fsize`, `Fext`,`FileDel`) VALUES ('"&MsgUID&"', '"&FileName&"','"&FileSize&"','"&FileExt&"','"&FileDel&"')"
response.write filesSQL

getAttachments = getAttachments & "<a href=""/attachments/" &_
at.Name &""">" & at.Name & "(" & at.Size & " bytes)" &_
"</a>" & separator
End Function

'this function by Lewis Moten
Function StripFileExt(sFileName)' works for both 3 letter and 4 letter file extensions
If sFileName = "" Then
end if 'Exit Function
If InStr(1, sFileName, ".") = 0 Then Exit Function
StripFileExt = Right(sFileName, Len(sFileName) - InStrRev(sFileName, ".") + 1)
End Function


<p>There are <%=webmail.Count%> messages!</p>

If webmail.Count > 0 Then
With Response
Dim i
For i = 1 To webmail.Count

Response.Write "<BR><br>"
Response.Write( webmail.GetMessageUID (i))&"<BR><br>"
MsgUID=( webmail.GetMessageUID (i))

''''Let's see if this message is already in db. If so, we won't process it and its files.

chkSQL = "SELECT * FROM archivedemails where MsgUID="&MsgUID&""

SET chkRS = Server.CreateObject("ADODB.Recordset") chkSQL, adoConn

if Not chkRS.EOF then
'FID = chkRS("FID")

Response.Write "<BR>This message "&MsgUID &" is already in the database.<br>"

response.write "<BR>This message "&MsgUID &" being inserted into db now.<br>"

'Response.Write( webmail.Messages(i).Headers.Text )
.Write "From " & webmail.Messages(i).From
.Write "<br>"
.Write "Date " & webmail.Messages(i).Date

.Write "<br>"
.Write "Size " & webmail.Messages(i).Size
.Write "<br>"
.Write "Subject " & webmail.Messages(i).Subject
Subject = Replace(Subject, chr(34), "&quot;")
Subject = Replace(Subject, "'", "&#39;")

'.Write "<pre>" & webmail.Messages(i).Body &"</pre>"
.Write(webmail.Messages(i).ContentType )
MsgBody = Replace(MsgBody, chr(34), "&quot;")
MsgBody = Replace(MsgBody, "'", "&#39;")

'decodeResults = Message.PGPDecode( true, true );
.Write "<br><br>"

Set msg = webmail.Messages(i)

'''check image files dimensions

SET objResult = Server.CreateObject("ADODB.Recordset") strSQL, adoConn

While Not objResult.EOF
FID = objResult("FID")
Fmsg = objResult("Fmsg")
Fname = objResult("Fname")
Fsize = objResult("Fsize")
Fext = objResult("Fext")
Fwidth = objResult("Fwidth")
Fheight = objResult("Fheight")
FileDel = objResult("FileDel")

'Response.Write "<BR>"&FID&" "&Fmsg&" "&Fname&" "&Fext&" "&Fsize&" "&Fwidth&" "&Fheight&" "&FileDel&""

'test file extension
imgChk = "N"
Dim sMyArray(14) 'what we name our array and how many items in it
sMyArray(0) = ".jpg"
sMyArray(1) = ".gif"
sMyArray(2) = ".jpeg"
sMyArray(3) = ".bmp"
sMyArray(4) = ".png"
sMyArray(5) = ".jpeg"
sMyArray(6) = ".doc"
sMyArray(7) = ".txt"
sMyArray(8) = ".pdf"
sMyArray(9) = ".xls"
sMyArray(10) = ".xlsx"
sMyArray(11) = ".docx"
sMyArray(12) = ".rtf"
sMyArray(13) = ".htm"
sMyArray(14) = ".html"

For Each x In sMyArray
'now we need to set up a Case with with to compare our querystring to the items in the array
Select Case MatchExt 'give your case a name for identification purposes
Case Yes
if x = lcase(Fext) then
Cal = 1
end if
End select
'end test file extension

'check if image file
Dim imgArray(5)
imgArray(0) = ".jpg"
imgArray(1) = ".gif"
imgArray(2) = ".jpeg"
imgArray(3) = ".bmp"
imgArray(4) = ".png"
imgArray(5) = ".jpeg"

For Each n In imgArray
'now we need to set up a Case to compare our string to the items in the array
Select Case MatchArray
Case Y
if n = lcase(Fext) then
imgChk = "Y"
end if
End select
'end check if image file

'response.write Cal & imgChk
if NOT Cal=1 then
response.write " File deleted "
''delete disallowed file
response.write "- Disallowed file name."
if fs.FileExists(strMyFilePath&Fname) then
FileDel="deleted "
response.write "<br>DELETED"&strMyFilePath&Fname &"<br>"
end if
''update file record in db
delSQL ="UPDATE emailfiles SET `FileDel` ='deleted' WHERE Fmsg = '"&MsgUID&"' AND Fname ='"&Fname&"'"
'response.write "<BR>"&delSQL&"<BR>"

end if

if imgChk="Y" then
'response.write " Image "
' Create instance of AspJpeg
Set Jpeg = Server.CreateObject("Persits.Jpeg")
' Open source image
Jpeg.Open strMyFilePath&Fname
''update record in db with image width and height
fdtSQL ="UPDATE emailfiles SET `Fwidth` ='"&FileW&"',`Fheight`='"&FileH&"' WHERE Fmsg = '"&MsgUID&"' AND Fname ='"&Fname&"'"
'response.write "<BR>"&fdtSQL&"<BR>"

end if

response.write "<br />"


set objResult=nothing

ReTo = ""
ReCC = ""

Set Recipients = msg.Recipients
separator = ", "

' We now need to get all the recipients,
' both normal and Carbon Copy (CC) recipients
' and store them in a variable

For n = 0 To Recipients.Count - 1
If n = Recipients.Count - 1 Then
separator = ""
End If

Set re = Recipients.item(n)
If re.ReType = 0 Then
ReTo = ReTo & re.Name & "&nbsp;(" & re.EMail & ")" & separator
ReCC = ReTo & re.Name & "&nbsp;(" & re.EMail & ")" & separator
End If

SQL = "INSERT INTO archivedemails (`MsgUID`, `MailDate`,`FromAddress`,`Subject`,`MsgBody`) VALUES ('"&MsgUID&"', '"&MailDate&"','"&FromAddress&"','"&Subject&"','"&MsgBody&"')"
' response.write "<br>"&SQL&"<br>"
'SELECT `MsgUID`, `MailDate`,FromName`,`FromAddress`,`Subject`,`MsgBody` FROM `archivedemails`
'SELECT * FROM `archivedfiles` WHERE 1`MsgUID`, `FileName`, `FileExt`, `FileSize`, `FileW`, `FileH`

end if
set chkRS=nothing

End With
End If

Set webmail = Nothing

response.write "ERROR: Couldn't connect to database"
end if

'set objResult=nothing
set adoConn=nothing



ASP Examples Menu of Active Server Pages scripts code Classic ASP

Classic ASP Active Server Pages Examples, code, tutorials, scriptsASP Examples Menu (below*)

Active Server Pages | ASP | Scripts | Tutorials | Code | Web Programming | Examples
Active Server Pages ASP code examples, tutorials, and snippets for use in Programming interactive websites.

If you find omissions or errors let me know. I have moved these code samples to their own domain; if you find pieces missing, please let me know.
My favorite scripts site is CODANGO.


If any the information I've posted here has been useful to you, please donate.

Quick 'n  easy  dirty PHP script code wizard-generator

Zenphoto RSS XML feed used as data source for javascript slide show with PHP

Classic ASP to archive emails into database and save attached files to folder

PHP Image GD for thumbnails and image resizing with pathing for Windows servers

ODBC database connections for Microsoft Access MDB files with Windows 7: solution posted on this forum.

HTML5 embedded video player "Projekktor" completely skinnable with hyperlinked watermark

Edit web.config to allow Windows iis7 server to handle mp4 files or other mime types as needed

URL rewrite or make friendly URLs for iis7 Windows Server 2008 by editing your web.config file


Use PHP to zip folders for backing up a website

Use PHP to archive emails in database and save attached files to folder

Use PHP with json to check how many hits left on Twitter API

PHP get single record from Access database without catchable fatal error message

PHP to make a bot to send automatic Twitter status updates with Abraham Williams' PHP Oauth Twitter Library

A way to use the PHP Oauth Twitter Library with your Classic ASP scripts for sending status updates

Get user's IP address location for your form results

Tutorial for registering an application with Twitter

Update your Twitter status with Classic ASP and Oauth seamlessly and invisibly without having to login to Twitter. Send status updates programmatically from a web page. PHP example too.

CLASSIC ASP: Cache your Twitter tweets in a database to keep your Twitter xml requests within the rate limit of 350 per hour / PHP VERSION

PHP: Use json to fetch Twitter followers' profiles

Index files content and insert into database for faster searches

Classic ASP with Ajax: secure URL check

Classic ASP with Ajax: referer check

Classic ASP with Ajax: a solution to the ampersand problem in querystrings

Very Simple Star Rating System for Classic ASP

Star Rating System uses CSS and JS adapated for Classic ASP from Yvo Schaap PHP script

XMLhttp with ASP to fetch and save photos from Photobucket account through RSS XML. Can be adapted for Youtube videos to import data to database.

NET image resize can be used to make thumbnails for Classic ASP

Track site visitors, get their ip address geographical data, count page views with Classic ASP

Javascript slideshow with Classic ASP to load image details dynamically from database photos table

Classic ASP with Ajax for rotating banners without page refresh and XML file converted to recordset as banner database
--Variation of the above but fetching a REMOTE XML file as the database
--Variation checks for secure URL and builds absolute URL and makes offsite banner links open in new window

True inline edit Classic ASP datagrid table database edit updating with Ajax SIMPLE EASY without page refresh!

Use Ajax with Classic ASP to preview data then update form with javascript url write

Yvo Schaap's easy inline edit Ajax: an example of using it to inline edit multiple rows of records in Classic ASP

Use Classic ASP to send text messages SMS from your website (Also shows how to use xmlhttp to post form data)

Ajax with Classic ASP for seamless, no page reload database record insertion

Nested SQL Statements to make temporary column names

Multiple records per row with paging

Display multiple records per row

Get ID of newly inserted record, Classic ASP, Access Database

Javascript timer with ASP to keep track of time expired until login expires / timeout session is up

Multiple Javascript event functions triggered from single form onsubmit

Get Querystring key names along with querystring variables

These are out of date but may still be of interest:

ASP Youtube Downloader  Version FOUR
All ASP code. Allows user client side downloads of Youtube videos. You have the option to allow files to be saved directly to your site also.
ASP/PHP video downloader (Works better than ASP for large files)

Use ASP to dynamically parse a Youtube XML playlist to render to html.

Zip up an archive file of your site for backup if you need to restore website with ASP and free Zip Component.

Zip all files in a folder into an archive or backup file dynamically by specific file extension.

Sanitize or clean price cost field for database insertion or display.

Javascript image dimensions and image file size preview.

Put recordset into array, assign keys to the records then use record associated with specific array key as a variable elsewhere.

Access Database Interface Generator Wizard to read your table and field names and to create a table display.

Combining dropdown selection box menu with dynamic ASP database page.

How to redirect user to original page they tried to view before logging, after they are logged in.

Previous/Current/Next Records, or Buddy Ring Script

Custom ASP 404 page not found error script: can also be used for URL rewriting

ASP Example: Combine ASP with Javascript for popup windows
dynamically sized to image dimensions.

ASP Example: How to use ASPJPEG to create thumbnails
Click for free Highly recommended thumbnailer for which you don't need Server access (doesn't seem to work on Windows Server 2008)

ASPjpeg: How to re-scale aspect ratio of thumbnails by height instead of width.

ASP Example: What if your host has an older version of ASPJPEG that doesn't support gifs?

Select Count Distinct Records for Access Database

Upload Image to folder and insert filename into database

Get date in such a way that it can be made part of a file name

Isolate a file name away from its path or extension or strip a path from a file name or strip characters from database field

User-customized on-the-fly stylesheet css files

Enhanced Page Hits Counter (also counts downloads and menu link hits)

Loop through array and compare to string with select case

Aphabetical Paging for your ASP scripts

Web Wiz Guide's Site Searcher Script modified as a file content indexer

Let Users Select How Many Records to View

Access Database for your PayPal IPN scripts

Miscellaneous collected code

From Classic ASP to PHP

You don't have to be a genius, just persistent, to write original Active Server Pages scripts

BuildApp - great old Classic ASP script generator!

Software Recommendation: bare_bones_no_bells_and_whistles_asp_code_generator_database_interface_maker (For PHP I recommend EasyGen.)

If any of this information is helpful to you, please consider donating with the button below. Thanks! ~~Lil