Classic ASP Active Server Pages Examples, code, tutorials, scriptsPHP Check Email Save Files to Web Folder or Archive Emails to File or Database

NOTE: I was not satisfied with any of the PHP scripts I tested for this purpose. I took another look at Classic ASP with Jmail and wrote an ASP script that performs exactly as I wanted. See it here.

 

I have wanted a script that would do this for a long time. There are a few on the net but none of them would work for me. I found some pieces that each did what I needed and put them together. This script works fine with Arvixe.com Windows hosting.

See the comments with script below. Additional enhancements might be to limit message capturing to certain count each time and delete after saved. I noticed that with large number of emails some files were saved as 0 KB--perhaps there were too many for the script to save all at once? The script I borrowed from most heavily has a line for imap's "seen" to set a flag and perhaps this could be used more fully to keep from downloading the same messages without having to delete them. See http://php.net/manual/en/function.imap-setflag-full.php

 

It wasn't until I finished my script that I saw this one that works much better!  Documentation for configuring that one is limited so I have posted a new notes about it below that may be helpful especially if your site is on a Windows / SMTP host:

1. Make sure you are using the newest version from zip file etodb-2006-09-01.zip -- the main zip file named emailtodb_v0.9.pack.zip is NOT the newer version.


2. You need both the example_1_index.php (rename as you wish) file AND the class.emailtodb_v0.9.php file.


3. Configure line 35 for the folder you want files saved to and make sure that folder is writeable.


4. Configure line 48 according to whether you will run script from browser (it uses meta-refresh) or cron.


5. Configure line 59 for your mail server and login. For Windows Host that uses SMTP:
$this->link = imap_open("{mail.YOURDOMAIN.com:143/notls}INBOX", "YOUREMAIL@YOURDOMAIN.COM", "YOURPASSWORD");


6. Configure line 23 of example_1_index.php for database credentials and email credentials. If Windows with SMTP:
$edb->connect('MAIL.YOURDOMAIN.COM', '/smtp:143/notls', 'YOURMAIL@YOURDOMAIN.COM', 'YOURPASSWORD');
 

