Search code examples
coldfusioncfmail

ColdFusion Limit to 5 E-mails a Day


Say I have the following script on page.cfm. Everytime somebody comes to page.cfm, an e-mail is sent to me. So if 1000 people come to page.cfm, I get 1000 e-mails.

<cfmail to="[email protected]"
from="[email protected]"
subject="Error"
type="text">
A person visited.
</cfmail>

I would like to limit it so I only get e-mails when the first 5 people visit in one day.

So if 2 people visit today, I get 2 e-mails. if 5 people visit I get 5, but if 100 people visit, I still get only 5 e-mails. And then the cycle continues the next day (if 2 people visit only 2 e-mails are send, but if 100 people visit only 5 e-mails are sent)

How can I do this with ColdFusion only? (without cfschedule)


Solution

  • The simplest way I can think of is to put a counter and a date stamp in a pair of Application variables.

    Then, for each request, check the date you've recorded. If it's not today, reset the counter variable to 1 and re-set the date to today.

    Then, where you're putting the cfmail tag, do a check to see if the counter has reached your limit. If not, send the mail. Either way, increment the counter.

    In Application.cfc onApplicationStart():

    <cfset application.alertDate = now()>
    <cfset application.alertCount = 1>
    

    (the above is mostly to ensure that the variables exist when used later)

    In Application.cfc onRequestStart():

    <cfif dateCompare(application.alertDate,now(),"d") EQ -1)>
      <cfset application.alertCount = 1>
      <cfset application.alertDate = now()>
    </cfif>
    

    In page.cfm:

    <cfset application.alertCount++>
    <cfif application.alertCount LTE 5>
      <cfmail ... >
    </cfif>