Ruby
Ruby
Reading Unread POP3 Email
The POP3 protocol cannot determine which emails are "unread," and pure POP3 servers do not store this information. Servers like Exchange Server, offering both POP3 and IMAP interfaces, do contain read/unread data, but it's only accessible through IMAP. Email clients like Outlook and Thunderbird store read/unread statuses on the client side. The example demonstrates using UIDLs to track and manage "unread" emails.Chilkat Ruby Downloads
require 'chilkat'
success = false
# This example requires the Chilkat API to have been previously unlocked.
# See Global Unlock Sample for sample code.
# The mailman object is used for receiving (POP3)
# and sending (SMTP) email.
mailman = Chilkat::CkMailMan.new()
# Set the POP3 server's hostname
mailman.put_MailHost("pop.example.com")
# Set the POP3 login/password.
mailman.put_PopUsername("***")
mailman.put_PopPassword("***")
# Keep a records of already-seen UIDLs in hash table serialized to an XML file.
seenUidlsPath = "c:/temp/seenUidls.xml"
sbXml = Chilkat::CkStringBuilder.new()
htSeenUidls = Chilkat::CkHashtable.new()
fac = Chilkat::CkFileAccess.new()
if (fac.FileExists(seenUidlsPath) == true)
success = sbXml.LoadFile(seenUidlsPath,"utf-8")
if (success == false)
print sbXml.lastErrorText() + "\n";
exit
end
htSeenUidls.AddFromXmlSb(sbXml)
end
# Get the complete list of UIDLs on the mail server.
stUidls = Chilkat::CkStringTable.new()
success = mailman.FetchUidls(stUidls)
if (success == false)
print mailman.lastErrorText() + "\n";
exit
end
# Build a list of unseen UIDLs
stUnseenUidls = Chilkat::CkStringTable.new()
i = 0
count = stUidls.get_Count()
while i < count
uidl = stUidls.stringAt(i)
if (htSeenUidls.Contains(uidl) != true)
stUnseenUidls.Append(uidl)
end
i = i + 1
end
if (stUnseenUidls.get_Count() == 0)
print "No unseen emails!" + "\n";
exit
end
# Download the unseen emails, adding each UIDL to the "seen" hash table.
email = Chilkat::CkEmail.new()
count = stUnseenUidls.get_Count()
i = 0
while i < count
# Download the full email.
uidl = stUnseenUidls.stringAt(i)
success = mailman.FetchByUidl(uidl,false,0,email)
if (success == false)
print mailman.lastErrorText() + "\n";
exit
end
print i.to_s() + "\n";
print "From: " + email.ck_from() + "\n";
print "Subject: " + email.subject() + "\n";
# Add this UIDL to the "seen" hash table.
htSeenUidls.AddStr(uidl,"")
i = i + 1
end
mailman.Pop3EndSession()
# Update the "seen" UIDLs file.
sbXml.Clear()
htSeenUidls.ToXmlSb(sbXml)
success = sbXml.WriteFile(seenUidlsPath,"utf-8",false)
if (success == false)
print sbXml.lastErrorText() + "\n";
exit
end
print "Success." + "\n";