(JavaScript) 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. Note: This example requires Chilkat v11.0.0 or greater.
var 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.
var mailman = new CkMailMan();
// Set the POP3 server's hostname
mailman.MailHost = "pop.example.com";
// Set the POP3 login/password.
mailman.PopUsername = "***";
mailman.PopPassword = "***";
// Keep a records of already-seen UIDLs in hash table serialized to an XML file.
var seenUidlsPath = "c:/temp/seenUidls.xml";
var sbXml = new CkStringBuilder();
var htSeenUidls = new CkHashtable();
var fac = new CkFileAccess();
if (fac.FileExists(seenUidlsPath) == true) {
success = sbXml.LoadFile(seenUidlsPath,"utf-8");
if (success == false) {
console.log(sbXml.LastErrorText);
return;
}
htSeenUidls.AddFromXmlSb(sbXml);
}
// Get the complete list of UIDLs on the mail server.
var stUidls = new CkStringTable();
success = mailman.FetchUidls(stUidls);
if (success == false) {
console.log(mailman.LastErrorText);
return;
}
// Build a list of unseen UIDLs
var stUnseenUidls = new CkStringTable();
var uidl;
var i = 0;
var count = stUidls.Count;
while (i < count) {
uidl = stUidls.StringAt(i);
if (htSeenUidls.Contains(uidl) !== true) {
stUnseenUidls.Append(uidl);
}
i = i+1;
}
if (stUnseenUidls.Count == 0) {
console.log("No unseen emails!");
return;
}
// Download the unseen emails, adding each UIDL to the "seen" hash table.
var email = new CkEmail();
count = stUnseenUidls.Count;
i = 0;
while (i < count) {
// Download the full email.
uidl = stUnseenUidls.StringAt(i);
success = mailman.FetchByUidl(uidl,false,0,email);
if (success == false) {
console.log(mailman.LastErrorText);
return;
}
console.log(i);
console.log("From: " + email.From);
console.log("Subject: " + email.Subject);
// Add this UIDL to the "seen" hash table.
htSeenUidls.AddStr(uidl,"");
i = i+1;
}
mailman.Pop3EndSession();
// Update the "seen" UIDLs file.
sbXml.Clear();
htSeenUidls.ToXmlSb(sbXml);
success = sbXml.WriteFile(seenUidlsPath,"utf-8",false);
if (success == false) {
console.log(sbXml.LastErrorText);
return;
}
console.log("Success.");
|