Connecting to Gmail using ColdFusion
Do you want to build an integrated ColdFusion interface to Gmail? Using newbish's IMAP CFC client, it can be done. It just needs a couple modifications to work with Gmail's SLL IMAP.
Here's how...
1. Enable IMAP in your Gmail account
2. Download the IMAP CFC from SourceForge.
3. Make the following modifications to the imap.cfc
- On line 7, add this... <cfset this.sslenabled = 0 />
- At the end of the init() function, add this...
<cfif isdefined("arguments.ssl")>
<cfset this.sslenabled = 1 />
</cfif> - Replace the GetStore() function with this one...
<cffunction name="GetStore" access="private" output="No">
<cftry>
<cfset clsSession = createObject("Java", "javax.mail.Session")>
<cfset objProperties = createObject("Java", "java.util.Properties")>
<cfset objStore = createObject("Java", "javax.mail.Store")>
<cfset Timeout = this.imapTimeout * 1000>
<cfif this.sslenabled>
<cfset protocol = "imaps">
<cfelse>
<cfset protocol = "imap">
</cfif>
<cfset objProperties.init()>
<cfset objProperties.put("mail.store.protocol", protocol)>
<cfset objProperties.put("mail.imap.port", this.imapPort)>
<cfset objProperties.put("mail.imap.connectiontimeout", Timeout)>
<cfset objProperties.put("mail.imap.timeout", Timeout)>
<cfset objSession = clsSession.getInstance(objProperties)>
<cfset objStore = objSession.getStore()>
<cfset objStore.connect(this.imapServer, this.username, this.password)>
<cfcatch type="any">
You do not have a mail account or there was a problem authenticating.<cfabort>
</cfcatch>
</cftry>
<cfreturn objStore>
</cffunction>
You can now use the CFC library to interface with Gmail's IMAP. Just make sure to pass the right arguments into the init function - The port has to be 993 for Gmail, and argument 6 should be a 1 (ssl enabled). The CFC will still work for non-SSL IMAP calls if you want to use it. Just pass a 0 in argument 6.
Here's an example for Gmail...
<!--- Written by Jason Quatrino, Hamilton College // --->
<cfset imapCFC = CreateObject("component","imap") />
<cfset imapInit = imapCFC.Init(username,password,"imap.gmail.com",993,15,1) /><!--- add your own username/password --->
<!--- determine which message ids to get --->
<cfset msgs = imapCFC.list("Inbox") />
<!--- Return a query of messages --->
<cfdump var="#msgs#" />
If you have a TON of e-mail in your Gmail Inbox, you might want to modify this code before you run it. Something like this... pass in just a few message IDs in the second argument of the list function. I can share more code if people are interested, but I don't have permission from "newbish" to post the whole CFC.
Brian wrote on 11/27/07 9:33 AM
Great article, thanks for sharing this with us.