7. One more thing, on line 327 or so, change
this line:
foreach ($from as $id => $object) {
to corrected as below:
foreach ($to as $id => $object) {



I highly recommend this script. It took me a little while to figure out how to make it run on a Windows host, but once done, it does really well and is exactly what I needed. I had tried writing my own script that does this work, but this one is vastly superior.  I have left the script I put together below in case anything in it is of use.  The biggest problem with the script below is that when it saves multiple files from a single email, it saves some of them as 0 byte files.

If you make improvements to the script below, I would love to see them. LilPeck@gmail.com

To set up the Database (MySQL):

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,
`FileName` varchar(255) NOT NULL,
`FileType` varchar(255) NOT NULL,
`MailID` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`MailID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=208 ;
 


 

<?php

//uncomment out the following two lines to show error messages
//ini_set('display_errors',1);
//error_reporting(E_ALL|E_STRICT);

//credits:
//main script: http://phpbuilder.com/board/showthread.php?t=10324540
//http://www.howtogeek.com/forum/topic/obtaining-sender-address-using-imap
//http://www.php.net/manual/en/function.imap-mail.php


//chmod("/home/user/public_html/archivedemail/", 0777); //this will work only for nix servers it is to make the files folder writeable for windows you have to do it manually
//path to save attached files to with trailing slash:
$absolutePath ="C:/WINDOWS/PATH/TO/SAVED/FILES/EMAILATTACHMENTS/";

$dbuser="YOURUSERID";
$dbpass="DATABASEPASSWORD";
$database="DATABASENAME";

mysql_connect("DATABASEHOST",$dbuser,$dbpass);
@mysql_select_db($database) or die( "Unable to select database");


$login="YOU@YOURDOMAIN.COM";
$password="YOURPASSWORD";

//your mail server may be one of the following
//$mailhost="{my.mailserver.net:110/pop3}"; // pop3host
$mailhost="{YOURDOMAIN.COM:143/notls}"; // SMTP MAIL WINDOWS SERVER -- DOES NOT SEEM TO BE NECESSARY TO WRITE AS MAIL
.YOURDOMAIN.COM

$mbox = imap_open($mailhost."INBOX", "$login", "$password")
or die("Could not open Mailbox - try again later!");

// make connection with mailbox and check # messages
if ($hdr = imap_check($mbox)) {
echo "Num Messages " . $hdr->Nmsgs ."\n\n<br><br>";
$msgCount = $hdr->Nmsgs;
} else { echo "failed"; }
$overview=imap_fetch_overview($mbox,"1:$msgCount",0);
$size=sizeof($overview);


// get message info
for($i=$size-1;$i>=0;$i--)
{
$val=$overview[$i];
$msg=$val->msgno;
$fromname=$val->from;
$date=$val->date;
$subj=$val->subject;

//get To address - you would need do more looping code to get multiple addressees
$header = imap_header($mbox, $i);
$to = $header->to;
foreach ($to as $id => $object) {
$toname = $object->personal;
$toaddress = $object->mailbox . "@" . $object->host;
//echo $toaddress;
}

//get FROM address
$header = imap_header($mbox, $i);
$from = $header->from;
foreach ($from as $id => $object) {
$fromname = $object->personal;
$fromaddress = $object->mailbox . "@" . $object->host;
//echo $fromaddress;
}


$seen=$val->seen;
$fromname = ereg_replace("\"","",$fromname);


// Check for attachments and store them
$struct = imap_fetchstructure($mbox,$msg);
$contentParts = count($struct->parts);

if ($contentParts >= 2) {
for ($ix=2;$ix<=$contentParts;$ix++) {
$att[$ix-2] = imap_bodystruct($mbox,$msg,$ix);
}
for ($k=0;$k<sizeof($att);$k++) {
if ($att[$k]->parameters[0]->value == "us-ascii" ||
$att[$k]->parameters[0]->value == "US-ASCII") {
if ($att[$k]->parameters[1]->value != "") {
$FileName[$k] = $att[$k]->parameters[1]->value;
//echo $FileName[$k]. "<BR>";
$FileType[$k] = strrev(substr(strrev($FileName[$k]),0,4));

}
} elseif ($att[$k]->parameters[0]->value != "iso-8859-1" &&
$att[$k]->parameters[0]->value != "ISO-8859-1") {
$FileName[$k] = $att[$k]->parameters[0]->value;
$FileType[$k] = strrev(substr(strrev($FileName[$k]),0,4));

$MyMessage = imap_fetchbody($mbox,$msg,1);



$MyMessage = imap_fetchbody($mbox,$msg,1);
$MyFile = mysql_real_escape_string($FileName[$k]);
$MyFileType = mysql_real_escape_string($FileType[$k]);
$MyMessage = imap_fetchbody($mbox,$msg,1);
$MyMessage = mysql_real_escape_string(strip_tags($MyMessage,''));

//WITH THE FOLLOWING LINES YOU COULD ARCHIVE THE INFORMATION TO DATABASE OR SAVE TO FILE INSTEAD IF YOU CHOOSE
mysql_query("INSERT INTO archivedemails (`MailDate`, `FromName`, `FromAddress`, `ToAddress`, `Subject`, `MsgBody`, `FileName`, `FileType`)
VALUES ('$date', '$fromname', '$fromaddress', '$toaddress', '$subj', '$MyMessage', '$MyFile', '$MyFileType')");

echo "<BR><BR>DATE: ".$date;
echo "<BR><BR>FROM: ".$fromname. " / ".$fromaddress;
//echo "<BR><BR>FROM: ".$fromaddress;
echo "<BR><BR>TO: ".$toaddress;
echo "<BR><BR>SUBJECT: ".$subj;
echo "<BR><BR>MESSAGE: <BR>".strip_tags($MyMessage,'<p><br>'); //I CHOSE TO REMOVE MOST HTML BUT LEAVE TWO TYPES OF TAGS YOU COULD REMOVE ALL HTML TAGS
echo "<BR><BR>ATTACHED FILE: ".$FileName[$k] ;
echo "<BR>FILE TYPE: ".$FileType[$k] . "<BR><BR><BR><hR>";

$fileContent = imap_fetchbody($mbox,$msg,$k+2);
$fileContent = imap_base64($fileContent);

//I CHOSE NOT TO SAVE FILES THAT HAVE .MSG AS THE EXTENSION. YOU COULD REMOVE THAT OR PUT IN SOMETHING ELSE OR WRITE UP AN ARRAY OF EXTENSIONS TO BE CHECKED
if ($FileType[$k]==".msg") {
echo "NOT DESIRED FILE TYPE";
}
else {

//WHERE DO YOU WANT TO SAVE THE ATTACHED FILES? The example shows with Windows absolute path with nix it will be like /home/user/public_html/archivedemail/
$localfile = fopen($absolutePath.$FileName[$k],"w");
fputs($localfile,$fileContent);
fclose($localfile);
}
}
}
}
}
imap_close($mbox);
mysql_close();
//chmod("/home/user1public_html/archivedemail/", 0755); //this will work only for nix servers it is to make the folder non-writeable again

//ADDITIONAL ENHANCEMENTS FOR SCRIPT MIGHT BE TO LIMIT MESSAGE CAPTURING TO A CERTAIN COUNT EACH TIME AND TO DELETE AFTER SAVED.
//NOTE: I NOTICED THAT WITH LARGE NUMBER OF EMAILS SOME FILES WERE SAVED AS 0 KB PERHAPS TOO MANY FOR THE SCRIPT TO DO AT ONCE?
?>

 


 


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

FACEBOOK API GEEWHIZ - INTEGRATE FACEBOOK WITH YOUR WEBSITE

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