Welcome to MailBee Objects, a set of robust and easy-to-use e-mail components which will enable your applications to send, receive and manage e-mail.

You can use the links below as first stops in your search for information.

Samples section provides dozens of code examples you can quickly start with:
  • Creating and sending e-mail
  • Receiving and displaying e-mail (POP3)
  • Receiving and displaying e-mail (IMAP4)
  • Advanced topics

Tutorials sections highlights some important aspects of creating, receiving and displaying e-mail in more detailed way.

FAQ page answers most common questions related to MailBee installation and usage issues.

Reference section contains full reference on all MailBee's objects, properties and methods.

Information on 64-bit version of MailBee Objects can be found here.

If you're using Delphi for native Windows (like Delphi 7, Delphi 2007, Delphi 2009), you can find a number of samples in MailBee/MailBee Programming Samples/Delphi folder of Start menu.

If you're using a .NET capable environment (like Visual Studio 2003 and above, Delphi Prism 2009, etc), consider upgrading to MailBee.NET Objects package which performs much better in .NET applications.

For details on purchasing MailBee Objects or individual MailBee components see Registration page.

Should you have any questions or concerns, please do not hesitate to contact AfterLogic Support on the web.

SMTP
Create and send e-mails with the SMTP object
POP3
Receive e-mails with the POP3 object
IMAP4
Receive e-mails and manage mailboxes with the IMAP4 object
SSL
 Add SSL/TLS security to e-mail applications
SMIME
 Add S/MIME security to e-mail applications

Send feedback to AfterLogic
Copyright © 2002-2020, AfterLogic Corporation. All rights reserved.


Ordering And Registration

MailBee Objects is shareware. During downloading MailBee Objects from AfterLogic web site you will receive a trial license key to the email address you have specified. This trial license is valid for 30 days. After the trial expiration, MailBee Objects will stop functioning. If you would like to continue using the product, you should register it.

Note: MailBee Objects and MailBee.NET Objects are different products. MailBee Objects (this product) CAN be used in .NET but it's not a native .NET assembly. It's a .NET-compatible ActiveX component (while MailBee.NET Objects is a pure .NET assembly). License keys for MailBee Objects and MailBee.NET Objects are different and not compatible with each other. Feature set is also different for these products (MailBee.NET Objects provides significantly more functions and flexibility while MailBee Objects is mostly intended for legacy applications which have not yet migrated to the .NET platform).

MailBee license keys start with MBC. MailBee.NET license keys start with MN.

Visit MailBee Objects Secure Registration Pages

You can purchase the entire bundle or select a particular component (like SMTP) and purchase it separately.

After the registration is complete, your permanent license key will be sent to the email address you specified during the purchase. Once you received the key, you can use it with MailBee just like you earlier did with a trial key (simply replace the trial key with your permanent key, nothing else required).

As noted above, a permanent license key can be used in exactly the same manner as a trial key. In your programs (or ASP pages) you need to assign LicenseKey property of MailBee.POP3, MailBee.IMAP4, MailBee.SMTP object to the value of your license key before first call of Connect method of POP3, IMAP4 or SMTP objects. For MailBee S/MIME plugin, LicenseKey must be assigned for SMIME object before using its functions.

Please also make sure to accept AfterLogic license agreement terms before using MailBee products.

View License Agreement


MailBee Objects FAQ

Repairing MailBee Objects installation or updating MailBee Objects to a new version.

'CreateObject Failed' (or 'Server.CreateObject failed') error. Why?

How to distribute MailBee Objects?

(POP3) How to retrieve headers for all messages and iterate through a collection in ASP?

(POP3) I need to get somewhat more than just message headers (but still not a whole message). Is it possible to get headers and first lines of message body?

(SMTP) How to turn line-wrapping off when composing plain-text body.

(SMTP) Messages are not sent. Any solution?

64-bit version of MailBee.dll

32-bit version of MailBee.dll on 64-bit Windows

Using MailBee with MS Exchange Server (for developers how previously worked with Outlook).

Is IPv6 supported?

Is OAuth 2.0 supported?

Repairing MailBee Objects installation or updating MailBee Objects to a new version.

To reinstall MailBee Objects or install a new version, it's required to uninstall an existing version first.

Prior to uninstalling make sure no applications use MailBee Objects. For example, Internet Information Server (IIS) caches recently used components, so you need to stop or restart the server BEFORE uninstalling MailBee Objects (execute "iisreset" command in Start/Run menu).

Also, ActiveX-aware development environments (such as Developer Studio) might lock MailBee Objects if you develop an application or ASP page that uses MailBee Objects. You need to close your development environment before uninstalling.

The easiest way to make sure MailBee Objects is not locked by some other application is to reboot the machine where MailBee Objects is installed. After rebooting, you must run MailBee uninstaller BEFORE using IIS or Developer Studio (otherwise, MailBee Objects could get locked again).

As soon as MailBee Objects is not locked anymore, you can uninstall it and install the new version.

'CreateObject Failed' (or 'Server.CreateObject failed') error. Why?

MailBee Objects installation was damaged for some reason. Stop or exit all applications that can potentially use MailBee Objects (such as IIS or Developer Studio), and reinstall MailBee Objects.

Another reason is a permission problem (often the case for ASP applications). Make sure IIS user (can be IUSR_<YOUR_SERVER_NAME>, NETWORK SERVICE, and a few other names) has permission to read MailBee.dll and read the Windows registry entries related to MailBee.

How to distribute MailBee Objects?

MailBee.dll ActiveX component is an only file required to distribute MailBee objects across computer systems. Copy it to any location (for example, windows system32 directory or your application directory) and register it as ActiveX component in the registry (for example, using regsvr32 utility or other tool your installer program provides).

If you're using 64-bit version, the same instructions apply with the only difference that the file to be distributed is MailBee64.dll.

(POP3) How to retrieve headers for all messages and iterate through a collection in ASP?

To retrieve only headers (without downloading whole messages) at once, use RetrieveHeaders method that returns collection of Message objects:

' Assume Mailer object is already created and all required settings
' (LicenseKey/UserName/Password/ServerName) are set.
If Mailer.Connect Then
  Set Msgs = Mailer.RetrieveHeaders
  Response.Write Msgs.Count & " messages total in mailbox<br>"
  For Each Msg In Msgs
    Response.Write "Subject: " & Msg.Subject & "<br>"
  Next
  Mailer.Disconnect
Else
  Response.Write Mailer.ErrDesc
End If

(POP3) I need to get somewhat more than just message headers (but still not a whole message). Is it possible to get headers and first lines of message body at once?

RetrieveHeaders along with RetrieveSingleMessageHeaders methods have optional parameter BodyLinesCount that allows you to specify how many body lines to download in addition to headers part.

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then

    ' Download headers and 10 lines of the body
    Set Msg = Mailer.RetrieveSingleMessageHeaders(1, 10)

    If Not Msg Is Nothing Then
      MsgBox "Body preview: " & Msg.BodyText
    End If
  End If
  Mailer.Disconnect
End If

(SMTP) How to turn line-wrapping off when composing plain-text body.

Use quoted-printable (QP) or base64 (B64) body encoding methods. These advanced methods preserve original text formatting - text is no longer wrapped by 76 characters per line. See BodyEncoding and AltBodyEncoding topics or the sample code below for details.

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.BodyText = "Assume the text at this line is longer that 76 symbols length"
  Mailer.Message.BodyEncoding = 2 ' Quoted-printable encoding
  Mailer.Send
  Mailer.Disconnect
End If

(SMTP) Messages are not sent. Any solution?

SMTP server you are using:

  • might be down
  • requires users' authentication (see SMTP.AuthMethod property on how to use SMTP authentication)
  • does not allow sending from the e-mail address you have specified in FromAddr field
  • antispam software running on the server or on your machine (or within your local network) blocks e-mail transmissions for some reason. Try to disable this software or switch to another SMTP server (if this software operates on the server)
  • the message size exceeded allowable limit. Many servers do not allow relaying large e-mails
  • the server may allow user access from restricted set of IP addresses only. This is common for ISP's servers where you may access mail server from your computer but not from remote computer (such as web server where webmail system powered by MailBee is running)
  • Server requires specific domain to be used in HELO command. Set SMTP.Domain or SMTP.Message.FromAddr property BEFORE calling SMTP.Connect method to use proper domain
MailBee.SMTP object supports a number of debugging properties and logging option to help you in understanding what really happens. Also, you may send the log file to us to find the solution quickly.

Debugging properties are:
  • IsError - whether an error occurred
  • ErrDesc - short text description of an error
  • ErrCode - numeric code of an error
  • ServerResponse - last text reply of the server

Logging may be activated by enabling logging option and specifying log file path (see EnableLogging and LogFilePath properties).

Sample code below shows how to activate logging and check debugging properties on error:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox

' Enable logging option
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt" ' You may send this log to us

' Uncomment the next line if you want the log file to be cleared first
' Mailer.ClearLog

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.site.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "recipient@server.com"
  Mailer.Message.FromAddr = "sender@server.com"
  Mailer.Message.Subject = "Test"
  Mailer.Message.BodyText = "Body test"
  If Not Mailer.Send Then
    MsgBox _
      Mailer.ErrDesc & vbCrLf & _
      "ErrCode: " & Mailer.ErrCode & vbCrLf & _
      "Last server reply: " & Mailer.ServerResponse

  End If
  Mailer.Disconnect
Else
  MsgBox _
    Mailer.ErrDesc & vbCrLf & _
    "ErrCode: " & Mailer.ErrCode & vbCrLf & _
    "Last server reply: " & Mailer.ServerResponse
End If

64-bit version of MailBee.dll

64-bit version of MailBee.dll (MailBee64.dll) is installed in the same folder where MailBee.dll resides. If your system is 64-bit, MailBee64.dll also gets registered (so that both 32-bit and 64-bit versions are registered side-by-side). If you need to register it on 64-bit Windows manually (for instance, when deploying your application), use regsvr32 utility in Windows\System32 folder. Note: there is another version of regsvr32 in Windows\SysWOW64 folder, do not use it!

You must run regsvr32 in "Run as Administrator" mode (for instance, when opening Command Prompt, use "Run as Administrator" option).

Example: C:\Windows\System32\regsvr32 "C:\Program Files (x86)\MailBee Objects\MailBee64.dll"

32-bit version of MailBee.dll on 64-bit Windows

To register 32-bit version of MailBee.dll on 64-bit Windows, use regsvr32 in Windows\SysWOW64 folder, NOT the regular regsvr32 in System32 folder. Also, You must run regsvr32 in "Run as Administrator" mode.

Using MailBee with MS Exchange Server (for developers how previously worked with Outlook)

Outlook usually works with MS Exchange over ExchangeRPC protocol, not over SMTP, POP3 or IMAP. Thus, the fact you can successfully connect with MS Outlook does not yet mean the same settings will apply in SMTP, POP3 or IMAP case.

If you have connectivity issues, make sure SMTP, POP3 or IMAP port is opened on both the server and your computer. Also, make sure MS Exchange is running SMTP and POP3 or IMAP service and the user you're trying to authenticate has permissions to use SMTP, POP3, or IMAP (depending on which protocol you're using).

By default, POP3 and IMAP access is DISABLED on MS Exchange server.

Using logging (see EnableLogging property of your mailer object) can be helpful for troubleshooting (for instance, to find out whether the problem occurs during connecting or during authenticating).

If the connection itself succeeds but you cannot log in, try using NTLM or GSSAPI authentication (see AuthMethod of the mailer component for details) because MS Exchange may disable other methods. Or, try setting Mailer.SSL.Enabled=True (where Mailer is your SMTP, POP3 or IMAP4 object). MS Exchange may be configured to allow you to authenticate only if the connection is secured.

Tthe username you're using for authentication may be incorrect due to the domain part. With GSSAPI or NTLM authentication, you can specify the domain with UserDomain property. With regular authentication, you have to supply it in the UserName. The typical syntax is "domain\username".

If your Exchange account is aliased, the full form of the login name can be "domain\logon_name\alias_name".

Is IPv6 supported?

Yes, IPv6 is supported for all components in MailBee Objects suite.

Is OAuth 2.0 supported?

Yes, OAuth 2.0 is supported for all components in MailBee Objects suite. You can find Gmail and OAuth 2.0 samples in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder.


MailBee Objects Version History

9.3

  • OAuth 2.0 support for POP3, IMAP4 and SMTP components (tested with Gmail and Office 365, includes samples in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder).
  • Minor fixes.

9.2

  • Better IPv6 support.
  • IMAP4 UIDPLUS extension support (IMAP4.UIDPlusResult property).
  • PFX support in SMIME.AddRecipientCert method.
  • Correct parsing of UTF-7-alike email addresses (with plus sign in them).
  • SMIME.CSP property now actually has effect (earlier it wasn't actually in use).
  • SHA2-256 signing in now supported in S/MIME.
  • The default encryption method in S/MIME is now 3DES (seems to be supported by most mail clients around) instead of a weaker RC4.
  • S/MIME signatures now include full certificate chain.
  • More accurate error handling in S/MIME.
  • Documentation fixes (mostly in S/MIME).

9.1

  • IDN domains (e-mail addresses with international characters in domain part).
  • Minor fixes.

9.0.3

  • Improved stability on 64-bit systems.
  • Documentation fixes.

9.0.2

  • SHA256 signatures to all .DLLs (in addition to SHA1 signatures).
  • SMTP authentication log file messages made more clear.
  • Misc. bugfixes.

9.0.1

  • TLS 1.1/1.2 support in SSL.Protocol property.
  • Documentation fixes (mostly on the ability to use MailBee.NET Queue instead of outdated MailBee Message Queue).
  • Misc. bugfixes.

9.0

  • Authenticode signatures for all .DLLs and the installer.
  • IMAP MOVE extension support (moving messages).
  • IMAP SPECIAL-USE extension support (special mailbox flags).
  • IMAP CHILDREN extension support (special mailbox flags).
  • IMAP SORT extension support (sorting of search results).
  • IMAP UNSEEN response support (message number of the first unseen message in the mailbox).
  • IMAP UIDNEXT response support (next predicted UID in the mailbox).
  • IMAP STATUS command support (unseen count, message count and other info for a mailbox without selecting it).
  • IMAP message sets - arbitrary sequences of message numbers or UIDs (more flexible than ranges, enable doing more actions in a single batch).
  • IMAP SetSeenFlag in RetrieveSingleMessage method.
  • IMAP -1 or -2 values for BodyPreviewSize parameter of RetrieveSingleMessageHeaders and RetrieveEnvelopesEx methods to enable downloading entire message with or without \Seen flag setting.
  • IMAP QUOTA now returns not only allocated but also occupied space in the mailbox (QuotaUsage property).
  • SMTP EHLO/HELO now uses the local machine host name if SMTP.Domain property not set.
  • AddressDelimiter property for Envelope and Message objects to make it easier to split address strings into individual addresses.
  • Filename autogeneration for attachments without filenames. New Attachment.FilenameAsIs property to get the original filename (possibly empty).
  • Samples now reside in My Documents instead of Program Files (eliminates UAC issues when opening sample projects).
  • Improved VB6's IMAP Demo 2 and Mailer samples (refer to readme files in samples folder if you have trouble loading VB6 sample projects on modern systems).
  • Misc. bugfixes and documentation fixes.
  • License keys in MBC900 format (contact AfterLogic Support to request your license key or renew maintenance contract if it's expired).

8.2

  • Windows 8/8.1 compatible installer (on these systems, avoids clutter on the Start Screen by putting a single link which opens MailBee Objects folder).
  • Better handling of non-English characters in encoded headers.
  • Better handling of quoted strings in IMAP responses and MIME messages.
  • Misc. improvements in MIME parser.
  • Fixed disconnect-related issues for all protocols (SMTP, IMAP, POP3).
  • New mode 4 of building filenames of related files (when using Message.GetBodyWithEmbeddedObjectsEx method). Preserves original filenames in most part but adds indexes to avoid overwriting when multiple related files in a message have the same filename (e.g. if the message has related files "pic.gif", "pic.gif", "anotherpic.jpg", temp files will bear names "pic[0].gif", "pic[1].gif", "anotherpic[2].jpg").

8.1

  • Support of Content-Location header (available in Attachment object and during displaying e-mails with embedded pictures as Content-ID alternative).
  • SMTP object now supports AllowRefusedRecipients property and GetAcceptedRecipients/GetRefusedRecipients methods to enable sending multi-recipient e-mails which may have some recipients invalid.
  • Better recognition of e-mail addresses with special symbols in Message's object ValidateEmailAddress method.
  • Misc. MIME parser fixes.

8.0

  • Full support of Unicode in all components. This release deprecates Codepage, CodepageMode, CharsetOriginal properties in all the classes, no more settings is required to enable international languages support. Message.Charset of outgoing e-mails is now by default set to "utf-8".
  • Added Message.AutoEncodeHeaders property (True by default). Encodes all headers with international characters in their values automatically, no need to use Message.EncodeHeaderText method.
  • Message.IsLocked property deprecated. Now changing an existing message is possible without using this property.
  • New charset-related parameters for Message.ImportBodyText , Message.ImportAltBodyText, Message.GetBodyWithEmbeddedObjectsEx methods.
  • New Message.GetCodepageFromCharset method for interoperability of charsets (which are strings) and codepages (which are numbers).
  • Message.GetMD5Digest and Message.GetMD5DigestOfArray method improvements.
  • Message.MinimalRebuild=True is now less restrictive on the ways you can change headers. You can now explicitly set headers via Subject, FromAddr, and other properties of Message object.
  • Message headers which you haven't changed are now left intact (not rebuilt) when you modify and re-send an existing message.
  • Better support of international filenames of attachments (now supports multi-line MIME words).
  • Message.AddAttachment (and its versions AddStringAttachment and AddMemoryAttachment) now let you add attachment with empty name (useful when forwarding an e-mail as attachment).
  • Removed references and dependencies on outdated MessageCensor component (Message.GetCensoredBody method removed).
  • POP3.RetrieveMessages and POP3.RetrieveHeaders methods now let you specify the range of messages to download.
  • New SMTP.GetLastDataFromClient and SMTP.GetLastDataFromServer methods along with SMTP.OnSendData and SMTP.OnReceiveData events let you keep track of any data transfer during the SMTP session.
  • New Email parameter in SMIME.AddRecipientCert and SMIME.SelectSenderCert lets you select certificates by e-mail address.
  • New CertInfo.Email property which lets the application determine the e-mail address of the certificate used to sign the message being verified.
  • A number of fixes and improvements to MIME parser, MIME builder, S/MIME functionality, and Uploader class.
  • New sample projects for Visual C++ (added IMAP Demo, SMTP Demo, POP3 Demo with UIDs support). Some VB6 demo projects revised and improved.
  • Documentation fixes.

7.0

  • Added IPv6 support for all components (SMTP, IMAP4, POP3).
  • DSN (Delivery Status Notification) support for SMTP component.
  • Auto-Detection of whether STARTTLS is supported, for SMTP component.
  • GetLastReceivedDataChunk methods for IMAP4 and POP3 components to monitor data being received.
  • IMAP4.OnEnvelopeDownloaded event lets you start processing e-mails and envelopes not while some messages/envelopes are still downloaded.
  • IMAP4.SetFlagsForMessageAsString and IMAP4.AppendMessage methods allow using non-standard IMAP message flags (like $Spam, \Starred, and so on).
  • Envelope.FlagsAsString property returns all the flags set for the message, including non-standard ones.
  • Support of multiple HTML bodies in the message (such as e-mails created by Apple Mail).
  • Message.ImportFromMemory method to load the entire message from byte array.
  • Documentation fixes and improvements.
  • New license keys (you need to upgrade your key to use the new version).

6.0

  • SSL component is now free functionality (SSL license is no longer required) for all mailer components (SMTP, POP3, IMAP4). Using SSL component made simpler, no need to create an SSL object, just set Mailer.SSL.Enabled = True to enable SSL.
  • NTLM authentication for all mailer component rewritten from the ground up and now uses SSPI interface. This allows for better compatibility with MS Exchange 2007/2010 and other MS products.
  • Integrated Windows Authentication now supported (no need to specify username if you want to log in the currently logged Windows user).
  • GSSAPI (over NTLM and over Kerberos) is now supported. GSSAPI is the only supported method in Exchange 2010 IMAP/POP3.
  • UserDomain and TargetName properties added to all mailer component to further support new authentication methods.
  • IMAP4.RetrieveMailboxesEx method now supports XLIST extension which enables support of special folder flags (like Sent, Drafts, Spam, Trash).
  • New IMAP4.GetCapabilities method to obtain the list of all extensions supported by the IMAP4 server.
  • New SMTP.IsQueueIIS property to workaround an issue with IIS SMTP pickup folder service which cannot double dots at the beginning of lines in .EML files being submitted to this queue with SMTP.SendToQueue or SMTP.SendToQueueEx methods.
  • Documentation fixes and improvements.
  • New license keys (you need to upgrade your key to use the new version).
  • .NET (C#, VB.NET, ASP.NET) samples removed. MailBee.NET Objects library performs much better for this purpose.

5.8.5

  • SaveKey utility (saves MailBee license key in the registry) is now also available for Windows Vista/2008/Seven (32-bit and 64-bit).
  • IMAP search now works with AOL (which produces RFC-incompliant SEARCH responses).
  • Misc. fixes to SSL layer and MIME parsing.

5.8

  • New Message.RemoveCharsetFromBody method which clears the charset information from the HTML body (useful when converting the charset of the body, for instance, when making UTF-8 e-mails).
  • Message.EncodeHeaderText method can also be used to encode attachment filenames.
  • Greatly improved IMAP performance for large e-mails.
  • New and improved code samples for Borland Delphi (Simple and Advanced Demos for SMTP, IMAP4 Demo and improved POP3 Demo with SSL/Gmail support).
  • SSL support (required for Gmail and other SSL-only services) added to Visual Basic 6 samples (POP3, IMAP and SMTP demos).
  • SSL/SMIME objects can now read the license key from the registry (previously saved with SaveKey tool).
  • SMTP component can now be reused after issuing Abort method.

5.7

  • IMAP IDLE support (see IMAP4.Idle method).
  • IMAP QUOTA support (see IMAP4.GetMailboxQuota method).
  • Smart parsing mode for not-well written IMAP servers allows MailBee to tolerate many errors in responses from such servers and produce IMAP requests which are easier to understand for such servers (see IMAP4.SmartParsing property).
  • New CodepageMode option to avoid charset conversions on attachments (see Message.CodepageMode, also applies to POP3.CodepageMode and IMAP4.CodepageMode). Deprecated in MailBee Objects v8.
  • Improvements and bugfixes to HTML-to-plaintext conversion, documentation and samples.

5.6

  • 64-bit version added.
  • DNS MX, SSL, NTLM and MIME fixes.
  • MailBee IMAP Demo 2 sample code fixes (C# and VB.NET version).
  • Delphi POP3 Demo sample code improvements.

5.5.3

  • New value (-1) for BodyPreviewSize parameter of IMAP4.RetrieveEnvelopesEx method allows downloading entire messages without setting \Seen flag.
  • SSL data corruption error fixed.
  • Support of multiple plain-text bodies (earlier only the first body was available, now they all are concatenated).

5.5.2

  • MIME bug fixes.

5.5.1

  • Miscellaneous bug fixes and improvements to MIME, S/MIME, and documentation.

5.5

  • SMTP.SendToQueue and SMTP.SendToQueueEx methods now produce .EML files in IIS SMTP queue format instead of .MBM files. This makes it possible to use MailBee to submit e-mails to IIS SMTP queue as well as to MailBee Message Queue v1.4 or above.
  • New optional parameters for SMTP.GetRelayServerFromEmailAddress method.
  • Advanced support of UTF-7M mailbox names in IMAP4 component. UTF-7M names are now automatically encoded/decoded by default. See IMAP4.UTF7EncodeMailboxNames for details.
  • IMAP4 component can now ignore IMAP envelopes which cannot be parsed. See IMAP4.RetrieveEnvelopesEx method for details.
  • Decoding of MS-TNEF (winmail.dat) attachments. Message.DecodeMstnef method does this.
  • Message.ConvertCharset method for manual conversions of charset encodings, Message.CharsetOriginal property (deprecated in MailBee Objects v8) and new modes for charset conversions.
  • Support of non-standard (neither plain-text nor HTML) text bodies. The typical example is calendar items (such as vCal entries). See Message.SpecialBodyText property for details.
  • Automatic detection and extraction of attachments from "old-school" email messages which are not in MIME format (messages containing attachments embedded directly into the text body).
  • Lots of miscellaneous fixes and improvements to the component library, the samples, and the documentation.

5.4

  • SMIME object (made as a part of SSL/SMIME plugin). Now MailBee supports e-mails securing according to the S/MIME standard. Such features as digital signing of the new e-mails, verification of the digital signatures, e-mails encryption and decryption are now available. License keys of SSL plugin of previous versions will continue to work with SSL and SMIME objects of this version.
  • Message.AddMemoryAttachment method allows the developer to create an attachment directly from memory array and attach it to the message. This method is useful for database attachments (such as a binary, image, blob, or text field).
  • Message.AddStringAttachment method for creating an attachment from a string.
  • SMTP.GetRelayServerFromEmailAddress method returns the host name of the SMTP MX server for the specified e-mail address. Thus, the developer can use this method in order to implement sending a message
    to the destination SMTP server of the specified e-mail address without the need to authenticate on this server.
  • SMTP.ResolveHostName method extracts the IP address that is associated with the specified host name.
  • Multiple enhancements and bug fixes to message parser, IMAP response parser, international support facilities, etc.

5.3

  • MailBee moved to www.afterlogic.com, licensing policy updated, etc.
  • Ability to read license key from the registry. The utility to place the key there (SaveKey.exe) is supplied, too
  • Uploader component introduced (useful for uploading files in ASP)
  • MailBee Objects + SSL plugin now fully support GMail over Secure-POP3 and Secure-SMTP
  • SMTP.ExecuteCommand method allows sending user-defined commands to SMTP server
  • AuthMethod=16 option for SMTP, POP3, and IMAP4 objects to allow connection without authentication to get list of supported authentication methods
  • FilenameInMessage="<none>" value of Message.AddAttachment and SMTP.AddAttachment method allows to forward as attachment existing RFC822 email message
  • Message.MinimalRebuild property to allow alteration of headers of existing message without full recompilation of the entire message
  • Message.RemoveHeader method to remove headers from the message
  • IMAP4.SendDelay property to workaround problem with certain slow IMAP4 servers which cannot handle commands from MailBee as fast as MailBee generates them
  • IMAP4.UIDValidity property to obtain UIDValidity value of a mailbox
  • IMAP4.RetrieveMailboxesEx method to provide better control over mailboxes list retrieval process
  • MailBee log now prints how many messages/mailboxes have been retrieved
  • Fixed setting of incorrect error code on timeout
  • Fixed crash with multiple Content-Type headers in the same part of the message
  • Fixed crash with some UUEncoded attachments
  • Minor fixes to sample projects and the documentation

5.2

  • MailBee sample projects for VB6, ASP, VB.NET, VBA, C#, VC++, Delphi and ColdFusion added
  • Attachments.Remove and Attachments.RemoveAll methods for deleting attachments from the message
  • Message.RawHeader property returns RFC822 header of the message
  • Message.GetFriendlyName and Message.GetPureAddr methods return friendly name and pure e-mail address for any specified full e-mail address
  • Better support for Unicode-encoded e-mails
  • Better compatibility with IMAP4 servers
  • Better RFC822 Date decoding
  • Improved parsing of e-mails sent from mobile devices
  • Fixed bug with adding redundant angle brackets in attachment Content-ID if angle brackets were already there
  • Certificate-related methods of SSL plugin now return more correct error values
  • Fixed failure to establish SSL session with non-empty client certificate on second (or later) connection

5.1.1

  • MailBee events are now supported in pure scripting languages such as JavaScript or VBScript
  • More correct and faster e-mail address validation
  • A few SSL-related fixes
  • Better HTML-to-plain parsing for partially downloaded messages
  • Multiple enhancements to electronic documentation

5.1

  • IMAP4.AuthMethod property. Secure authentication options (CRAM-MD5, NTLM, MSN) is now available for IMAP4 object
  • IMAP4.AppendMessage method allows uploading messages into mailboxes on the IMAP4 server
  • IMAP4.SetFlagsForMessage method allows setting flags for messages on the IMAP4 server
  • POP3.GetMessageNumberFromUID method returns ordinal position of a message in given its Unique-ID
  • POP3.GetMessageUID method returns Unique-ID of a message in given its ordinal position in the mailbox
  • Better parsing of IMAP4 server responses
  • Improved "HTML to plain-text" conversion (for Message object)
  • MSN authentication now works properly with all MSN servers
  • Multiple minor fixes and enhancements of POP3 and IMAP4 objects
  • Great improvement and expansion of MailBee electronic documentation: dozens of new tutorials, code examples, and fixes

5.0

  • IMAP4 object. Now MailBee supports IMAP4 protocol. Many subordinate objects and collections added, such as Envelope, BodyPartStructure, Mailbox
  • SSL object. Now MailBee supports SSL/TLS secure communications for SMTP, POP3 and IMAP4 protocols including both dedicated port connections and STARTTLS regular port connections
  • POP3.Search method added. It returns array of unique-ids of all messages in mailbox. Extremely useful for: checking for new messages, read/unread messages, etc.
  • Message.ImportFromFile method allows you to load an e-mail message directly from a file
  • Message.ValidateEmailAddress method checks syntax of email address and optionally tests email address domain for existence
  • Message.GetFileAsArray method returns file content as binary array you can easily use with Response.Write ot organize efficient file download
  • Attachment.ContentAsArray property returns attachment's content as binary array, so you can download a file to the client without even writing it to disk
  • Cold Fusion now supported
  • Unicode can be used in both headers and body. See Message.ToUTF8 method for details
  • Methods for displaying and managing HTML-formatted email messages with embedded pictures and other objects: GetBodyWithEmbeddedObjects, GetBodyWithEmbeddedObjectsEx, RemoveMessageDirectory, GetMessageDirectoryPath, MessageDirectoryExists
  • Message.GetMD5Digest method for generating MD5 digests of text strings (also used for generating temporary directory names for storing embedded pictures)
  • POP3.Codepage and Message.Codepage properties for choosing desired codepage to convert headers and body (deprecated in MailBee Objects v8).
  • POP3.CodepageMode and Message.CodepageMode properties for choosing charset/codepage conversion method (deprecated in MailBee Objects v8).
  • Message.Date property added (instead of Message.MessageDate). Message.MessageDate is still available for compatibility
  • Message.XMailer property added. Now you may set your own "X-Mailer" value
  • "Date" header is automatically appended to the message
  • SMTP.SendEx method for sending messages from/to addresses different from those specified in the message itself
  • SMTP.SendToQueueEx method (queue-version of SendEx method)
  • Quoted-printable decoding issue fixed
  • Properly recognizes default charset for headers if it set within multipart body
  • Better Date field parsing
  • NTLM authentication now supports IIS SMTP
  • Default encoding is set to "Quoted-Printable" (instead of "No encoding")
  • Unique random MIME boundaries generated (instead of fixed ones)
  • Autoconnect/autodisconnect ability added to POP3/SMTP objects to simplify their usage
  • SendCommand now supports commands that return multi-line response (through ExpectMultilineResponse parameter)
  • POP3/SMTP objects now respond to "connection closed by remote side" event much quicker
  • Now Content-ID is taken from attachment headers even if the attachment is not expected to have Content-ID (but does have it)
  • Asynchronous mode enhancements (Busy property value is set and analyzed by POP3/SMTP objects with more accuracy)
  • Electronic documentation extended with "how-to" tutorials and code examples along with other enhancements

4.0

  • MailBee Objects library was substantially enhanced and optimized. Now it is implemented as standalone self-contained C++ ATL lightweight COM object. All speed-critical code sections are written in pure C (not even C++). New version operates up to 40 times faster (on certain operations), uses less memory during operation, has smaller file size, does not use any additional DLLs such as VB Runtime, Regular Expressions library, etc.
  • MailBee Objects redistributable now consists of a single file only (MailBee.dll) instead of 3 files in 3.x versions.
  • MessageCensor is moved from MailBee Objects into separate free component
  • MailBee Message Queue (MMQ) system is now supported by MailBee Objects. Using this system allows SMTP component operate very quickly by off-loading task of delivering mail to MMQ, which operates in a background as Windows service
  • Help Reference has been completely rewritten
  • New installer with modern user interface
  • Native Winsock2 API is used instead of object-oriented WinSock wrappers. This results in a greater speed, reliability and scalability of POP3 and SMTP connections
  • POP3 and SMTP objects can now fire events. This allows your applications to track and control operations progress
  • POP3 and SMTP objects now include Abort method, which allows you to quickly close connection (for example, when user presses Cancel button or when your application closes)
  • New ErrCode, ClientRequest, ServerResponse properties of POP3 and SMTP object give you much more information on current mail session status
  • Log messages have been completely revised for POP3 and SMTP objects
  • POP3 object now provides TotalSize and Size(Index) properties which allow to determine total size of all messages in the mailbox or the size of particular message without even downloading messages headers
  • POP3 can now download messages partially (i.e. message headers + part of message body). See BodyLinesCount parameter info in RetrieveHeaders and RetrieveSingleMessageHeaders topics
  • POP3.Ping method allows you to keep connection alive while staying connected for a long time. This method sends "noop" command to POP3 server
  • POP3.SendCommand method allows you to send custom request to POP3 server and get server response
  • SMTP object can now send any Message objects (for example, those created by POP3 object) through assigning of Message property. Thus you can easily implement forwarding and redirecting messages
  • SMTP.Domain property allows you to explicitly specify sender's domain (argument of HELO command)
  • SMTP.Message.FromAddr property is now used to determine sender's domain if Domain property is empty. If FromAddr is also empty, current machine hostname is used
  • SMTP.SendToQueue method is used to send messages to MailBee Message Queue system. When using this method, you do not even need to Connect or Disconnect to/from SMTP server
  • SMTP.SendEx method allows blind-forwarding (sending from/to addresses different from specified in the message headers)
  • Message object can now be created explicitly (through CreateObject). You can create Message object, assign its Message.RawBody property (to content of a message file, for example) and get completely parsed Message object. This also works in reverse manner: if you modify some of message properties and then get RawBody property, it will be updated to take into account last properties changes
  • Message object can now be edited (and includes corresponding methods and properties). If you got it, for example, from POP3 object, you can clear "read-only" mode by setting Message.Locked = False, and then start changing message properties
  • Message object includes new GetDateFromString method that allows you to get Date data type presentation of date strings (such as Date message header)
  • Attachment object now includes IsMessage property that allows you to determine whether this attachment holds another MIME message inside. If so, you can create Message object and load Attachment.Content into Message.RawBody to access embedded message properties
  • Attachment.SaveFile method now returns Boolean result instead of Long
  • Attachments and Messages collections now support "For Each" syntax to iterate through collection members
  • GetPlainFromHtml and GetHtmlFromPlain methods of Message object allow you to manually construct plain version of html content and vice versa
  • PureToAddr, PureFromAddr, PureCCAddr methods of Message object now operate handle much more situations
  • FromFriendlyName, ToFriendlyName, CCFriendlyName methods added to the Message object
  • "Html to plain text" algorithm has been completely revised and now provides much better formatted text
  • Removed some outdated methods and properties of POP3 object that were deprecated and hidden in MailBee 3.x
  • Multiple minor fixes to message parsing and composing engine

3.0.2

  • Added optional parameter FilenameInMessage to SMTP.AddAttachment method
  • Added optional BodyLinesCount parameter to POP3.RetrieveHeaders, POP3.RetrieveSingleMessageHeaders methods
  • Fixed timeout-related problems in SMTP object

3.0.1

  • PureFromAddr, PureToAddr, PureCCAddr properies of Message Object to get pure addresses (without friendly names)
  • Minor documentation fixes

3.0

  • Brand new SMTP object introduced! Create your own e-mail messages with html-formatting and attachment capabilities, and send them to SMTP servers
  • PopMailer object replaced with POP3 object. New POP3 object works much faster and provides new easier to understand interface
  • Attachment object's property File replaced with IsInline property
  • Some propeties of Message object were renamed: MessageTo -> ToAddr, From -> FromAddr, CC -> CCAddr
  • Now alternative body is plain version of html body. Corresponding changes to property names of Message object are: AltBody -> BodyText, Body -> AltBodyText. Now BodyText property always holds the richest available body of the message. AltBodyText is plain-text version of BodyText or empty if BodyText already has plain-text format
  • Many minor bug fixes

2.7

  • Brand new MessageCensor object introduced! Filter your html-fromatted mail messages or any other html sources to get rid of embedded scripts, popups, ActiveXes, applets and any other potentially dangerous or importunate stuff. MessageCensor object comes with a predefined set of censorship rules applicable for the most cases and provides ways to alter the rules or set new ones
  • Fix to message decoder engine (an issue which caused some mails to be unrecognized at all)

2.6

  • Improved plain body generation (for html-only messages)
  • Fixed issue "empty attachment body"
  • Content-ID header is now supported for attachments. ContentID property and GetPureContentID method were introduced
  • Size property has been added to Attachment object. Returns attachment size (in bytes)
  • Message object now supports CC property (content of CC message header)
  • FAQ and Version History were added to help system

2.5

  • Message.Size property was introduced. It is set to correct value even if only headers are received
  • Message.HasAttachments property was introduced. It is useful to determine whether a message contains any attachments if only headers are received
  • Message.RawBody property fixed
  • POPMailer.ReceiveMailHeaders method at very fast connection speed issue fixed

2.4

    First commercially available version

2.3 and earlier

  • Used in contract-based and in-house developments only


Overview

MailBee Objects is a set of powerful and easy to use ActiveX/COM components intended for usage in your Windows and classic ASP web pages to get email messages from Internet servers using POP3/IMAP4 protocols or send them via SMTP protocol, including converting e-mail messages from or into MIME format.

MailBee Objects contain several objects and collections:

  • POP3 object is created by the user. It connects to POP3 server (including OAuth 2.0, APOP, NTLM, MSN, GSSAPI/NTLM, GSSAPI/Kerberos secure authentication), retrieves messages and creates Message objects. You can get all messages at once (in this case POP3 returns you Messages collection), or you can receive particular message (and get single Message object)
  • IMAP4 object is created by the user. It connects to IMAP4 server, authenticates (using regular auth, OAuth 2.0, NTLM, etc), retrieves messages or message envelopes. Envelope is a customizable set of data which can contain the message itself (or its headers) and a number of other data fields, like read/unread status of the message.
  • SMTP object is created by the user. It connects to SMTP server (secure authentication and OAuth 2.0 is also available), sends composed or relays previously saved to disk messages
  • Message object includes properties to access message headers ("From", "Subject", etc.) and collection of e-mail attachments (Attachments property). Message objects used for both email retrieval and sending (POP3/IMAP4 objects create them for you, while you may create them for SMTP object)
  • Attachment object represents message attachment. Message object can hold an unlimited number of the attachments in Attachments collection
  • SSL object is always available through SSL property of a mailer object (SMTP, POP3, or IMAP4 object)
  • SMIME object is created by the user. This object allows e-mails securing according to the S/MIME standard. Message object is processed using the properties and methods of the SMIME object (such as Encrypt, Decrypt, Sign, etc)

MailBee.POP3, MailBee.IMAP4, MailBee.SMTP and MailBee.SMIME objects have LicenseKey property. When you purchase the entire MailBee Objects bundle, you get the licenses for all of them. If you purchase only a single component, you get the license for that component only. All other objects have no license keys and are always available for use regardless which license you own.

MailBee.POP3 object allows you to write e-mail managing and retrieving engine in just a few seconds. MailBee.POP3 automatically performs complex operations such as splitting message into parts, decoding headers and body from various MIME-encodings (Base64, quoted-printable, UUE), converting the message body and headers from local charsets to Unicode. With MailBee.POP3, you have access to both raw and decoded message content, and can do everything with it - save to database, to disk, or even modify message properties and then send the message with MailBee.SMTP object.

MailBee.IMAP4 is a version of MailBee.POP3 object for IMAP4 mail protocol. It supports advanced IMAP4 features such as message envelopes and body structures, message search, looking for new/unread/recent messages, multiple mailboxes, and much more.

MailBee.SMTP object is an easy to use tool to create and send e-mail messages. It supports creating both plain-text and html-formatted messages with attachments and inline objects (including automatic alternative body creation, automatic scanning and adding attachments for specified html source and much more). MailBee.SMTP also allows you to use secure authentication to SMTP servers.

MailBee.SMTP object can be extended with external MailBee Message Queue (legacy) or MailBee .NET Queue (modern) systems to enable message queuing that can noticeably improve performance of email sending applications or web pages. MailBee.NET Queue (needs .NET Framework) has more features and supports SSL. Alternatively, if your mail server is IIS SMTP, you can submit messages directly into its pickup folder (like CDONTS does).

Both MailBee.POP3, MailBee.IMAP4 and MailBee.SMTP objects support event firing for better control of the requested operations and logging capabilities (in many cases logging might noticeably simplify debugging and development).

SSL property of every mailer class allows you to implement secure communications mode 2 lines of code: enabling SSL object with Mailer.SSL.Enabled=True and setting PortNumber property of Mailer object (which can be an instance of SMTP, POP3 or IMAP4 class). Alternatively, instead of changing PortNumber, you can set SSL.UseStartTLS to use secure connection on a regular port). Also, SSL object can be easily configured and tweaked if needed. You can not only make it use regular port communications (secure communication on the same port as regular communication) instead of dedicated port, but also search or check certificates, force specific security protocols, and more. The best supported protocol is TLS 1.2.

MailBee.SMIME object allows you to secure your e-mails easily by using the digital certificates. This object allows you to add the digital signatures to new messages; to encrypt the messages; to verify digital signatures of received messages and to decrypt these messages; to manage the digital certificates of the message senders and recipients.


MailBee Objects Features

POP3 Object

  • Supports secure authentication methods (including OAuth 2.0, APOP, NTLM, GSSAPI/NTLM, GSSAPI/Kerberos, Integrated Windows Authentication)
  • Supports Office 365, Gmail, and other providers.
  • Can retrieve all messages as a collection, retrieve only headers for each message, headers + part of message body
  • Can retrieve any single particular message or its headers
  • Can detect total message count in the mailbox, total size of all messages and sizes of every message. All of above does not require messages or headers retrieval
  • Automatically parses retrieved messages and headers (decoding from base64/quoted-printable/uue, converting data from local charset to Unicode, etc.)
  • Automatically creates plain-text version of HTML formatted message if plain version is not available in the message itself
  • Can determine whether a message contains attachments when downloading message headers only
  • Can delete messages from POP3 server
  • Supports logging POP3 session into the file
  • Can execute user-specified commands (SendCommand method)
  • Ping method allows you to implement "keep connection alive" function in your applications
  • Supports event mechanism to track retrieval progress (and abort retrieval if needed)
  • Supports message UIDs (unique-ids). This greatly simplifies programming task of detecting new mails, and dramatically decreases amount of data to be received from server for this purpose
  • Full and automatic support for Unicode and UTF-8. Supports international headers, attachment names, bodies, etc

IMAP4 Object

  • Supports Office 365, Gmail, and other providers.
  • Retrieves entire message, message header, message header and part of message body, message envelope and body structure
  • Searches messages that match specified criteria
  • Retrieves, selects and manages mailboxes (supports SPECIAL-USE, XLIST, CHILDREN extensions which enable special folder flags like Sent, Drafts, Spam, Trash)
  • Copies, uploads, sets flags, deletes messages on the IMAP4 server
  • Moves messages between mailboxes (the IMAP4 server must support MOVE extension)
  • Provides event notification mechanism and background processing
  • Supports logging IMAP4 session into the file
  • Executes user-supplied commands
  • Ping method for keeping connection alive
  • Idle method (the server must support IDLE extension)
  • GetMailboxQuota method (the server must support QUOTA extension)
  • Automatically decodes received messages from MIME format
  • Automatically generates plain-text version for HTML-only messages
  • Supports UIDs
  • Supports secure authentication methods (including OAuth 2.0, CRAM-MD5, NTLM, GSSAPI/NTLM, GSSAPI/Kerberos, Integrated Windows Authentication)
  • Full and automatic support for Unicode and UTF-8. Supports international headers, attachment names, bodies, etc
  • UTF-7M mailbox names
  • GetCapabilities method to obtain the list of extensions supported by the server

SMTP Object

  • Supports Office 365, Gmail, and other providers.
  • Can send any Message object to SMTP server
  • Can send messages to IIS SMTP queue or to MailBee Message Queue or MailBee.NET Queue system instead of direct sending to SMTP server. Using MailBee Message Queue (or its modern replacement MailBee.NET Queue) allows SMTP component to operate very quickly because messages are actually delivered in a background ("fire and forget" delivery)
  • Supports ESMTP authentication, including secure authentication methods (OAuth 2.0, CRAM-MD5, NTLM, GSSAPI/NTLM, GSSAPI/Kerberos, Integrated Windows Authentication)
  • Can relay (blind-forward) messages stored in disk files (RelayMessage method)
  • Supports creating plain-text and HTML messages. For HTML messages HTML Import option is available (it allows to export HTML files with embedded graphics, style-sheets, etc. in one ImportBodyText method call)
  • Provides method to add custom MIME-headers (AddHeader method)
  • Supports unlimited number of attachments
  • Full and automatic support for Unicode and UTF-8. Supports international headers, attachment names, bodies, etc.
  • Can preserve original formatting of plain-text keeping long lines unwrapped but still providing compatibility with MIME rules (BodyEncoding property)
  • Includes method MakeAltBody to create plain-text version of HTML body if plain-text version is not available
  • Supports logging SMTP session into the file
  • Supports event mechanism to track retrieval progress (and abort sending if needed)
  • Executes user-supplied commands
  • Can determine MX server for the specified e-mail address domain (allows for "direct send" without SMTP relay server)

SSL Object

  • Secure SSL/TLS communications for SMTP, POP3 and IMAP4 protocols
  • Both dedicated port and "STARTTLS over regular port" communications
  • SSL support is up to TLS 1.0/1.1/1.2
  • Client and server certificates. Trusted certificate check, search and select client certificate, option to automatically add server certificate to the store, custom certificate stores including registry and file stores
  • PFX support

SMIME Object

  • Can encrypt and decrypt e-mail messages using the different encrypting algorithms
  • Can sign e-mail messages with digital signatures and verify the integrity of these messages
  • Because SMIME object secures messages using Message object, all securing functionality of SMIME object also applies to the Message object
  • Provides properties and methods for managing the digital certificates that are used to secure the e-mails: trusted certificate check, search and select client certificate, add certificates to the specified store, custom certificate stores including registry and file stores
  • PFX support

Message Object

  • Available in all MailBee Objects packages (POP3, IMAP4, SMTP, Objects). Used as a main unit POP3/IMAP4 retrieval and SMTP sending methods operate with
  • Because SMTP object composes messages using Message object, all composing functionality of SMTP object also applies to Message object
  • Includes collection of a message's attachments
  • Provides access to custom message headers through GetHeader method
  • Can display HTML messages saving all necessary files
  • Can create HTML messages importing all necessary files
  • International character sets, Unicode, UTF-8, IDN domains fully supported
  • Can be created explicitly through CreateObject and then saved to disk or sent by SMTP object
  • Any content can be loaded to RawBody property (such as content of message file or attachment with message inside)
  • RawBody operates symmetrically: when you set Message properties or call Message-affecting methods (such as AddAttachment), RawBody will reflect this changes next time you read it; when you load RawBody with new value, other Message properties such as BodyText are refreshed
  • No redundant refreshes on RawBody. If you sequentially change some Message properties, RawBody will be updated only when you read it, not after every changing Message properties
  • E-mail address validation (both e-mail address syntax and domain MX lookup)

Attachment Object

  • Also available in all MailBee Objects packages as a part of Message object
  • Content of attachment is available directly through Content property. You do not have to save a file to disk first and then read it to get attachment content
  • SaveFile method allows you to easily save attachment content to disk
  • Supports international and encoded filenames
  • IsInline property allows to determine whether attachment is an object related in HTML message body (such as embedded image or CSS file) or not (i.e. attachment was explicitly added by the user)
  • ContentID and ContentType properties are also available


Sending e-mails (SMTP)

Troubleshooting | Solving typical problems of e-mail sending.
Simple e-mail | Sending a simple plain-text e-mail.
HTML e-mail | Sending an HTML-formatted e-mail.
HTML e-mail from a file | Sending an HTML e-mail exported from an HTML file.
Adding attachments | Sending an e-mail with an attachment.
Embedding images and files | Sending an e-mail with embedded pictures, sounds, scripts and style-sheets.
Adding custom headers | Sending an e-mail with user-defined headers.
Advanced e-mail | Sending a complex e-mail with multiple bodies, attachments and recipients.
International e-mail | Sending an e-mail with UTF-8 body and international characters in the subject.
SMTP Authentication | Sending an e-mail through the SMTP server that requires senders to authenticate themselves.
Mail merge and bulk e-mail (Simple) | Sending multiple personalized e-mails using database as a source of recipients info.
Mail merge and bulk e-mail (Advanced) | Sending multiple personalized e-mails with attachments using database as a source of recipients info.
Mail merge and bulk e-mail (Queuing) | Queuing multiple e-mails for background delivery with MailBee Message Queue or MailBee.NET Queue.
Forwarding message | Taking an e-mail from the POP3 account and resending it to another recipient.
Redirecting message | Taking an e-mail from the POP3 account and redirecting it to another recipient, leaving the original recipients in the message headers.
Bounced messages (SMTP part) | Sending an e-mail in a way to allow tracking bounced mails.
Handling events | Tracking the progress of e-mail sending and making user interface responsive while communicating with the SMTP server.
OAuth 2.0 authentication | Using OAuth 2.0 (XOAUTH2) to send email.

Send feedback to AfterLogic


Troubleshooting

Visual Basic Code | ASP Code

Common reason of the messages not being sent is one of the following:
  • Server requires SMTP authentication
  • Authentication failed (wrong UserName and/or Password, unsupported authentication method). You can try several common choices:
    • UserName=Account_name (e.g. "jdoe" if your e-mail address is "jdoe@domain.com")
    • UserName=E-Mail_address (e.g. "jdoe@domain.com")
    • Try different values for AuthMethod property (such as 1, 2, 3, 4, 5)
  • Specified server is not SMTP (ErrCode=4 in this case). For example, SMTP server name for "jdoe@domain.com" is usually somewhat like "mail.domain.com" or "smtp.domain.com" BUT NOT just "domain.com"
  • SMTP server rejects connections from your IP address
  • SMTP server is behind firewall
  • Specified "From:" address is not allowed by this server
  • Specified "To:" address is allowed only if the user has already passed SMTP authentication
  • Message size limit exceeded, traffic limit per connection exceeded, etc.
You can determine exact reason of the problem from MailBee's log file. To enable logging, set EnableLogging and LogFilePath properties of the SMTP object.

This sample sends simple e-mail using SMTP authentication. SMTP session log is written into "C:\Temp\smtp_log.txt" file.

[Visual Basic]:

Dim objSMTP

Set objSMTP = CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Enable SMTP authentication
objSMTP.AuthMethod = 2

' Set authentication credentials
objSMTP.UserName = "jdoe"
objSMTP.Password = "secret"

' Set message properties
objSMTP.FromAddr = "sender@firstdomain.com"
objSMTP.ToAddr = "recipient@seconddomain.com"
objSMTP.Subject = "Test"
objSMTP.BodyText = "Body of the test message"

' Try to send message
If objSMTP.Send Then
  MsgBox "Sent successfully"
Else
  MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
End If

[ASP]:

<%
Dim objSMTP

Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Enable SMTP authentication
objSMTP.AuthMethod = 2

' Set authentication credentials
objSMTP.UserName = "jdoe"
objSMTP.Password = "secret"

' Set message properties
objSMTP.FromAddr = "sender@firstdomain.com"
objSMTP.ToAddr = "recipient@seconddomain.com"
objSMTP.Subject = "Test"
objSMTP.BodyText = "Body of the test message"

' Try to send message
If objSMTP.Send Then
  Response.Write "Sent successfully"
Else
  Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
End If
%>
See Also:
ErrCode Property

Send feedback to AfterLogic


Simple e-mail

Visual Basic Code | ASP Code

The sample sends plain-text e-mail with no attachments.

For simplicity, SMTP authentication is not used and no error-checking is performed.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Hi"
objSMTP.BodyText = "This is test message"

' Send it!
objSMTP.Send

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Hi"
objSMTP.BodyText = "This is test message"

' Send it!
objSMTP.Send
%>
See Also:
Send Method

Send feedback to AfterLogic


HTML e-mail

Visual Basic Code | ASP Code

The sample sends HTML e-mail with no attachments.

SMTP.BodyFormat is a key property of the sample.

For simplicity, SMTP authentication is not used and no error-checking is performed.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Message in HTML format"

' Set HTML format for the body
objSMTP.BodyFormat = 1

' Place HTML contents into the body
objSMTP.BodyText = "<html>This word is <b>bold</b></html>"

' Send it!
objSMTP.Send

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Message in HTML format"

' Set HTML format for the body
objSMTP.BodyFormat = 1

' Place HTML contents into the body
objSMTP.BodyText = "<html>This word is <b>bold</b></html>"

' Send it!
objSMTP.Send
%>
See Also:
Send Method

Send feedback to AfterLogic


HTML e-mail from a file

Visual Basic Code | ASP Code

The sample sends HTML e-mail exported from an HTML file.

If the HTML file contains references to images, scripts, CSS files and other objects, they will be embedded with the e-mail as inline attachments.

SMTP.ImportBodyText is a key property of the sample.

For simplicity, SMTP authentication is not used and no error-checking is performed.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Message in HTML format"

' Export an HTML file into the e-mail message
objSMTP.ImportBodyText "C:\docs\letter.htm", True

' Send it!
objSMTP.Send

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Message in HTML format"

' Export an HTML file into the e-mail message
objSMTP.ImportBodyText "C:\docs\letter.htm", True

' Send it!
objSMTP.Send
%>
See Also:
Send Method

Send feedback to AfterLogic


Adding attachments

Visual Basic Code | ASP Code

The sample sends plain-text e-mail with 2 attachments.

First attachment is placed into the message under its natural name. Second attachment is placed under different name (this is often used when attachments are added from temporary files).

SMTP.AddAttachment is a key property of the sample.

For simplicity, SMTP authentication is not used and no error-checking is performed.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Hi"
objSMTP.BodyText = "This is test message with attachments"

' Add attachment from "file1.doc" file.
' It will appear as "file1.doc" in the e-mail.
objSMTP.AddAttachment "C:\files\file1.doc"

' Add attachment from "file2.tmp" file.
' It will appear as "renamed.doc" in the e-mail.
objSMTP.AddAttachment "C:\files\file2.tmp", , ,"renamed.doc"

' Send it!
objSMTP.Send

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Hi"
objSMTP.BodyText = "This is test message with attachments"

' Add attachment from "file1.doc" file.
' It will appear as "file1.doc" in the e-mail.
objSMTP.AddAttachment "C:\files\file1.doc"

' Add attachment from "file2.tmp" file.
' It will appear as "renamed.doc" in the e-mail.
objSMTP.AddAttachment "C:\files\file2.tmp", , ,"renamed.doc"

' Send it!
objSMTP.Send
%>
See Also:
Send Method

Send feedback to AfterLogic


Embedding images and files

Visual Basic Code | ASP Code

The sample sends HTML message with embedded image.

Although it is possible to embed files (usually images) indirectly (by importing HTML file which references them, see HTML e-mail from a file sample), you can still embed them manually.

Embedded objects are attachments referenced in the message body: images, sounds, scripts, style-sheets and all other files required to properly display the message body.

In the message body, embedded objects are related through Content-IDs (CIDs). Thus, Content-ID in the body must match Content-ID of attachment that holds the embedded object.

In the sample code, embedded image is added as attachment with Content-ID set to "pic1". The message body contains <IMG> tag with SRC="cid:pic1". This will cause HTML-capable mail clients to display embedded image in this <IMG> tag.

For simplicity, SMTP authentication is not used and no error-checking is performed.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "HTML message with embedded image"

' Set HTML format for the body
objSMTP.BodyFormat = 1

' Place HTML contents (IMG tag) into the body
objSMTP.BodyText = "<html><img src='cid:pic1'></html>"

' Embed image (add as attachment with Content-ID value set)
objSMTP.AddAttachment "C:\images\signature.jpg", ,"pic1"

' Send it!
objSMTP.Send

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "HTML message with embedded image"

' Set HTML format for the body
objSMTP.BodyFormat = 1

' Place HTML contents (IMG tag) into the body
objSMTP.BodyText = "<html><img src='cid:pic1'></html>"

' Embed image (add as attachment with Content-ID value set)
objSMTP.AddAttachment "C:\images\signature.jpg", ,"pic1"

' Send it!
objSMTP.Send
%>
See Also:
AddAttachment Method

Send feedback to AfterLogic


Adding custom headers

Visual Basic Code | ASP Code

The sample sends plain-text e-mail with "Organization:" field set in the headers.

SMTP.AddHeader is a key method of the sample.

For simplicity, SMTP authentication is not used and no error-checking is performed.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Hi"
objSMTP.BodyText = "This is test message with custom headers"

' Add "Organization" header
objSMTP.AddHeader "Organization", "Corporation, Inc."

' Send it!
objSMTP.Send

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Hi"
objSMTP.BodyText = "This is test message with custom headers"

' Add "Organization" header
objSMTP.AddHeader "Organization", "Corporation, Inc."

' Send it!
objSMTP.Send
%>
See Also:
AddAttachment Method

Send feedback to AfterLogic


Advanced e-mail

Visual Basic Code | ASP Code

The sample sends HTML e-mail with alternative plain-text version (for HTML-incapable readers), attachments and custom headers to several recipients.

HTML part of the e-mail is constructed from 3 parts. The header and the footer are exported from HTML files (with their embedded objects, if any). Main HTML content is manually generated.

Alternative plain-text version of the HTML content is generated by SMTP.Message.MakeAltBody method.

Additionally, regular (not inline) attachment is added to the e-mail.

The e-mail has several recipients of various types (To, CC, BCC), different Reply-To and From headers, friendly names and comments in some of e-mail addresses.

Full syntax (e.g. SMTP.Message.ToAddr instead of SMTP.ToAddr shortcut) is used to set properties of the message to be sent by SMTP object. Using full syntax allows accessing all methods and properties of the Message object that SMTP component sends.

If required, SMTP authentication can be enabled by uncommenting corresponding lines. Logging is enabled by default, error-checking is performed.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Uncomment the following 3 lines to enable SMTP authentication
' objSMTP.AuthMethod = 2
' objSMTP.UserName = "jdoe"
' objSMTP.Password = "secret"

' Set "From:", "Reply-To:", "To:", "CC:", "BCC:", "Subject:" fields
objSMTP.Message.FromAddr = "John Doe <jdoe@some.com> (Some Company)"
objSMTP.Message.ReplyToAddr = "Foo Company Support Team <support@some.com>"
objSMTP.Message.ToAddr = "Bill Johnes <bill.johnes@domain1.com>, someone@domain2.com (Another company)"
objSMTP.Message.CCAddr = "Management Department <man@some.com> (Some Company), stat@statserver.some.com"
objSMTP.Message.BCCAddr = "Big.Brother@secretservice.com, Mr. X <collect_secrets@competitorcompany.com>"
objSMTP.Message.Subject = "Complex message"

' Set HTML format of the body
objSMTP.Message.BodyFormat = 1

' Construct HTML body: header from file + main part + footer from file

' Export the header into HTML body
objSMTP.Message.ImportBodyText "C:\docs\letter.htm", True

' Append main part to HTML body
objSMTP.Message.BodyText = objSMTP.BodyText & "<p>This is main part</p>"

' Export the footer into HTML body. AppendMode is True,
' so exported content will not overwrite existing body
objSMTP.Message.ImportBodyText "C:\docs\letter.htm", True, True

' HTML body ready, generate plain-text version
objSMTP.Message.MakeAltBody

' Add attachment from the file
objSMTP.Message.AddAttachment "C:\My documents\report.xls"

' Add custom header
objSMTP.Message.AddHeader "X-Special", "Something"

' Try to send message
If objSMTP.Send Then
  MsgBox "Sent successfully"
Else
  MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
End If

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Uncomment the following 3 lines to enable SMTP authentication
' objSMTP.AuthMethod = 2
' objSMTP.UserName = "jdoe"
' objSMTP.Password = "secret"

' Set "From:", "Reply-To:", "To:", "CC:", "BCC:", "Subject:" fields
objSMTP.Message.FromAddr = "John Doe <jdoe@some.com> (Some Company)"
objSMTP.Message.ReplyToAddr = "Foo Company Support Team <support@some.com>"
objSMTP.Message.ToAddr = "Bill Johnes <bill.johnes@domain1.com>, someone@domain2.com (Another company)"
objSMTP.Message.CCAddr = "Management Department <man@some.com> (Some Company), stat@statserver.some.com"
objSMTP.Message.BCCAddr = "Big.Brother@secretservice.com, Mr. X <collect_secrets@competitorcompany.com>"
objSMTP.Message.Subject = "Complex message"

' Set HTML format of the body
objSMTP.Message.BodyFormat = 1

' Construct HTML body: header from file + main part + footer from file

' Export the header into HTML body
objSMTP.Message.ImportBodyText "C:\docs\letter.htm", True

' Append main part to HTML body
objSMTP.Message.BodyText = objSMTP.BodyText & "<p>This is main part</p>"

' Export the footer into HTML body. AppendMode is True,
' so exported content will not overwrite existing body
objSMTP.Message.ImportBodyText "C:\docs\letter.htm", True, True

' HTML body ready, generate plain-text version
objSMTP.Message.MakeAltBody

' Add attachment from the file
objSMTP.Message.AddAttachment "C:\My documents\report.xls"

' Add custom header
objSMTP.Message.AddHeader "X-Special", "Something"

' Try to send message
If objSMTP.Send Then
  Response.Write "Sent successfully"
Else
  Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
End If
%>
See Also:
MakeAltBody Method

Send feedback to AfterLogic


International e-mail

Visual Basic Code | ASP Code

The sample sends internationalized HTML e-mail:
  • The message's HTML body contains "Text" word printed in Simplified Chinese, Korean and Cyrillic. To allow mixing different languages in the same document, UTF-8 charset is used (UTF stands for "Unicode Transformation Format")
  • "Subject:" field contains "你好" ("Hello" in Simplified Chinese). Charset is "gb-2312"
  • "From:" field contains e-mail address whose friendly name is written in Cyrillic ("windows-1251" charset)
Note that you'll not need to do anything special (like using any of the properties and methods below) to enable international charsets in the message. The code below does this only for advanced purposes, like when you need to use non-UTF-8 in some parts of your e-mail.

SMTP.Message.ToUTF8 method is used to convert any text to UTF-8 charset. By default, MailBee already uses UTF-8 for outbound e-mails.

SMTP.Message.EncodeHeaderText method is used to encode particular headers into email-compliant form. Encoding is required if the header text:
  • exceeds maximum allowed length (> 60 chars)
  • contains extended characters which cannot be represented in 7bit chars. Some old e-mail gateways do not support extended characters
  • presented in charset different from the message body's charset (e.g. the body is "UTF-8" and the Subject is "gb-2312")
  • contains multi-line text
  • note that MailBee by default automatically encodes all the headers with international characters because SMTP.Message.AutoEncodeHeaders is True.
SMTP.Message.Charset property specifies charset of the body. This charset is also used as default charset for the headers.

For simplicity, SMTP authentication is not used and no error-checking is performed.

[Visual Basic]:

Dim objSMTP, strTemp

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Encode "From:" value as Cyrillic
strTemp = objSMTP.Message.EncodeHeaderText("From", "Почта <postmaster@domain.com>", "windows-1251", 2)

' Assign encoded "From:" value to corresponding header
objSMTP.Message.FromAddr = strTemp

' Set "To:" value, no encoding is required here
' since no international characters were used
objSMTP.Message.ToAddr = "recipient@anotherdomain.com"

' Encode "Subject:" value as Simplified Chinese
strTemp = objSMTP.Message.EncodeHeaderText("Subject", "你好", "gb-2312", 3)

' Assign encoded "Subject:" value to corresponding header
objSMTP.Message.Subject = strTemp

' Set HTML format for the body
objSMTP.Message.BodyFormat = 1

' Mark that body content is composed with UTF-8 charset
objSMTP.Message.Charset = "UTF-8"

' Compose HTML body using UTF-8 charset:

' Prepare HTML HEAD section. ToUTF8 is used here for clarity only
' (since UTF-8 representation of US characters is the same as their
' native representation)
strTemp = objSMTP.Message.ToUTF8("<html><head>" & _
  "<meta content=""text/html; charset=UTF-8"" http-equiv=Content-Type>" & _
  "</head><body>" & _
  "Word ""Text"" in Simplifed Chinese, Korean and Cyrillic:<br>")

' Print "Text" in Simplified Chinese
strTemp = strTemp & objSMTP.Message.ToUTF8("ОД±ѕ<br>", "gb2312")

' Print "Text" in Simplified Korean
strTemp = strTemp & objSMTP.Message.ToUTF8("їшє»<br>", "EUC-KR")

' Print "Text" in Cyrillic
strTemp = strTemp & objSMTP.Message.ToUTF8("Текст</body></html>", "windows-1251")

' Assign UTF-8 content to the message body
objSMTP.Message.BodyText = strTemp

' Send the message
objSMTP.Send

[ASP]:

Dim objSMTP, strTemp

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Encode "From:" value as Cyrillic
strTemp = objSMTP.Message.EncodeHeaderText("From", "Почта <postmaster@domain.com>", "windows-1251", 2)

' Assign encoded "From:" value to corresponding header
objSMTP.Message.FromAddr = strTemp

' Set "To:" value, no encoding is required here
' since no international characters were used
objSMTP.Message.ToAddr = "recipient@anotherdomain.com"

' Encode "Subject:" value as Simplified Chinese
strTemp = objSMTP.Message.EncodeHeaderText("Subject", "你好", "gb2312", 2)

' Assign encoded "Subject:" value to corresponding header
objSMTP.Message.Subject = strTemp

' Set HTML format for the body
objSMTP.Message.BodyFormat = 1

' Mark that body content is composed with UTF-8 charset
objSMTP.Message.Charset = "UTF-8"

' Compose HTML body using UTF-8 charset:

' Prepare HTML HEAD section. ToUTF8 is used here for clarity only
' since UTF-8 representation of US characters is the same as their
' native representation
strTemp = objSMTP.Message.ToUTF8("<html><head>" & _
  "<meta content=""text/html; charset=UTF-8"" http-equiv=Content-Type>" & _
  "</head><body>" & _
  "Word ""Text"" in Simplifed Chinese, Korean and Cyrillic:<br>")

' Print "Text" in Simplified Chinese
strTemp = strTemp & objSMTP.Message.ToUTF8("ОД±ѕ<br>", "gb2312")

' Print "Text" in Simplified Korean
strTemp = strTemp & objSMTP.Message.ToUTF8("їшє»<br>", "EUC-KR")

' Print "Text" in Cyrillic
strTemp = strTemp & objSMTP.Message.ToUTF8("Текст</body></html>", "windows-1251")

' Assign UTF-8 content to the message body
objSMTP.Message.BodyText = strTemp

' Send the message
objSMTP.Send
See Also:
Charset Property
EncodeHeaderText Method
ToUTF8 Method

Send feedback to AfterLogic


SMTP Authentication

Visual Basic Code | ASP Code

The sample sends simple e-mail using SMTP authentication.

Many mail servers allow sending e-mails from authenticated users only. To authenticate, you need to specify your user account name, the password and the authentication method.

Authentication methods can be of two types: secure (password is transmitted to the server in secure format) and insecure (password is transmitted as plain-text). Many SMTP servers support insecure methods only.

SMTP object supports several authentication methods (both secure and insecure) through AuthMethod property. Some of them may be not supported by particular SMTP server.

[Visual Basic]:

Dim objSMTP, strTemp

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Use LOGIN Authentication method (insecure, but
' supported by nearly all SMTP servers)
objSMTP.AuthMethod = 2

' Set authentication credentials
objSMTP.UserName = "jdoe"
objSMTP.Password = "secret"

' Set message properties
objSMTP.FromAddr = "sender@firstdomain.com"
objSMTP.ToAddr = "recipient@seconddomain.com"
objSMTP.Subject = "Test"
objSMTP.BodyText = "Body of the test message"

' Try to send message
If objSMTP.Send Then
  MsgBox "Sent successfully"
Else
  MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
End If

[ASP]:

Dim objSMTP, strTemp

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Use LOGIN Authentication method (insecure, but
' supported by nearly all SMTP servers)
objSMTP.AuthMethod = 2

' Set authentication credentials
objSMTP.UserName = "jdoe"
objSMTP.Password = "secret"

' Set message properties
objSMTP.FromAddr = "sender@firstdomain.com"
objSMTP.ToAddr = "recipient@seconddomain.com"
objSMTP.Subject = "Test"
objSMTP.BodyText = "Body of the test message"

' Try to send message
If objSMTP.Send Then
  Response.Write "Sent successfully"
Else
  Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
End If
See Also:
AuthMethod Property

Send feedback to AfterLogic


Mail merge and bulk e-mail (Simple)

Visual Basic Code | ASP Code

The sample sends multiple e-mails using single template and database.

For each message, actual values taken from the database substitute placeholders in the template. Thus, all e-mails will have the same look but will be still personalized.

The sample code connects to the MS Access database using ADO's Connection object. Then ADO's Recordset object is filled with the values from "emails" table. Each record of this table is then used to produce a single e-mail.

The code assumes the database is located in "C:\Docs\simple_merge.mdb" file, and "emails" table looks like the following:
id | email | first_name | last_name
1 | account@domain.com | John | Doe
2 | bill.smith@company.com | Bill | Smith
3 | Kate@site.com | Kate | Jones
Note 1: The sample sends all e-mails over single SMTP connection (this provides maximum performance). However, some SMTP servers allow sending only a few e-mails over the same connection. See Advanced sample for details.

Note 2: To reduce response time of your mass-sending application, you can tell MailBee to send e-mail in the background. See Queuing sample for details.

[Visual Basic]:

' Mailer object
Dim objSMTP

' ADO Connection object
Dim objConn

' ADO Recordset object
Dim rsEmails

' Merge patterns (Body and "To:", all other fields remain
' unchanged for all e-mails in the mailing list)
Dim strBodyPattern, strToPattern

' Define body pattern
strBodyPattern = "Hello %%FIRST_NAME%%, " & vbCrLf & _
  "You are welcome to visit our site at:" & vbCrLf & _
  "http://www.site.com" & vbCrLf & vbCrLf & _
  "Sincerely, Site Team"

' Define "To:" pattern (will look like
' "John Doe <j.doe@domain.com>" in e-mail)
strToPattern = "%%FIRST_NAME%% %%LAST_NAME%% <%%EMAIL%%>"

' Create SMTP mailer component
Set objSMTP  = CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file. If any
' errors occur, the log can be used to investigate
' the problem.
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock mailer component
objSMTP.LicenseKey = "put your license key here"

' Specify SMTP server name
objSMTP.ServerName = "smtp.site.com"

' Comment next 3 lines if your SMTP server does not
' require SMTP authentication
objSMTP.AuthMethod = 2
objSMTP.UserName = "your mail account name"
objSMTP.Password = "your mail account password"

' Connect to the server. We use single connection
' for sending all e-mails in the database.
If objSMTP.Connect Then
  ' Plain-text e-mail. Change to 1 to send HTML e-mail
  objSMTP.BodyFormat = 0

  ' Specify "From:" and "Subject:". They remain unchanged
  ' for all the e-mails.
  objSMTP.Message.FromAddr = "Site Team <sales@site.com>"
  objSMTP.Message.Subject = "Invitation"

  ' Create ADO Connection object
  Set objConn  = CreateObject("ADODB.Connection")

  ' Connect to Access database
  objConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
    "Data Source=C:\Docs\simple_merge.mdb;"

  ' Create ADO Recordset object
  Set rsEmails = CreateObject("ADODB.Recordset")

  ' Open "emails" table. This table is
  ' actual data source for the merge
  rsEmails.Open "emails", objConn

  ' Loop through the table
  While Not rsEmails.EOF

    ' Merge body pattern and actual data
    ' from the database
    objSMTP.Message.BodyText = strBodyPattern
    objSMTP.Message.BodyText = Replace(objSMTP.Message.BodyText, "%%FIRST_NAME%%", rsEmails("first_name"))

    ' Merge "To:" pattern and actual data
    ' from the database
    objSMTP.Message.ToAddr = strToPattern
    objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%FIRST_NAME%%", rsEmails("first_name"))
    objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%LAST_NAME%%", rsEmails("last_name"))
    objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%EMAIL%%", rsEmails("email"))

    ' Try to send e-mail
    If Not objSMTP.Send Then
      ' Notify user on sending error
      MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
    End If

    ' Proceed with the next record in the table
    rsEmails.MoveNext
  Wend

  ' Close the table and the whole database
  rsEmails.Close
  objConn.Close

  ' Free database-related objects
  Set rsEmails = Nothing
  Set objConn = Nothing

  ' Disconnect from SMTP server
  objSMTP.Disconnect
Else
  ' Notify user on connection error
  MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
End If

[ASP]:

<%
' Mailer object
Dim objSMTP

' ADO Connection object
Dim objConn

' ADO Recordset object
Dim rsEmails

' Merge patterns (Body and "To:", all other fields remain
' unchanged for all e-mails in the mailing list)
Dim strBodyPattern, strToPattern

' Define body pattern
strBodyPattern = "Hello %%FIRST_NAME%%, " & vbCrLf & _
  "You are welcome to visit our site at:" & vbCrLf & _
  "http://www.site.com" & vbCrLf & vbCrLf & _
  "Sincerely, Site Team"

' Define "To:" pattern (will look like
' "John Doe <j.doe@domain.com>" in e-mail)
strToPattern = "%%FIRST_NAME%% %%LAST_NAME%% <%%EMAIL%%>"

' Create SMTP mailer component
Set objSMTP  = Server.CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file. If any
' errors occur, the log can be used to investigate
' the problem.
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock mailer component
objSMTP.LicenseKey = "put your license key here"

' Specify SMTP server name
objSMTP.ServerName = "smtp.site.com"

' Comment next 3 lines if your SMTP server does not
' require SMTP authentication
objSMTP.AuthMethod = 2
objSMTP.UserName = "your mail account name"
objSMTP.Password = "your mail account password"

' Connect to the server. We use single connection
' for sending all e-mails in the database.
If objSMTP.Connect Then
  ' Plain-text e-mail. Change to 1 to send HTML e-mail
  objSMTP.BodyFormat = 0

  ' Specify "From:" and "Subject:". They remain unchanged
  ' for all the e-mails.
  objSMTP.Message.FromAddr = "Site Team <sales@site.com>"
  objSMTP.Message.Subject = "Invitation"

  ' Create ADO Connection object
  Set objConn  = Server.CreateObject("ADODB.Connection")

  ' Connect to Access database
  objConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
    "Data Source=C:\Docs\simple_merge.mdb;"

  ' Create ADO Recordset object
  Set rsEmails = Server.CreateObject("ADODB.Recordset")

  ' Open "emails" table. This table is
  ' actual data source for the merge
  rsEmails.Open "emails", objConn

  ' Loop through the table
  While Not rsEmails.EOF

    ' Merge body pattern and actual data
    ' from the database
    objSMTP.Message.BodyText = strBodyPattern
    objSMTP.Message.BodyText = Replace(objSMTP.Message.BodyText, "%%FIRST_NAME%%", rsEmails("first_name"))

    ' Merge "To:" pattern and actual data
    ' from the database
    objSMTP.Message.ToAddr = strToPattern
    objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%FIRST_NAME%%", rsEmails("first_name"))
    objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%LAST_NAME%%", rsEmails("last_name"))
    objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%EMAIL%%", rsEmails("email"))

    ' Try to send e-mail
    If Not objSMTP.Send Then
      ' Notify user on sending error
      Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc & "<br>"
    End If

    ' Proceed with the next record in the table
    rsEmails.MoveNext
  Wend

  ' Close the table and the whole database
  rsEmails.Close
  objConn.Close

  ' Free database-related objects
  Set rsEmails = Nothing
  Set objConn = Nothing

  ' Disconnect from SMTP server
  objSMTP.Disconnect
Else
  ' Notify user on connection error
  Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc & "<br>"
End If
%>
See Also:
Mail merge and bulk e-mail (Advanced)
Mail merge and bulk e-mail (Queuing)

Send feedback to AfterLogic


Mail merge and bulk e-mail (Advanced)

Visual Basic Code | ASP Code

The sample sends multiple e-mails with attachments using single template and database.

Two main differences from Simple version of the sample:
  • Supports e-mails which have optional parts such as attachments. E.g., some users will receive attachments while others will not
  • Limits number of e-mails sent over the single connection session. Useful when your SMTP server imposes such limitation
The code assumes the database is located in "C:\Docs\advanced_merge.mdb" file, and "emails" table looks like the following:
id | email | first_name | last_name | filename
1 | account@domain.com | John | Doe | 345.doc
2 | bill.smith@company.com | Bill | Smith |
3 | Kate@site.com | Kate | Jones | 377.doc
Note: Some SMTP servers limit maximum number of sends per second (not per connection). E.g, you can only send 5 e-mails per second from the same IP address. In this case, you can use queuing and background delivery with MailBee Message Queue or MailBee.NET Queue system. See Queuing sample for details.

[Visual Basic]:

' Mailer object
Dim objSMTP

' ADO Connection object
Dim objConn

' ADO Recordset object
Dim rsEmails

' Merge patterns (Body and "To:", all other fields remain
' unchanged for all e-mails in the mailing list)
Dim strBodyPattern, strToPattern

' Counter to limit number of sends per connection
Dim I

' Define body pattern
strBodyPattern = "Hello %%FIRST_NAME%%, " & vbCrLf & _
  "You are welcome to visit our site at:" & vbCrLf & _
  "http://www.site.com" & vbCrLf & vbCrLf & _
  "Sincerely, Site Team"

' Define "To:" pattern (will look like
' "John Doe <j.doe@domain.com>" in e-mail)
strToPattern = "%%FIRST_NAME%% %%LAST_NAME%% <%%EMAIL%%>"

' Create SMTP mailer component
Set objSMTP  = CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file. If any
' errors occur, the log can be used to investigate
' the problem.
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock mailer component
objSMTP.LicenseKey = "put your license key here"

' Specify SMTP server name
objSMTP.ServerName = "localhost"

' Comment next 3 lines if your SMTP server does not
' require SMTP authentication
objSMTP.AuthMethod = 2
objSMTP.UserName = "your mail account name"
objSMTP.Password = "your mail account password"

' Create ADO Connection object
Set objConn  = CreateObject("ADODB.Connection")

' Connect to Access database
objConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
   "Data Source=C:\Docs\advanced_merge.mdb;"

' Create ADO Recordset object
Set rsEmails = CreateObject("ADODB.Recordset")

' Open "emails" table. This table is
' actual data source for the merge
rsEmails.Open "emails", objConn

' Initialize counter to connect to SMTP
' server before sending any e-mails
I = 1

' Loop through the table
Do While Not rsEmails.EOF

  ' Connect to the server. We connect only one time
  ' per 10 sends and reuse existing connection for
  ' subsequent 9 e-mails.
  If I = 1 Then
    If Not objSMTP.Connect Then
      ' Notify user on connection error and exit
      MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
      Exit Do
    End If
  End If

  ' Set all properties for each e-mail.
  ' This is required because we will reset
  ' the message later to free Attachments
  ' collection.

  ' Plain-text e-mail. Change to 1 to send HTML e-mail
  objSMTP.BodyFormat = 0

  ' Specify "From:" and "Subject:". They remain unchanged
  ' for all the e-mails.
  objSMTP.Message.FromAddr = "Site Team <sales@site.com>"
  objSMTP.Message.Subject = "Invitation"

  ' Merge body pattern and actual data
  ' from the database
  objSMTP.Message.BodyText = strBodyPattern
  objSMTP.Message.BodyText = Replace(objSMTP.Message.BodyText, "%%FIRST_NAME%%", rsEmails("first_name"))

  ' Merge body pattern and actual data
  ' from the database
  objSMTP.Message.ToAddr = strToPattern
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%FIRST_NAME%%", rsEmails("first_name"))
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%LAST_NAME%%", rsEmails("last_name"))
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%EMAIL%%", rsEmails("email"))

  ' Add attachment if required
  If rsEmails("filename") <> "" Then
    objSMTP.Message.AddAttachment "C:\Data\" & rsEmails("filename")
  End If

  ' Try to send e-mail
  If Not objSMTP.Send Then
    ' Notify user on sending error
    MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
  End If

  ' Reset all message properties to defaults and
  ' clear Attachments collection. If this method
  ' was not called, subsequent messages would also
  ' hold attachments from previously sent messages.
  objSMTP.ResetMessage

  ' Proceed with the next record in the table
  rsEmails.MoveNext

  ' Disconnect once 10-th e-mail is sent or passed
  ' the end of the database.
  '
  ' You may adjust number of 10 to the maximum
  ' "sends per connection" value allowed by your
  ' SMTP server.
  If I = 10 Or rsEmails.EOF Then

    ' Disconnect from SMTP server
    objSMTP.Disconnect

    ' Reinitialize counter to force Connect
    ' before next send
    I = 0
  End If

  ' Proceed with the next e-mail
  I = I + 1
Loop

' Close the table and the whole database
rsEmails.Close
objConn.Close

' Free database-related objects
Set rsEmails = Nothing
Set objConn = Nothing

[ASP]:

<%
' Mailer object
Dim objSMTP

' ADO Connection object
Dim objConn

' ADO Recordset object
Dim rsEmails

' Merge patterns (Body and "To:", all other fields remain
' unchanged for all e-mails in the mailing list)
Dim strBodyPattern, strToPattern

' Counter to limit number of sends per connection
Dim I

' Define body pattern
strBodyPattern = "Hello %%FIRST_NAME%%, " & vbCrLf & _
  "You are welcome to visit our site at:" & vbCrLf & _
  "http://www.site.com" & vbCrLf & vbCrLf & _
  "Sincerely, Site Team"

' Define "To:" pattern (will look like
' "John Doe <j.doe@domain.com>" in e-mail)
strToPattern = "%%FIRST_NAME%% %%LAST_NAME%% <%%EMAIL%%>"

' Create SMTP mailer component
Set objSMTP  = Server.CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file. If any
' errors occur, the log can be used to investigate
' the problem.
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock mailer component
objSMTP.LicenseKey = "put your license key here"

' Specify SMTP server name
objSMTP.ServerName = "localhost"

' Comment next 3 lines if your SMTP server does not
' require SMTP authentication
objSMTP.AuthMethod = 2
objSMTP.UserName = "your mail account name"
objSMTP.Password = "your mail account password"

' Create ADO Connection object
Set objConn  = Server.CreateObject("ADODB.Connection")

' Connect to Access database
objConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
   "Data Source=C:\Docs\advanced_merge.mdb;"

' Create ADO Recordset object
Set rsEmails = Server.CreateObject("ADODB.Recordset")

' Open "emails" table. This table is
' actual data source for the merge
rsEmails.Open "emails", objConn

' Initialize counter to connect to SMTP
' server before sending any e-mails
I = 1

' Loop through the table
Do While Not rsEmails.EOF

  ' Connect to the server. We connect only one time
  ' per 10 sends and reuse existing connection for
  ' subsequent 9 e-mails.
  If I = 1 Then
    If Not objSMTP.Connect Then
      ' Notify user on connection error and exit
      Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
      Exit Do
    End If
  End If

  ' Set all properties for each e-mail.
  ' This is required because we will reset
  ' the message later to free Attachments
  ' collection.

  ' Plain-text e-mail. Change to 1 to send HTML e-mail
  objSMTP.BodyFormat = 0

  ' Specify "From:" and "Subject:". They remain unchanged
  ' for all the e-mails.
  objSMTP.Message.FromAddr = "Site Team <sales@site.com>"
  objSMTP.Message.Subject = "Invitation"

  ' Merge body pattern and actual data
  ' from the database
  objSMTP.Message.BodyText = strBodyPattern
  objSMTP.Message.BodyText = Replace(objSMTP.Message.BodyText, "%%FIRST_NAME%%", rsEmails("first_name"))

  ' Merge body pattern and actual data
  ' from the database
  objSMTP.Message.ToAddr = strToPattern
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%FIRST_NAME%%", rsEmails("first_name"))
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%LAST_NAME%%", rsEmails("last_name"))
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%EMAIL%%", rsEmails("email"))

  ' Add attachment if required
  If rsEmails("filename") <> "" Then
    objSMTP.Message.AddAttachment "C:\Data\" & rsEmails("filename")
  End If

  ' Try to send e-mail
  If Not objSMTP.Send Then
    ' Notify user on sending error
    Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc & "<br>"
  End If

  ' Reset all message properties to defaults and
  ' clear Attachments collection. If this method
  ' was not called, subsequent messages would also
  ' hold attachments from previously sent messages.
  objSMTP.ResetMessage

  ' Proceed with the next record in the table
  rsEmails.MoveNext

  ' Disconnect once 10-th e-mail is sent or passed
  ' the end of the database.
  '
  ' You may adjust number of 10 to the maximum
  ' "sends per connection" value allowed by your
  ' SMTP server.
  If I = 10 Or rsEmails.EOF Then

    ' Disconnect from SMTP server
    objSMTP.Disconnect

    ' Reinitialize counter to force Connect
    ' before next send
    I = 0
  End If

  ' Proceed with the next e-mail
  I = I + 1
Loop

' Close the table and the whole database
rsEmails.Close
objConn.Close

' Free database-related objects
Set rsEmails = Nothing
Set objConn = Nothing
%>
See Also:
Mail merge and bulk e-mail (Queuing)

Send feedback to AfterLogic


Mail merge and bulk e-mail (Queuing)

Visual Basic Code | ASP Code

The sample queues e-mail sends for background delivery with MailBee Message Queue or MailBee.NET Queue system.

The code repeats Simple version of the sample (including template and database usage) with only difference that e-mails are queued to MailBee Message Queue system and no actual connection to the SMTP server is made.

SMTP.SendToQueue is a key method of the sample.

When using queing, your application only creates messages (with MailBee, this is extremely fast process). Actual delivery is performed by MailBee Message Queue system (or MailBee.NET Queue, there is no difference for this sample). This allows your application to respond very quickly even if thousands of e-mails have been created and placed into the queue.

Queing is especially useful when the machine running MailBee and actual SMTP server are not within the same local network (and communication between them is relatively slow). Another case is when SMTP server limits rate of e-mail sends from one IP address.

Note: In order to run this sample, MailBee Message Queue or MailBee.NET Queue must be installed and configured properly.

[Visual Basic]:

' Mailer object
Dim objSMTP

' ADO Connection object
Dim objConn

' ADO Recordset object
Dim rsEmails

' Merge patterns (Body and "To:", all other fields remain
' unchanged for all e-mails in the mailing list)
Dim strBodyPattern, strToPattern

' Define body pattern
strBodyPattern = "Hello %%FIRST_NAME%%, " & vbCrLf & _
  "You are welcome to visit our site at:" & vbCrLf & _
  "http://www.site.com" & vbCrLf & vbCrLf & _
  "Sincerely, Site Team"

' Define "To:" pattern (will look like
' "John Doe <j.doe@domain.com>" in e-mail)
strToPattern = "%%FIRST_NAME%% %%LAST_NAME%% <%%EMAIL%%>"

' Create SMTP mailer component
Set objSMTP  = CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file. If any
' errors occur, the log can be used to investigate
' the problem.
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock mailer component
objSMTP.LicenseKey = "put your license key here"

' Plain-text e-mail. Change to 1 to send HTML e-mail
objSMTP.BodyFormat = 0

' Specify "From:" and "Subject:". They remain unchanged
' for all the e-mails.
objSMTP.Message.FromAddr = "Site Team <sales@site.com>"
objSMTP.Message.Subject = "Invitation"

' Create ADO Connection object
Set objConn  = CreateObject("ADODB.Connection")

' Connect to Access database
objConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
  "Data Source=C:\Docs\simple_merge.mdb;"

' Create ADO Recordset object
Set rsEmails = CreateObject("ADODB.Recordset")

' Open "emails" table. This table is
' actual data source for the merge
rsEmails.Open "emails", objConn

' Loop through the table
While Not rsEmails.EOF

  ' Merge body pattern and actual data
  ' from the database
  objSMTP.Message.BodyText = strBodyPattern
  objSMTP.Message.BodyText = Replace(objSMTP.Message.BodyText, "%%FIRST_NAME%%", rsEmails("first_name"))

  ' Merge "To:" pattern and actual data
  ' from the database
  objSMTP.Message.ToAddr = strToPattern
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%FIRST_NAME%%", rsEmails("first_name"))
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%LAST_NAME%%", rsEmails("last_name"))
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%EMAIL%%", rsEmails("email"))

  ' Try to queue e-mail in MailBee Message Queue pickup folder
  ' (this usually succeeds unless disk is full)
  If Not objSMTP.SendToQueue("C:\MMQ Files") Then
    ' Notify user on queuing error
    MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
  End If

  ' Proceed with the next record in the table
  rsEmails.MoveNext
Wend

' Close the table and the whole database
rsEmails.Close
objConn.Close

' Free database-related objects
Set rsEmails = Nothing
Set objConn = Nothing

[ASP]:

<%
' Mailer object
Dim objSMTP

' ADO Connection object
Dim objConn

' ADO Recordset object
Dim rsEmails

' Merge patterns (Body and "To:", all other fields remain
' unchanged for all e-mails in the mailing list)
Dim strBodyPattern, strToPattern

' Define body pattern
strBodyPattern = "Hello %%FIRST_NAME%%, " & vbCrLf & _
  "You are welcome to visit our site at:" & vbCrLf & _
  "http://www.site.com" & vbCrLf & vbCrLf & _
  "Sincerely, Site Team"

' Define "To:" pattern (will look like
' "John Doe <j.doe@domain.com>" in e-mail)
strToPattern = "%%FIRST_NAME%% %%LAST_NAME%% <%%EMAIL%%>"

' Create SMTP mailer component
Set objSMTP  = Server.CreateObject("MailBee.SMTP")

' Enable logging SMTP session into a file. If any
' errors occur, the log can be used to investigate
' the problem.
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock mailer component
objSMTP.LicenseKey = "put your license key here"

' Plain-text e-mail. Change to 1 to send HTML e-mail
objSMTP.BodyFormat = 0

' Specify "From:" and "Subject:". They remain unchanged
' for all the e-mails.
objSMTP.Message.FromAddr = "Site Team <sales@site.com>"
objSMTP.Message.Subject = "Invitation"

' Create ADO Connection object
Set objConn  = Server.CreateObject("ADODB.Connection")

' Connect to Access database
objConn.Open "Provider=Microsoft.Jet.OLEDB.4.0; " & _
  "Data Source=C:\Docs\simple_merge.mdb;"

' Create ADO Recordset object
Set rsEmails = Server.CreateObject("ADODB.Recordset")

' Open "emails" table. This table is
' actual data source for the merge
rsEmails.Open "emails", objConn

' Loop through the table
While Not rsEmails.EOF

  ' Merge body pattern and actual data
  ' from the database
  objSMTP.Message.BodyText = strBodyPattern
  objSMTP.Message.BodyText = Replace(objSMTP.Message.BodyText, "%%FIRST_NAME%%", rsEmails("first_name"))

  ' Merge "To:" pattern and actual data
  ' from the database
  objSMTP.Message.ToAddr = strToPattern
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%FIRST_NAME%%", rsEmails("first_name"))
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%LAST_NAME%%", rsEmails("last_name"))
  objSMTP.Message.ToAddr = Replace(objSMTP.Message.ToAddr, "%%EMAIL%%", rsEmails("email"))

  ' Try to queue e-mail in MailBee Message Queue pickup folder
  ' (this usually succeeds unless disk is full)
  If Not objSMTP.SendToQueue("C:\MMQ Files") Then
    ' Notify user on queuing error
    Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc & "<br>"
  End If

  ' Proceed with the next record in the table
  rsEmails.MoveNext
Wend

' Close the table and the whole database
rsEmails.Close
objConn.Close

' Free database-related objects
Set rsEmails = Nothing
Set objConn = Nothing
%>
See Also:
SendToQueue Method
SendToQueueEx Method

Send feedback to AfterLogic


Forwarding message

Visual Basic Code | ASP Code

The sample demonstrates receiving e-mail from POP3 e-mail account and resending received e-mail to another recipient.

The code slightly touches received e-mail before resending: "FW:" is inserted to "Subject:" field and "To:" field is replaced with the e-mail address of the actual recipient.

Note: MailBee is also capable of resending messages without "touching" them (so original message is fully preserved). This requires that messages can be sent to recipients different from those specified in "To:" or "CC:" fields. See Redirecting message sample for details.

For simplicity, logging SMTP/POP3 sessions into files and SMTP authentication are not used.

[Visual Basic]:

Dim objPOP3, objSMTP, objMsg

' Create POP3 mailer component
Set objPOP3 = CreateObject("MailBee.POP3")

' Create SMTP mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock POP3 component
objPOP3.LicenseKey = "put your license key here"

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Specify name of SMTP server to resend e-mail to
objSMTP.ServerName = "smtp.server.com"

' Connect to POP3 server and log in e-mail account
If objPOP3.Connect("mail.domain1.com", 110, "user", "password") Then

   ' If the mailbox contains some messages,
   If objPOP3.MessageCount > 0 Then
      ' then grab the first e-mail.
      Set objMsg = objPOP3.RetrieveSingleMessage(1)

      ' Any errors?
      If objPOP3.IsError Then
        ' Notify user on e-mail retrieval error
        MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
      Else

        ' Replace recipients with forwarded recipient
        objMsg.ToAddr = "bill@host.com"

        ' Do not send to original CC's
        objMsg.CCAddr = ""

        ' Alter "Subject:" field
        objMsg.Subject = "FW: " & objMsg.Subject

        ' Tell SMTP component which message to send
        Set objSMTP.Message = objMsg

        ' Try to send e-mail
        If Not objSMTP.Send Then
          ' Notify user on send error
          MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
        End If
      End If
   End If

   ' Although POP3 and SMTP objects automatically
   ' disconnect on object destruction, it's recommended
   ' to disconnect manually to free memory & resources
   ' as soon as they are no longer needed.
   If objSMTP.Connected Then objSMTP.Disconnect
   objPOP3.Disconnect
Else
  ' Notify user on POP3 connection error
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If

[ASP]:

<%
Dim objPOP3, objSMTP, objMsg

' Create POP3 mailer component
Set objPOP3 = CreateObject("MailBee.POP3")

' Create SMTP mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock POP3 component
objPOP3.LicenseKey = "put your license key here"

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Specify name of SMTP server to resend e-mail to
objSMTP.ServerName = "smtp.server.com"

' Connect to POP3 server and log in e-mail account
If objPOP3.Connect("mail.domain1.com", 110, "user", "password") Then

   ' If the mailbox contains some messages,
   If objPOP3.MessageCount > 0 Then
      ' then grab the first e-mail.
      Set objMsg = objPOP3.RetrieveSingleMessage(1)

      ' Any errors?
      If objPOP3.IsError Then
        ' Notify user on e-mail retrieval error
        Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
      Else

        ' Replace recipients with forwarded recipient
        objMsg.ToAddr = "bill@host.com"

        ' Do not send to original CC's
        objMsg.CCAddr = ""

        ' Alter "Subject:" field
        objMsg.Subject = "FW: " & objMsg.Subject

        ' Tell SMTP component which message to send
        Set objSMTP.Message = objMsg

        ' Try to send e-mail
        If Not objSMTP.Send Then
          ' Notify user on send error
          Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
        End If
      End If
   End If

   ' Although POP3 and SMTP objects automatically
   ' disconnect on object destruction, it's recommended
   ' to disconnect manually to free memory & resources
   ' as soon as they are no longer needed.
   If objSMTP.Connected Then objSMTP.Disconnect
   objPOP3.Disconnect
Else
  ' Notify user on POP3 connection error
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If
%>
See Also:
SMTP.Message Property

Send feedback to AfterLogic


Redirecting message

Visual Basic Code | ASP Code

The sample demonstrates receiving e-mail from POP3 e-mail account and resending received e-mail to another recipient.

The code resends e-mail in its original state (as it came from POP3 server). Since e-mail is not altered, all original MIME information will be preserved.

To send e-mail to address different from the recipients in the e-mail itself, SMTP.SendEx method is used.

Note: Some SMTP servers do not allow sending e-mail to addresses different from specified in "To:", "CC:", "BCC:" headers.

For simplicity, logging SMTP/POP3 sessions into files and SMTP authentication are not used.

[Visual Basic]:

Dim objPOP3, objSMTP, objMsg

' Create POP3 mailer component
Set objPOP3 = CreateObject("MailBee.POP3")

' Create SMTP mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock POP3 component
objPOP3.LicenseKey = "put your license key here"

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Specify name of SMTP server to resend e-mail to
objSMTP.ServerName = "smtp.server.com"

' Connect to POP3 server and log in e-mail account
If objPOP3.Connect("mail.domain1.com", 110, "user", "password") Then

   ' If the mailbox contains some messages,
   If objPOP3.MessageCount > 0 Then
      ' then grab the first e-mail.
      Set objMsg = objPOP3.RetrieveSingleMessage(1)

      ' Any errors?
      If objPOP3.IsError Then
        ' Notify user on e-mail retrieval error
        MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
      Else

        ' Tell SMTP component which message to send
        Set objSMTP.Message = objMsg

        ' Try to send e-mail to required recipients
        If Not objSMTP.SendEx(, "bill@host.com") Then
          ' Notify user on send error
          MsgBox "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
        End If
      End If
   End If

   ' Although POP3 and SMTP objects automatically
   ' disconnect on object destruction, it's recommended
   ' to disconnect manually to free memory & resources
   ' as soon as they are no longer needed.
   If objSMTP.Connected Then objSMTP.Disconnect
   objPOP3.Disconnect
Else
  ' Notify user on POP3 connection error
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If

[ASP]:

<%
Dim objPOP3, objSMTP, objMsg

' Create POP3 mailer component
Set objPOP3 = CreateObject("MailBee.POP3")

' Create SMTP mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock POP3 component
objPOP3.LicenseKey = "put your license key here"

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Specify name of SMTP server to resend e-mail to
objSMTP.ServerName = "smtp.server.com"

' Connect to POP3 server and log in e-mail account
If objPOP3.Connect("mail.domain1.com", 110, "user", "password") Then

   ' If the mailbox contains some messages,
   If objPOP3.MessageCount > 0 Then
      ' then grab the first e-mail.
      Set objMsg = objPOP3.RetrieveSingleMessage(1)

      ' Any errors?
      If objPOP3.IsError Then
        ' Notify user on e-mail retrieval error
        Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
      Else

        ' Tell SMTP component which message to send.
        Set objSMTP.Message = objMsg

        ' Try to send e-mail to required recipients
        If Not objSMTP.SendEx(, "bill@host.com") Then
          ' Notify user on send error
          Response.Write "Error #" & objSMTP.ErrCode & ", " & objSMTP.ErrDesc
        End If
      End If
   End If

   ' Although POP3 and SMTP objects automatically
   ' disconnect on object destruction, it's recommended
   ' to disconnect manually to free memory & resources
   ' as soon as they are no longer needed.
   If objSMTP.Connected Then objSMTP.Disconnect
   objPOP3.Disconnect
Else
  ' Notify user on POP3 connection error
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If
%>
See Also:
SMTP.SendEx Method

Send feedback to AfterLogic


Bounced messages (SMTP part)

Visual Basic Code | ASP Code

The sample sends e-mail so as possible delivery errors would come to special e-mail address.

When the e-mail cannot be delivered, bounced e-mail is sent to the original sender. However, it is often more convenient to have bounced e-mails arrived to single mailbox which is specially dedicated to bounce e-mails.

The sample code makes bounce e-mails to arrive to dedicated address (which can be different from "From:" address) using SMTP.SendEx method.

Note: Some SMTP servers do not allow sending e-mail from address different from specified in "From:" header.

Demonstration of processing bounced e-mail themselves is shown in POP3 part of the sample.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "joe@domain1.com"
objSMTP.ToAddr = "bill@domain2.com"
objSMTP.Subject = "Hi"
objSMTP.BodyText = "This is test message"

' Send e-mail. If it cannot be delivered, bounce will
' arrive to bounce@domain3.com, not to joe@domain1.com
objSMTP.SendEx "bounce@domain3.com"

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Hi"
objSMTP.BodyText = "This is test message"

' Send e-mail. If it cannot be delivered, bounce will
' arrive to bounce@domain3.com, not to joe@domain1.com
objSMTP.SendEx "bounce@domain3.com"
%>
See Also:
Bounced messages (POP3 part)
SMTP.SendEx Method

Send feedback to AfterLogic


Handling events

Visual Basic Code | ASP Code

The sample demonstrates sending e-mail while staying responsive to user actions. User can abort sending process by closing the app.

Note: This sample code is for Visual Basic only. ASP does not support events.

By default, MailBee does not processes Windows events when performing mail operation. This gives maximum performance and fits fine for web applications (such as ASP ones).

Desktop applications, however, usually give user an option to interact with the app even when it is busy (e.g. sends e-mail).

To let MailBee process Windows events, EnableEvents property of SMTP object must be set to True before connecting to SMTP server.

MailBee is also capable of firing its own events (such as sending progress). See EnableEvents property documentation for details.

[Visual Basic]:

' Declare mailer object global to control
' it within different subroutines
Dim objSMTP

' User clicked the button. Must send e-mail
Private Sub Command1_Click()

  ' Allow SMTP object to process Windows
  ' events during operation
  objSMTP.EnableEvents = True

  ' Unlock SMTP component
  objSMTP.LicenseKey = "put your license key here"

  ' Set SMTP server name
  objSMTP.ServerName = "mail.server.com"

  ' Set message properties
  objSMTP.FromAddr = "me@mydomain.com"
  objSMTP.ToAddr = "you@yourdomain.com"
  objSMTP.Subject = "Hi"
  objSMTP.BodyText = "This is large message"

  ' Add large attachment so message sending
  ' would take some time
  objSMTP.AddAttachment "C:\Data\Bigfile.avi"

  ' Send it!
  objSMTP.Send

  ' Close the connection
  objSMTP.Disconnect
End Sub

' App launched, create mailer object but
' do not send any e-mail yet
Private Sub Form_Load()
  ' Create mailer component
  Set objSMTP = CreateObject("MailBee.SMTP")
End Sub

' User closed the app
Private Sub Form_Unload(Cancel As Integer)
  ' If e-mail is still being sent,
  ' abort mail operation
  If objSMTP.Busy Then objSMTP.Abort
End Sub

[ASP]:

Not applicable
See Also:
SMTP.EnableEvents Property

Send feedback to AfterLogic


OAuth 2.0 authentication

Visual Basic Code | ASP Code

The sample sends HTML e-mail using OAuth 2.0 access token (which you need to obtain from a mail service provider using their API).

SMTP.AuthMethod is a key property of the sample.

MailBee Objects ships with VBScript OAuth 2.0 sample for Gmail. You can find it in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder.

Note that the mail service provider's APIs for obtaining access tokens can be different for web and Windows applications.

[Visual Basic]:

Dim objSMTP

' Create mailer component
Set objSMTP = CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' OAuth 2.0 authentication
objSMTP.AuthMethod = 8
objSMTP.UserName = "username" ' Usually, email address
objSMTP.Password = "access_token" ' You get it from the mail service provider using their proprietary API

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Message in HTML format"

' Set HTML format for the body
objSMTP.BodyFormat = 1

' Place HTML contents into the body
objSMTP.BodyText = "<html>This word is <b>bold</b></html>"

' Send it!
objSMTP.Send

[ASP]:

<%
Dim objSMTP

' Create mailer component
Set objSMTP = Server.CreateObject("MailBee.SMTP")

' Unlock SMTP component
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' OAuth 2.0 authentication
objSMTP.AuthMethod = 8
objSMTP.UserName = "username" ' Usually, email address
objSMTP.Password = "access_token" ' You get it from the mail service provider using their proprietary API

' Set message properties
objSMTP.FromAddr = "me@mydomain.com"
objSMTP.ToAddr = "you@yourdomain.com"
objSMTP.Subject = "Message in HTML format"

' Set HTML format for the body
objSMTP.BodyFormat = 1

' Place HTML contents into the body
objSMTP.BodyText = "<html>This word is <b>bold</b></html>"

' Send it!
objSMTP.Send
%>
See Also:
AuthMethod Property

Send feedback to AfterLogic


Receiving e-mails (POP3)

Troubleshooting | Solving typical problems of e-mail receiving.
Using secure login | Logging in the POP3 mail account using secure methods.
Learning the number of messages | Learning the number of messages in the mailbox.
Learning the total size of messages | Learning the total size occupied by all messages in the mailbox.
Downloading headers | Downloading the headers of the messages.
Detecting attachments | Detecting whether a message has any attachments without downloading entire message.
Downloading entire message | Downloading entire message.
Search for new messages | Skipping already downloaded messages and downloading only new ones.
Displaying a message | Downloading and displaying a message.
Deleting a message | Deleting a message from the mailbox.
Bounced messages (POP3 part) | Processing bounced messages.
Handling events | Tracking the progress of e-mail receiving and making user interface responsive while communicating with the POP3 server.
OAuth 2.0 authentication | Using OAuth 2.0 (XOAUTH2) to access email.

Send feedback to AfterLogic


Troubleshooting

Visual Basic Code | ASP Code

Common reason of e-mail account login problems or the messages not being received is one of the following:
  • POP3 user name (UserName property of POP3 object) is different from account name (or from e-mail address).

    Some POP3 servers expect user name in form of 'account_name' while others - 'account_name@domain.com'. Sometimes, user name is not related with either account name or e-mail address. Contact your e-mail server administration for details
  • POP3 mailbox is locked. If someone else is already connected to the mailbox, noone else can establish connection to the same mailbox
  • POP3 server configuration (domains, MX records, etc.) is incorrect. Check your server's documentation for details
You can exact reason of the problem from MailBee's log file. To enable logging, set EnableLogging and LogFilePath properties of POP3 object.

If the problem persists, don't hesitate to contact our Technical Support Team to get a prompt and helpful reply.

This sample connects to the POP3 server transmitting password as clear text, and then completely retrieves first message in the mailbox (if any). POP3 session log is written into "C:\Temp\pop3_log.txt" file. All possible errors are handled.

[Visual Basic]:

Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Enable logging POP3 session into a file
objPOP3.EnableLogging = True
objPOP3.LogFilePath = "C:\Temp\pop3_log.txt"

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download first message completely
  Set objMsg = objPOP3.RetrieveSingleMessage(1)

  If Not objPOP3.IsError Then
    ' Display message body
    MsgBox objMsg.BodyText
  Else
    ' Display error information
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Enable logging POP3 session into a file
objPOP3.EnableLogging = True
objPOP3.LogFilePath = "C:\Temp\pop3_log.txt"

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download first message completely
  Set objMsg = objPOP3.RetrieveSingleMessage(1)

  If Not objPOP3.IsError Then
    ' Display message body
    Response.Write objMsg.BodyText
  Else
    ' Display error information
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
ErrCode Property
ErrDesc Property
ServerResponse Property

Send feedback to AfterLogic


Using secure login

Visual Basic Code | ASP Code

The sample connects to the POP3 server transmitting password in encrypted form.

By default, password is transmitted to POP3 server as clear text. If this is undesirable, you can force MailBee to use some sort of secure authentication. Just set AuthMethod property of POP3 object before connecting to the POP3 server.

For example, if AuthMethod=1, MailBee will use APOP secure authentication which is supported by most POP3 servers.

Note: Some servers do not support secure authentication of any kind.

[Visual Basic]:

Dim objPOP3

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Force APOP authentication
objPOP3.AuthMethod = 1

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then
  MsgBox "Connected successfully"

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Force APOP authentication
objPOP3.AuthMethod = 1

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then
  Response.Write "Connected successfully"

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
AuthMethod Property

Send feedback to AfterLogic


Learning the number of messages

Visual Basic Code | ASP Code

The sample prints the number of messages in the mailbox.

MessageCount is a key property of this sample.

[Visual Basic]:

Dim objPOP3

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Force APOP authentication
objPOP3.AuthMethod = 1

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Display the number of messages
  MsgBox objPOP3.MessageCount & " messages"

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Force APOP authentication
objPOP3.AuthMethod = 1

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Display the number of messages
  Response.Write objPOP3.MessageCount & " messages"

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
MessageCount Property

Send feedback to AfterLogic


Learning the total size of messages

Visual Basic Code | ASP Code

The sample prints the total size (in bytes) occupied by all mesages in the mailbox.

TotalSize is a key property of this sample.

[Visual Basic]:

Dim objPOP3

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Force APOP authentication
objPOP3.AuthMethod = 1

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Display the total size of messages
  MsgBox objPOP3.TotalSize & " bytes of mailbox space used"

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Force APOP authentication
objPOP3.AuthMethod = 1

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Display the total size of messages
  Response.Write objPOP3.TotalSize & " bytes of mailbox space used"

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
TotalSize Property

Send feedback to AfterLogic


Downloading headers

Visual Basic Code | ASP Code

The sample downloads headers for all the messages in the mailbox without downloading entire messages.

"From:", "To:" and "Subject:" fields are displayed for each downloaded message headers.

In ASP code, Server.HTMLEncode is used for encoding "<" and ">" characters (which often appear in e-mail addresses but not allowed in HTML) into their safe HTML equivalents. Visual Basic code does not require such encoding.

RetrieveHeaders is a key method of this sample.

[Visual Basic]:

Dim objPOP3, objMsg, objMsgs

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download headers for all messages
  Set objMsgs = objPOP3.RetrieveHeaders

  If Not objPOP3.IsError Then
    ' Display "From:", "To:", "Subject:" for each message
    For Each objMsg In objMsgs
      MsgBox _
        "From: " & objMsg.FromAddr & vbCrLf & _
        "To: " & objMsg.ToAddr & vbCrLf & _
        "Subject: " & objMsg.Subject
    Next
  Else
    ' Display error information
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3, objMsg, objMsgs

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download headers for all messages
  Set objMsgs = objPOP3.RetrieveHeaders

  If Not objPOP3.IsError Then
    ' Display "From:", "To:", "Subject:" for each message
    For Each objMsg In objMsgs
      MsgBox _
        "From: " & Server.HTMLEncode(objMsg.FromAddr) & "<br>" & _
        "To: " & Server.HTMLEncode(objMsg.ToAddr) & "<br>" & _
        "Subject: " & Server.HTMLEncode(objMsg.Subject)
    Next
  Else
    ' Display error information
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
POP3.RetrieveHeaders Method
Messages Collection

Send feedback to AfterLogic


Detecting attachments

Visual Basic Code | ASP Code

The sample detects whether any attachments are present for each message in the mailbox.

To get attachments status, only message headers are retrieved.

HasAttachments property of Message object is a key property of this sample.

Note: Seldom, message headers say that attachments are present but there are really no any attachments. Download of entire message (not just headers) makes HasAttachments property to be 100%-accurate.

[Visual Basic]:

Dim objPOP3, objMsg, objMsgs, I

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download headers for all messages
  Set objMsgs = objPOP3.RetrieveHeaders

  If Not objPOP3.IsError Then
    ' Display notification for messages with attachments
    For I = 1 To objMsgs.Count
      If objMsgs(I).HasAttachments Then
        MsgBox "Message #" & I & " has attachments"
      End If
    Next
  Else
    ' Display error information
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3, objMsg, objMsgs

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download headers for all messages
  Set objMsgs = objPOP3.RetrieveHeaders

  If Not objPOP3.IsError Then
    ' Display notification for messages with attachments
    For I = 1 To objMsgs.Count
      If objMsgs(I).HasAttachments Then
        Response.Write "Message #" & I & " has attachments<br>"
      End If
    Next
  Else
    ' Display error information
   Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
Message.HasAttachments Property

Send feedback to AfterLogic


Downloading entire message

Visual Basic Code | ASP Code

The sample completely downloads last message in the mailbox.

Body text of the downloaded message is displayed to user.

[Visual Basic]:

Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Enable logging POP3 session into a file
objPOP3.EnableLogging = True
objPOP3.LogFilePath = "C:\Temp\pop3_log.txt"

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download last message completely
  Set objMsg = objPOP3.RetrieveSingleMessage(objPOP3.MessageCount)

  If Not objPOP3.IsError Then
    ' Display message body
    MsgBox objMsg.BodyText
  Else
    ' Display error information
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Enable logging POP3 session into a file
objPOP3.EnableLogging = True
objPOP3.LogFilePath = "C:\Temp\pop3_log.txt"

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download last message completely
  Set objMsg = objPOP3.RetrieveSingleMessage(objPOP3.MessageCount)

  If Not objPOP3.IsError Then
    ' Display message body
    Response.Write objMsg.BodyText
  Else
    ' Display error information
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
RetrieveSingleMessage Method

Send feedback to AfterLogic


Search for new messages

Visual Basic Code | ASP Code

The sample downloads new messages only, skipping already received messages, and displays "Subject:" for each new message.

Note: This sample provides only simple version of the code. More detailed documentation and code samples are available in Receiving new messages from POP3 server tutorial.

Basically, the POP3 protocol has no features to determine whether a message has already been downloaded. However, you can implement this with Unique-ID. Unique-ID is a unique identifier of an e-mail on the POP3 server.

Search method of POP3 object returns an array which contains Unique-ID's of all messages in the mailbox. First element of the array contains Unique-ID of the first message in the mailbox, second element - Unique-ID of the second message, and so on.

The idea is as follows...

Firstly, your application must store Unique-ID's of already received messages in a local database.

Next time before you start downloading e-mail, retrieve Unique-ID's for all messages in the mailbox (using Search method) and look up them in the database. If Unique-ID of some message is found in the database, the message is old; otherwise, it is new. Thus you can filter out Unique-ID of every old message.

In real code, sample function IsNewMessage() should query the database for the given Unique-ID value and return True if the Unique-ID was NOT found in the database. In this sample, no real database is used and IsNewMessage() always returns True.

Last thing is to download new messages knowing their Unique-ID's. Since RetrieveSingleMessage method expects message numbers but not Unique-ID's, it is required to get message number from Unique-ID. It's simple: an index of the Unique-ID value in the Unique-ID array is the message number.

[Visual Basic]:

' This is main function. It retrieves new messages from
' the POP3 server and shows "Subject:" field of each
' retrieved message.
Sub RetrieveNewMessages()
  Dim objPOP3, objMsg, I

  ' Array of Unique-IDs (taken from the POP3 server)
  Dim arrIDs

  ' Create POP3 object
  Set objPOP3 = CreateObject("MailBee.POP3")

  ' Unlock POP3 object
  objPOP3.LicenseKey = "put your license key here"

  ' Set POP3 server name
  objPOP3.ServerName = "mail.server.com"

  ' Set user credentials
  objPOP3.UserName = "username"
  objPOP3.Password = "password"

  ' Connect to the server and log in the mailbox
  If objPOP3.Connect Then

    ' Get Unique-IDs for all messages in the mailbox
    arrIDs = objPOP3.Search

    ' Iterate through all messages in the mailbox
    For I = 1 To objPOP3.MessageCount

      ' Search Unique-ID of the message in the database
      If IsNewMessage(arrIDs(I)) Then

        ' Download new message entirely
        Set objMsg = objPOP3.RetrieveSingleMessage(I)

        ' Display the message's Subject
        MsgBox objMsg.Subject
      End If
    Next

    ' Close the connection
    objPOP3.Disconnect
  Else
    ' Display error information
    MsgBox "Error #" & objPOP3.ErrCode
    MsgBox "Server response: " & objPOP3.ServerResponse
  End If
End Sub

' This helper function should lookup the ID in the
' database, and then return True if the ID does not
' exist in the list of already downloaded messages.
Function IsNewMessage(ID)
  ' For demo purposes, the function always returns True.
  IsNewMessage = True
End Function

[ASP]:

' This is main function. It retrieves new messages from
' the POP3 server and shows "Subject:" field of each
' retrieved message.
Sub RetrieveNewMessages()
  Dim objPOP3, objMsg, I

' Array of Unique-IDs (taken from the POP3 server)
  Dim arrIDs As Variant

  ' Create POP3 object
  Set objPOP3 = Server.CreateObject("MailBee.POP3")

  ' Unlock POP3 object
  objPOP3.LicenseKey = "put your license key here"

  ' Set POP3 server name
  objPOP3.ServerName = "mail.server.com"

  ' Set user credentials
  objPOP3.UserName = "username"
  objPOP3.Password = "password"

  ' Connect to the server and log in the mailbox
  If objPOP3.Connect Then

    ' Get Unique-IDs for all messages in the mailbox
    arrIDs = objPOP3.Search

    ' Iterate through all messages in the mailbox
    For I = 1 To objPOP3.MessageCount

      ' Search Unique-ID of the message in the database
      If IsNewMessage(arrIDs(I)) Then

        ' Download entire message
        Set objMsg = objPOP3.RetrieveSingleMessage(I)

        ' Display the message's Subject
        Response.Write objMsg.Subject & "<br>"
      End If
    Next

    ' Close the connection
    objPOP3.Disconnect
  Else
    ' Display error information
    Response.Write "Error #" & objPOP3.ErrCode & "<br>"
    Response.Write "Server response: " & objPOP3.ServerResponse
  End If
End Sub

' This helper function should lookup the ID in the
' database, and then return True if the ID does not
' exist in the list of already downloaded messages.
Function IsNewMessage(ID)
  ' For demo purposes, the function always returns True.
  IsNewMessage = True
End Function
See Also:
"Receiving new messages from POP3 server" Tutorial
Search Method

Send feedback to AfterLogic


Displaying a message

Visual Basic Code | ASP Code

The sample displays contents of the message body.

Visual Basic code displays the body as plain text. If the message has HTML version only, MailBee automatically creates plain-text version.

ASP code displays the body as HTML. If the message has plain-text version only, it is converted into HTML.

Note: Advanced topics related to displaying HTML messages are discused in the tutorials:
  • Displaying HTML-formatted messages in Visual Basic
  • Displaying HTML-formatted messages in ASP

[Visual Basic]:

Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Enable logging POP3 session into a file
objPOP3.EnableLogging = True
objPOP3.LogFilePath = "C:\Temp\pop3_log.txt"

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download first message completely
  Set objMsg = objPOP3.RetrieveSingleMessage(1)

  If Not objPOP3.IsError Then
    ' HTML message?
    If objMsg.BodyFormat = 1 Then
      ' The message is HTML, so display
      ' plain version of HTML message body
      MsgBox objMsg.AltBodyText
    Else
      ' No, the message is not HTML,
      ' so display message body
      MsgBox objMsg.BodyText
    End If
  Else
    ' Display error information
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Enable logging POP3 session into a file
objPOP3.EnableLogging = True
objPOP3.LogFilePath = "C:\Temp\pop3_log.txt"

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Download first message completely
  Set objMsg = objPOP3.RetrieveSingleMessage(1)

  If Not objPOP3.IsError Then
    ' HTML message?
    If objMsg.BodyFormat = 1 Then
      ' The message is HTML, so
      ' display HTML message body
      Response.Write objMsg.BodyText
    Else
      ' The message is not HTML, so
      ' create HTML version of the body
      Response.Write objMsg.GetHTMLFromPlain(objMsg.BodyText)
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
"Displaying HTML-formatted messages in Visual Basic" Tutorial
"Displaying HTML-formatted messages in ASP" Tutorial

Send feedback to AfterLogic


Deleting a message

Visual Basic Code | ASP Code

The sample deletes first message from the mailbox.

Note: DeleteMessage method just marks a message for deletion. Actual deletion takes place when Disconnect method is called and POP3 session is closed.

[Visual Basic]:

Dim objPOP3

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Mark first message for deletion
  If objPOP3.DeleteMessage(1) Then
    MsgBox "Message #1 marked for deletion"
  Else
    ' Display error information
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection. The message is
  ' actually deleted here
  If objPOP3.Disconnect Then
    MsgBox "Message #1 purged"
  End If
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Mark first message for deletion
  If objPOP3.DeleteMessage(1) Then
    Response.Write "Message #1 marked for deletion <br>"
  Else
    ' Display error information
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection. The message is
  ' actually deleted here
  If objPOP3.Disconnect Then
    Response.Write "Message #1 purged"
  End If
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
DeleteMessage Method

Send feedback to AfterLogic


Bounced messages (POP3 part)

Visual Basic Code | ASP Code

The sample demonstrates processing bounced messages.

In SMTP part of this sample we made bounce e-mails to arrive to single e-mail account dedicated to bounced e-mails.

Each bounced e-mail contains (along with other info) e-mail address delivery has failed for. This failed address is what we want to know.

In this part, we retrieve bounced e-mails from dedicated account and then extract failed e-mail address from each bounced e-mail. Failed address is passed to RemoveEmailFromDatabase() subroutine which must remove failed address from database (in this sample, it does nothing).

Each mail server uses its own bounced message format. In this sample, typical bounced message is assumed to look like:
From: MAILER-DAEMON@afterlogic.com
To: MailBee@afterlogic.com
Subject: Undeliverable mail: A word from MailBee Support Team

Failed to deliver to 'abc@you.com'
SMTP module(domain you.com) reports:
you.com: no DNS A-data returned
Modify GetInvalidEmailAddress() function to suit bounced e-mail format used by your mail server.

Note 1: Bounced e-mails arrived from another hosts will probably have different formats. In production code, you should support as many bounced e-mail formats as possible.

Note 2: You can eliminate necessity to parse bounced e-mail to get failed address by using wildcard mailbox for bounced e-mails account. However, this functionality greatly depends on particular mail server implementations and is not discussed here.

Note 3: In some cases, you may want to scan bounced e-mails for other information. E.g. do not remove e-mail address if bounced message arrived due temporary problem: mailbox is over quota, mail server is down, etc.

[Visual Basic]:

Dim objPOP3, objMsgs, strEmail, I

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Enable logging POP3 session into a file
objPOP3.EnableLogging = True
objPOP3.LogFilePath = "C:\Temp\pop3_log.txt"

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Get headers + 100 body lines for all messages.
  ' 100 body lines is enough because failed address
  ' is somewhere in the beginning of the body
  Set objMsgs = objPOP3.RetrieveHeaders(1, -1, 100)

  If Not objPOP3.IsError Then
    ' Loop through all messages in the mailbox
    For I = 1 To objMsgs.Count

      ' Get failed email address
      strEmail = GetInvalidEmailAddress(objMsgs(I))

      ' If strEmail is non-empty, failed email address
      ' was found
      If Len(strEmail) > 0 Then

        ' Remove failed email from database
        RemoveEmailFromDatabase strEmail

        ' Delete bounced email from server to avoid
        ' processing it next time
        objPOP3.DeleteMessage I
      End If
    Next
  Else
    ' Display error information
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

' The functions checks whether the message
' is bounced and extracts failed address
' from bounced message
Function GetInvalidEmailAddress(objMsg)
  Dim I1, I2

  GetInvalidEmailAddress = ""

  ' Check if this is a bounced message report
  If InStr(1, objMsg.FromAddr, "Mailer-Daemon", 1) < 1 Then Exit Function
  If InStr(1, objMsg.Subject, "Undeliverable mail", 1) <> 1 Then Exit Function

  ' Now we're sure this is a bounced message report

  I1 = InStr(1, objMsg.BodyText, "'", 0)
  I2 = InStr(I1 + 1, objMsg.BodyText, "'", 0)

  ' Message does not contain email address?
  If I1 < 1 Or I2 < 1 Then Exit Function

  ' Get failed address
  GetInvalidEmailAddress = Mid(objMsg.BodyText, I1 + 1, I2 - I1 - 1)

  ' E-mail address is often enclosed in "<>".
  ' Remove them if needed.
  If Left(GetInvalidEmailAddress, 1) = "<" And Right(GetInvalidEmailAddress, 1) = ">" Then
    GetInvalidEmailAddress = Mid(GetInvalidEmailAddress, 2, Len(GetInvalidEmailAddress) - 2)
  End If
End Function

' This function must remove (or disable) specified
' email address from mailing list
Sub RemoveEmailFromDatabase(strEmail)
  ' Do nothing for this demo
End Sub

[ASP]:

<%
Dim objPOP3, objMsgs, strEmail, I

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Enable logging POP3 session into a file
objPOP3.EnableLogging = True
objPOP3.LogFilePath = "C:\Temp\pop3_log.txt"

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Get headers + 100 body lines for all messages.
  ' 100 body lines is enough because failed address
  ' is somewhere in the beginning of the body
  Set objMsgs = objPOP3.RetrieveHeaders(1, -1, 100)

  If Not objPOP3.IsError Then
    ' Loop through all messages in the mailbox
    For I = 1 To objMsgs.Count

      ' Get failed email address
      strEmail = GetInvalidEmailAddress(objMsgs(I))

      ' If strEmail is non-empty, failed email address
      ' was found
      If Len(strEmail) > 0 Then

        ' Remove failed email from database
        RemoveEmailFromDatabase strEmail

        ' Delete bounced email from server to avoid
        ' processing it next time
        objPOP3.DeleteMessage I
      End If
    Next
  Else
    ' Display error information
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  End If

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If

' The functions checks whether the message
' is bounced and extracts failed address
' from bounced message
Function GetInvalidEmailAddress(objMsg)
  Dim I1, I2

  GetInvalidEmailAddress = ""

  ' Check if this is a bounced message report
  If InStr(1, objMsg.FromAddr, "Mailer-Daemon", 1) < 1 Then Exit Function
  If InStr(1, objMsg.Subject, "Undeliverable mail", 1) <> 1 Then Exit Function

  ' Now we're sure this is a bounced message report

  I1 = InStr(1, objMsg.BodyText, "'", 0)
  I2 = InStr(I1 + 1, objMsg.BodyText, "'", 0)

  ' Message does not contain email address?
  If I1 < 1 Or I2 < 1 Then Exit Function

  ' Get failed address
  GetInvalidEmailAddress = Mid(objMsg.BodyText, I1 + 1, I2 - I1 - 1)

  ' E-mail address is often enclosed in "<>".
  ' Remove them if needed.
  If Left(GetInvalidEmailAddress, 1) = "<" And Right(GetInvalidEmailAddress, 1) = ">" Then
    GetInvalidEmailAddress = Mid(GetInvalidEmailAddress, 2, Len(GetInvalidEmailAddress) - 2)
  End If
End Function

' This function must remove (or disable) specified
' email address from mailing list
Sub RemoveEmailFromDatabase(strEmail)
  ' Do nothing for this demo
End Sub
%>
See Also:
Bounced Messages (SMTP part)

Send feedback to AfterLogic


Handling events

Visual Basic Code | ASP Code

The sample demonstrates retrieving e-mail while staying responsive to user actions. User can abort e-mail downloading process by closing the app.

Note: This sample code is for Visual Basic only. ASP does not support events.

By default, MailBee does not processes Windows events when performing mail operation. This gives maximum performance and fits fine for web applications (such as ASP ones).

Desktop applications, however, usually give user an option to interact with the app even when it is busy (e.g. receives e-mail).

To let MailBee process Windows events, EnableEvents property of POP3 object must be set to True before connecting to POP3 server.

MailBee is also capable of firing its own events (such as download progress). See EnableEvents property documentation for details.

[Visual Basic]:

' Declare mailer object global to control
' it within different subroutines
Dim objPOP3

' User clicked the button. Must get e-mail
Private Sub Command1_Click()
  Dim objMsgs

  ' Allow POP3 object to process Windows
  ' events during operation
  objPOP3.EnableEvents = True

  ' Unlock POP3 component
  objPOP3.LicenseKey = "put your license key here"

  ' Set POP3 server name
  objPOP3.ServerName = "mail.server.com"

  ' Set user credentials
  objPOP3.UserName = "username"
  objPOP3.Password = "password"

  ' Connect to the server and log in the mailbox
  If objPOP3.Connect Then

    ' Completely download all messages in
    ' the mailbox (this often takes some time)
    Set objMsgs = objPOP3.RetrieveMessages

    ' Close the connection
    objPOP3.Disconnect
  End If
End Sub

' App launched, create mailer object but
' do not get any e-mail yet
Private Sub Form_Load()
  ' Create mailer component
  Set objPOP3 = CreateObject("MailBee.POP3")
End Sub

' User closed the app
Private Sub Form_Unload(Cancel As Integer)
  ' If e-mail is still being received,
  ' abort mail operation
  If objPOP3.Busy Then objPOP3.Abort
End Sub

[ASP]:

Not applicable
See Also:
POP3.EnableEvents Property

Send feedback to AfterLogic


OAuth 2.0 authentication

Visual Basic Code | ASP Code

This sample connects to POP3 server using OAuth 2.0 access token (which you need to obtain from a mail service provider using their API), logs in e-mail account, and selects "Inbox" folder.

MailBee Objects ships with VBScript OAuth 2.0 sample for Gmail. You can find it in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder.

Note that the mail service provider's APIs for obtaining access tokens can be different for web and Windows applications.

[Visual Basic]:

Dim objPOP3

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username" ' Usually, email address
objPOP3.Password = "access_token" ' You get it from the mail service provider using their proprietary API

' OAuth 2.0
objPOP3.AuthMethod = 6

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Display the number of messages
  MsgBox objPOP3.MessageCount & " messages"

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode
  MsgBox "Server response: " & objPOP3.ServerResponse
End If

[ASP]:

<%
Dim objPOP3

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username" ' Usually, email address
objPOP3.Password = "access_token" ' You get it from the mail service provider using their proprietary API

' OAuth 2.0
objPOP3.AuthMethod = 6

' Connect to the server and log in the mailbox
If objPOP3.Connect Then

  ' Display the number of messages
  Response.Write objPOP3.MessageCount & " messages"

  ' Close the connection
  objPOP3.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & "<br>"
  Response.Write "Server response: " & objPOP3.ServerResponse
End If
%>
See Also:
AuthMethod Property

Send feedback to AfterLogic


Receiving e-mails (IMAP4)

Troubleshooting | Solving typical problems of e-mail receiving.
Connecting to server | Connecting to the IMAP4 server and logging in the mail account.
Selecting a mailbox | Selecting a mailbox to be examined.
Search for new messages | Locating and downloading new messages.
Select e-mail from list using Unique-ID (UID) | Using Unique-ID's to identify messages.
Downloading the list of messages | Downloading and displaying the list of all of the messages in the mailbox.
Downloading entire message | Downloading entire message.
Deleting & expunging messages | Deleting existing messages and expunging deleted messages from the mailbox.
OAuth 2.0 authentication | Using OAuth 2.0 (XOAUTH2) to access email.

Send feedback to AfterLogic


Troubleshooting

Visual Basic Code | ASP Code

Common reason of e-mail account login problems or the messages not being accessible is one of the following:
  • IMAP4 user name (UserName property of IMAP4 object) is different from account name (or from e-mail address).

    Some IMAP4 servers expect user name in form of 'account_name' while others - 'account_name@domain.com'. Sometimes, user name is not related with either account name or e-mail address. Contact your e-mail server administrator for details
  • Mailbox not selected. Unlike POP3, IMAP4 supports multiple mailboxes (i.e. folders) per e-mail account. Once logged in e-mail account, user must select a mailbox (such as "Inbox") to be able to read or manage the messages
  • Wrong or misspelled mailbox name. Also, in spite of "Inbox" and "INBOX" point to the same folder, "Outbox" and "OUTBOX" (or "sent" and "Sent") can be different folders. "Inbox" folder name is always case-insensitive but this is not necessary true for other folders
  • IMAP4 protocol is not available on mail server. Many mail servers still do not support IMAP4 protocol (or it was disabled by server's administrator). Contact your mail server administrator for details
  • IMAP4 server configuration (domains, MX records, etc.) is incorrect. Check your server's documentation for details
You can exact reason of the problem from MailBee's log file. To enable logging, set EnableLogging and LogFilePath properties of IMAP4 object.

If the problem persists, don't hesitate to contact our Technical Support Team to get a prompt and helpful reply.

This sample connects to the IMAP4 server, selects "Inbox" folder, and then completely retrieves first message in the folder. IMAP4 session log is written into "C:\Temp\imap4_log.txt" file. All possible errors are handled.

[Visual Basic]:

Dim objIMAP4, objMsg

' Create IMAP4 object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Enable logging IMAP4 session into a file
objIMAP4.EnableLogging = True
objIMAP4.LogFilePath = "C:\Temp\imap4_log.txt"

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Completely retrieve first message
    Set objMsg = objIMAP4.RetrieveSingleMessage(1)

    If Not objIMAP4.IsError Then
      ' Display the number of
      ' attachments in the message
      MsgBox "The message contains " & _
        objMsg.Attachments.Count & " attachment(s)"
    Else
      ' Display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    MsgBox "Error #" & objIMAP4.ErrCode
    MsgBox "Server response: " & objIMAP4.ServerResponse
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objIMAP4.ErrCode
  MsgBox "Server response: " & objIMAP4.ServerResponse
End If

[ASP]:

<%
Dim objIMAP4, objMsg

' Create IMAP4 object
Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Enable logging IMAP4 session into a file
objIMAP4.EnableLogging = True
objIMAP4.LogFilePath = "C:\Temp\imap4_log.txt"

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Completely retrieve first message
    Set objMsg = objIMAP4.RetrieveSingleMessage(1, False)

    If Not objIMAP4.IsError Then
      ' Display the number of
      ' attachments in the message
      Response.Write "The message contains " & _
        objMsg.Attachments.Count & " attachment(s)"
    Else
      ' Display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
    Response.Write "Server response: " & objIMAP4.ServerResponse
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
  Response.Write "Server response: " & objIMAP4.ServerResponse
End If
%>
See Also:
ErrCode Property
ErrDesc Property
ServerResponse Property

Send feedback to AfterLogic


Connecting to server

Visual Basic Code | ASP Code

This sample connects to IMAP4 server and logs in e-mail account. No mailbox is being selected, however.

Once connected, you can select, manage, subscribe or unsubscribe mailboxes.

[Visual Basic]:

Dim objIMAP4, objMsg

' Create IMAP4 object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  MsgBox "Connected successfully"

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objIMAP4.ErrCode
  MsgBox "Server response: " & objIMAP4.ServerResponse
End If

[ASP]:

<%
Dim objIMAP4, objMsg

' Create IMAP4 object
Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  Response.Write "Connected successfully"

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
  Response.Write "Server response: " & objIMAP4.ServerResponse
End If
%>
See Also:
Connected Property
ExamineMailbox Method
SelectMailbox Method

Send feedback to AfterLogic


Selecting a mailbox

Visual Basic Code | ASP Code

This sample connects to IMAP4 server, logs in e-mail account and selects "Inbox" folder for read/write access.

Note: "Mailbox" and "folder" terms mean the same.

SelectMailbox method used in this sample selects e-mail account folder for read/write access (i.e. you can both retrieve and manage e-mail).

ExamineMailbox method differs from SelectMailbox in that the folder is being selected for read-only access (i.e. you can only read e-mail).

[Visual Basic]:

Dim objIMAP4, objMsg

' Create IMAP4 object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Enable logging IMAP4 session into a file
objIMAP4.EnableLogging = True
objIMAP4.LogFilePath = "C:\Temp\imap4_log.txt"

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then
    ' All is fine
    MsgBox "Inbox selected successfully"
  Else
    ' Display error information
    MsgBox "Error #" & objIMAP4.ErrCode
    MsgBox "Server response: " & objIMAP4.ServerResponse
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objIMAP4.ErrCode
  MsgBox "Server response: " & objIMAP4.ServerResponse
End If

[ASP]:

<%
Dim objIMAP4, objMsg

' Create IMAP4 object
Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Enable logging IMAP4 session into a file
objIMAP4.EnableLogging = True
objIMAP4.LogFilePath = "C:\Temp\imap4_log.txt"

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then
    ' All is fine
    Response.Write "Inbox selected successfully"
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
    Response.Write "Server response: " & objIMAP4.ServerResponse
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
  Response.Write "Server response: " & objIMAP4.ServerResponse
End If
%>
See Also:
ErrCode Property
ErrDesc Property
ServerResponse Property

Send feedback to AfterLogic


Search for unread messages

Visual Basic Code | ASP Code

This sample connects to IMAP4 server, logs in e-mail account, selects "Inbox" folder and downloads unread (UNSEEN in IMAP) messages.

Unlike POP3, IMAP4 protocol remembers which messages have been already downloaded. This makes it easy to determine which messages are new.

Note: If e-mail account is accessed by multiple mail agents, IMAP4's unread messages detection won't work: messages not yet received by one mail agent can be already received (and marked as read on the server) by another mail agent. In other words, when the same message can be unread for one mail agent and read for another, your app should not rely on IMAP4 read/unread messages detection. In this case, you can use the same approach as for POP3 protocol (see Search for new messages POP3 sample).

[Visual Basic]:

Dim objIMAP4, objMsg, arrNew, I

' Create IMAP4 object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Enable logging IMAP4 session into a file
objIMAP4.EnableLogging = True
objIMAP4.LogFilePath = "C:\Temp\imap4_log.txt"

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Get Unique-IDs of unread messages
    arrNew = objIMAP4.Search(True, "unseen")

    If Not objIMAP4.IsError Then

      ' Loop through new messages
      For I = LBound(arrNew) To UBound(arrNew)

        ' Completely retrieve message by its Unique-ID
        Set objMsg = objIMAP4.RetrieveSingleMessage(arrNew(I), True)

        If Not objIMAP4.IsError Then
          ' Display message body
          MsgBox objMsg.BodyText
        Else
          ' Display error information
          MsgBox "Error #" & objIMAP4.ErrCode & ", " & _
            objIMAP4.ErrDesc
        End If
      Next
    Else
      ' Display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & _
        objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    MsgBox "Error #" & objIMAP4.ErrCode
    MsgBox "Server response: " & objIMAP4.ServerResponse
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objIMAP4.ErrCode
  MsgBox "Server response: " & objIMAP4.ServerResponse
End If

[ASP]:

<%
Dim objIMAP4, objMsg, arrNew, I

' Create IMAP4 object
Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Enable logging IMAP4 session into a file
objIMAP4.EnableLogging = True
objIMAP4.LogFilePath = "C:\Temp\imap4_log.txt"

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Get Unique-IDs of unread messages
    arrNew = objIMAP4.Search(True, "unseen")

    If Not objIMAP4.IsError Then

      ' Loop through new messages
      For I = LBound(arrNew) To UBound(arrNew)

        ' Completely retrieve a message by its Unique-ID
        Set objMsg = objIMAP4.RetrieveSingleMessage(arrNew(I), True)

        If Not objIMAP4.IsError Then
          ' Display message body
          Response.Write objMsg.BodyText & "<br>"
        Else
          ' Display error information
          Response.Write "Error #" & objIMAP4.ErrCode & ", " & _
            objIMAP4.ErrDesc & "<br>"
        End If
      Next
    Else
      ' Display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & _
        objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
    Response.Write "Server response: " & objIMAP4.ServerResponse
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
  Response.Write "Server response: " & objIMAP4.ServerResponse
End If
%>
See Also:
Search Method

Send feedback to AfterLogic


Select e-mail from list using UID

Visual Basic Code | ASP Code

This sample demonstrates using Unique-ID's (UID's) to reliably identify messages.

First section of the code (DisplayList procedure in Visual Basic sample and DisplayList.asp file in ASP sample) displays the list of all messages in the mailbox. Each item in the list corresponds to a message. For each message in the list, Unique-ID value is remembered.

Second section of the code (DisplayEmail procedure in Visual Basic sample and DisplayEmail.asp file in ASP sample) displays body of the message, given its Unique-ID value.

Visual Basic sample also assumes the application's main form contains List1 control of ListBox class.
Since Unique-ID values persist accross sessions, they are often more reliable way to identify messages on the mail server.

Persisting of Unique-ID values is especially important in web environments where multiple users can simultaneously access shared mail account. Assume the following scenario:
  • Bob requests message list of the shared mailbox to be displayed and sees something interesting in the subject of e-mail #3
  • Alice deletes e-mail #2 in the shared mailbox. Message numbers starting from #3 shift by -1, i.e. e-mail #3 becomes e-mail #2, e-mail #4 becomes e-mail #3, etc.
  • Bob requests message #3 to be displayed. However, the message expected by Bob is e-mail #2 now, i.e. message list went out of sync. Bob actually receives message next to the one he is interested in
The scenario above would not be a problem when using Unique-IDs since their values never shift. They are tightly linked to the messages.

[Visual Basic]:

' IMAP4 object
Dim objIMAP4

' Stores Unique-ID for each message in the Inbox
Dim arrUIDs

' Connects to server, logs in email account
' and selects Inbox.
' Returns True if succeeded, otherwise False
Function GetInbox()
  GetInbox = False

  ' Set IMAP4 server name
  objIMAP4.ServerName = "mail.server.com"

  ' Set user credentials
  objIMAP4.UserName = "username"
  objIMAP4.Password = "password"

  ' Connect to the server and
  ' log in email account
  If objIMAP4.Connect Then
    ' Select Inbox folder
    If objIMAP4.SelectMailbox("Inbox") Then
      ' Successully logged in and selected Inbox
      GetInbox = True
    Else
      ' Display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    MsgBox "Error #" & objIMAP4.ErrCode
    MsgBox "Server response: " & objIMAP4.ServerResponse
  End If
End Function

' Fills ListBox control with "Subject:" field
' of each message in the Inbox and remembers
' Unique-ID's of all messages in arrUIDs array
Sub DisplayList()
  Dim objEnvelopes, objEnvelope

  ' Try to login
  If GetInbox Then

    ' Fill array with Unique-ID values of all
    ' messages in the mailbox
    arrUIDs = objIMAP4.Search(True)

    ' Get envelopes for all messages in the Inbox
    Set objEnvelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False)

    If Not objIMAP4.IsError Then
      For Each objEnvelope In objEnvelopes
        ' Add each message's "Subject:" to ListBox
        List1.AddItem objEnvelope.Subject
      Next
    Else
      ' Display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  End If

  ' Disconnect if needed
  If objIMAP4.Connected Then
    objIMAP4.Disconnect
  End If
End Sub

' Display body of an e-mail when this e-mail's
' "Subject:" is clicked in List1 control
Private Sub List1_Click()
  Dim objMsg

  ' Try to login
  If GetInbox Then

    ' Get message by Unique-ID stored in arrUIDs array
    Set objMsg = objIMAP4.RetrieveSingleMessage(arrUIDs(List1.ListIndex + 1), True)

    If Not objIMAP4.IsError Then
      ' Display message body
      MsgBox objMsg.BodyText
    Else
      ' Display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  End If

  ' Disconnect if needed
  If objIMAP4.Connected Then
    objIMAP4.Disconnect
  End If
End Sub

' Display message list on application start
Private Sub Form_Load()

  ' Create and unlock IMAP4 object
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"

  ' Display messages' subjects and remember messages' Unique-ID's
  DisplayList
End Sub

[ASP]:

DisplayList.asp:

<%
Dim objIMAP4, objEnvelopes, I

' Connects to server, logs in email account
' and selects Inbox.
' Returns True if succeeded, otherwise False.
'
' This function is duplicated in both ASP files.
' In production code, it's better to move duplicates
' into single include file.
Function GetInbox()
  GetInbox = False

  ' Set IMAP4 server name
  objIMAP4.ServerName = "mail.server.com"

  ' Set user credentials
  objIMAP4.UserName = "username"
  objIMAP4.Password = "password"

  ' Connect to the server and
  ' log in email account
  If objIMAP4.Connect Then
    ' Select Inbox folder
    If objIMAP4.SelectMailbox("Inbox") Then
      ' Successully logged in and selected Inbox
      GetInbox = True
    Else
      ' Display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
    Response.Write "Server response: " & objIMAP4.ServerResponse
  End If
End Function

' Create and unlock IMAP4 object
Set objIMAP4 = CreateObject("MailBee.IMAP4")
objIMAP4.LicenseKey = "put your license key here"

' Try to login
If GetInbox Then

  ' Fill array with Unique-ID values of all
  ' messages in the mailbox
  arrUIDs = objIMAP4.Search(True)

  If Not objIMAP4.IsError Then
    ' Get envelopes for all messages in the Inbox
    Set objEnvelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False)

    If Not objIMAP4.IsError Then
      For I = 1 To objEnvelopes.Count
        ' Print each e-mail's "Subject:" in the form of
        ' "A HREF" link that points to DisplayEmail.asp with UID parameter
        ' set to Unique-ID of the e-mail
        Response.Write "<a href='DisplayEmail.asp?uid=" & arrUIDs(I) & "'>" & objEnvelopes(I).Subject & "</a><br>"
      Next
    Else
      ' Display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
  End If
End If

' Disconnect if needed
If objIMAP4.Connected Then
  objIMAP4.Disconnect
End If
%>

DisplayEmail.asp:

<%
Dim objIMAP4, objMsg, I

' Connects to server, logs in email account
' and selects Inbox.
' Returns True if succeeded, otherwise False.
'
' This function is duplicated in both ASP files.
' In production code, it's better to move duplicates
' into single include file.
Function GetInbox()
  GetInbox = False

  ' Set IMAP4 server name
  objIMAP4.ServerName = "mail.server.com"

  ' Set user credentials
  objIMAP4.UserName = "username"
  objIMAP4.Password = "password"

  ' Connect to the server and
  ' log in email account
  If objIMAP4.Connect Then
    ' Select Inbox folder
    If objIMAP4.SelectMailbox("Inbox") Then
      ' Successully logged in and selected Inbox
      GetInbox = True
    Else
      ' Display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
    Response.Write "Server response: " & objIMAP4.ServerResponse
  End If
End Function

' Create and unlock IMAP4 object
Set objIMAP4 = CreateObject("MailBee.IMAP4")
objIMAP4.LicenseKey = "put your license key here"

' Try to login
If GetInbox Then

  ' Get message by Unique-ID taken from Request variable
  Set objMsg = objIMAP4.RetrieveSingleMessage(Request.QueryString("uid"), True)

  If Not objIMAP4.IsError Then
      ' Display message body
      Response.Write objMsg.BodyText
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
  End If
End If

' Disconnect if needed
If objIMAP4.Connected Then
  objIMAP4.Disconnect
End If
%>
See Also:
Envelope.UID Property

Send feedback to AfterLogic
Copyright � 2002-2020, AfterLogic Corporation. All rights reserved.


Downloading the list of messages

Visual Basic Code | ASP Code

This sample connects to IMAP4 server, logs in e-mail account, selects "Inbox" folder, downloads headers for all e-mails in the folder. For each e-mail, "From:" field and number of attachments are displayed.

The IMAP4 protocol allows to examine messages in greater detail than the POP3 protocol. With IMAP4, you can get message envelopes, body structures and normal POP3-style message headers.

Message envelope (available through Envelope object) is similar to message headers but provides some properties which message headers don't (such as datetime of the moment when the e-mail was received by IMAP4 server). On other hand, envelope contains only basic headers such as "Subject:", "To:", "From:", "Reply-To:", "Message-ID:", "Date:" and so on. To get custom headers (such as "Organization" or "X-Priority") you still need to retrieve message headers.

If custom headers are needed, you can tell MailBee to also retrieve message headers when retrieving envelopes. Use RetrieveEnvelopesEx method with AlsoGetMessagePreview parameter set to True.

Body structure allows you to learn message structure (number and names of attachments, types of message bodies, and so on). You can get body structures together with envelopes using RetrieveEnvelopesEx method with AlsoGetBodyStructure parameter set to True.

Body structure is organized in the tree of BodyPartStructure objects. E-mail messages often consist of several parts which can contain another parts (and these parts can also contain smaller parts). Usually, nesting level does not exceed the number of 3, but can potentially be unlimited. BodyPartStructure objects provide body structures of contained smaller parts (if any) in SubParts property. Each object in SubParts collection is also a BodyPartStructure object. To scan the whole body structure (e.g. to count all attachments in the e-mail) it's required to scan all BodyPartStructure objects with all their subparts.

[Visual Basic]:

' This function performs recursively through
' all body parts of the e-mail, counting the number
' of the attachments
Function GetAttachmentsCount(objBodyPart)
  Dim objSubPart

  GetAttachmentsCount = 0
  If objBodyPart.IsMultipart Then
    ' Body part is grouping part, dig into subparts
    For Each objSubPart In objBodyPart.SubParts
      GetAttachmentsCount = GetAttachmentsCount + GetAttachmentsCount(objSubPart)
    Next
  ElseIf objBodyPart.Disposition = "attachment" Then
    ' Body part is attachment
    GetAttachmentsCount = 1
  End If
End Function

Dim objIMAP4, objEnvelopes, objEnvelope

Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Download envelopes together with body structures for
    ' all e-mails in the folder
    Set objEnvelopes = _
      objIMAP4.RetrieveEnvelopesEx(1, objIMAP4.MessageCount, False, True)

    If Not objIMAP4.IsError Then
      For Each objEnvelope In objEnvelopes
        ' Display "Subject:" (taken from envelope) and number of
        ' attachments (taken from bdoy structure) for every e-mail
        MsgBox "Subject: " & objEnvelope.Subject & vbCrLf & _
          "Number of attachments: " & _
          GetAttachmentsCount(objEnvelope.BodyStructure)
      Next
    Else
      ' Display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objIMAP4.ErrCode
  MsgBox "Server response: " & objIMAP4.ServerResponse
End If

[ASP]:

<%
' This function performs recursively through
' all body parts of the e-mail, counting the number
' of the attachments
Function GetAttachmentsCount(objBodyPart)
  Dim objSubPart

  GetAttachmentsCount = 0
  If objBodyPart.IsMultipart Then
    ' Body part is grouping part, dig into subparts
    For Each objSubPart In objBodyPart.SubParts
      GetAttachmentsCount = GetAttachmentsCount + GetAttachmentsCount(objSubPart)
    Next
  ElseIf objBodyPart.Disposition = "attachment" Then
    ' Body part is attachment
    GetAttachmentsCount = 1
  End If
End Function

Dim objIMAP4, objEnvelopes, objEnvelope

Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Download envelopes together with body structures for
    ' all e-mails in the folder
    Set objEnvelopes = _
      objIMAP4.RetrieveEnvelopesEx(1, objIMAP4.MessageCount, False, True)

    If Not objIMAP4.IsError Then
      For Each objEnvelope In objEnvelopes
        ' Display "Subject:" (taken from envelope) and number of
        ' attachments (taken from bdoy structure) for every e-mail
        Response.Write "Subject: " & objEnvelope.Subject & "<br>" & _
          "Number of attachments: " & _
          GetAttachmentsCount(objEnvelope.BodyStructure) & "<br><br>"
      Next
    Else
      ' Display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
  Response.Write "Server response: " & objIMAP4.ServerResponse
End If
%>
See Also:
RetrieveEnvelopes Method
RetrieveEnvelopesEx Method

Send feedback to AfterLogic


Downloading entire message

Visual Basic Code | ASP Code

This sample connects to IMAP4 server, logs in e-mail account, selects "Inbox" folder and entirely downloads first message in the folder.

"From:", "To:", "Subject:", body text, and filenames of attachments are displayed for the downloaded message.

[Visual Basic]:

Dim objIMAP4, objMsg, objAttach, strEmailInfo

Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Completely retrieve a message
    Set objMsg = objIMAP4.RetrieveSingleMessage(1, False)

    If Not objIMAP4.IsError Then

      ' Add message headers to message's info string
      strEmailInfo = _
        "From:      " & objMsg.FromAddr & vbCrLf & _
        "To:        " & objMsg.ToAddr & vbCrLf & _
        "Subject:   " & objMsg.Subject & vbCrLf
        "Attach(s): "

      ' Add attachments' names to message's info string
      For Each objAttach In objMsg.Attachments
        ' Skip inline attachments (embedded images and so on)
        If Not objAttach.IsInline Then
          strEmailInfo = strEmailInfo & " " & objAttach.Filename
        End If
      Next

      ' Add body text to message's info string
      strEmailInfo = strEmailInfo & vbCrLf & vbCrLf & objMsg.BodyText

      ' Display message's info
      MsgBox strEmailInfo
    Else
      ' Display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objIMAP4.ErrCode
  MsgBox "Server response: " & objIMAP4.ServerResponse
End If

[ASP]:

<%
Dim objIMAP4, objMsg, objAttach, strEmailInfo

Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Completely retrieve a message
    Set objMsg = objIMAP4.RetrieveSingleMessage(1, False)

    If Not objIMAP4.IsError Then

      ' Add message headers to message's info string
      '
      ' We use Server.HTMLEncode to properly handle situation
      ' when HTML-unsafe chars (such as '<', '>', '&') appear
      ' somewehere in "From:", "To:" or "Subject:" fields
      strEmailInfo = _
        "From:      " & Server.HTMLEncode(objMsg.FromAddr) & "<br>" & _
        "To:        " & Server.HTMLEncode(objMsg.ToAddr) & "<br>" & _
        "Subject:   " & Server.HTMLEncode(objMsg.Subject) & "<br>" & _
        "Attach(s): "

      ' Add attachments' names to message's info string
      For Each objAttach In objMsg.Attachments
        ' Skip inline attachments (embedded images and so on)
        If Not objAttach.IsInline Then
          strEmailInfo = strEmailInfo & " " & objAttach.Filename
        End If
      Next

      ' Add body text to message's info string
      strEmailInfo = strEmailInfo & "<br><br>" & objMsg.BodyText

      ' Display message's info
      Response.Write strEmailInfo
    Else
      ' Display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
  Response.Write "Server response: " & objIMAP4.ServerResponse
End If
%>
See Also:
RetrieveSingleMessage Method
Message Object

Send feedback to AfterLogic


Deleting & expunging messages

Visual Basic Code | ASP Code

This sample connects to IMAP4 server, logs in e-mail account, selects "Inbox" folder and permanently removes all messages which were already seen before.

Search method with "SEEN" search condition is used to locate already seen messages.

DeleteMessages method is used to mark messages for deletion.

ExpungeAndClose method is used to close "Inbox" mailbox and permanently delete messages marked for deletion (you can also use Expunge method to purge messages without closing the mailbox).

[Visual Basic]:

Dim objIMAP4, arrSeen, I

Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Get message numbers of already seen messages
    arrSeen = objIMAP4.Search(False, "SEEN")

    If Not objIMAP4.IsError Then
      ' Loop through already seen messages
      For I = LBound(arrSeen) To UBound(arrSeen)
        ' Mark message for deletion
        objIMAP4.DeleteMessages arrSeen(I), arrSeen(I), False
      Next
    Else
      ' Display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If

    ' Purge deleted messages and close "Inbox"
    If Not objIMAP4.ExpungeAndClose Then
      ' On error, no emails would be purged:
      ' display error information
      MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    MsgBox "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objIMAP4.ErrCode
  MsgBox "Server response: " & objIMAP4.ServerResponse
End If

[ASP]:

<%
Dim objIMAP4, arrSeen, I

Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Get message numbers of already seen messages
    arrSeen = objIMAP4.Search(False, "SEEN")

    If Not objIMAP4.IsError Then
      ' Loop through already seen messages
      For I = LBound(arrSeen) To UBound(arrSeen)
        ' Mark message for deletion
        objIMAP4.DeleteMessages arrSeen(I), arrSeen(I), False
      Next
    Else
      ' Display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc & "<br>"
    End If

    ' Purge deleted messages and close "Inbox"
    If Not objIMAP4.ExpungeAndClose Then
      ' On error, no emails would be purged:
      ' display error information
      Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
    End If
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & ", " & objIMAP4.ErrDesc
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
  Response.Write "Server response: " & objIMAP4.ServerResponse
End If
%>
See Also:
DeleteMessages Method
ExpungeAndClose Method

Send feedback to AfterLogic


OAuth 2.0 authentication

Visual Basic Code | ASP Code

This sample connects to IMAP4 server using OAuth 2.0 access token (which you need to obtain from a mail service provider using their API), logs in e-mail account, and selects "Inbox" folder.

MailBee Objects ships with VBScript OAuth 2.0 sample for Gmail. You can find it in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder.

Note that the mail service provider's APIs for obtaining access tokens can be different for web and Windows applications.

[Visual Basic]:

Dim objIMAP4, objMsg

' Create IMAP4 object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Enable logging IMAP4 session into a file
objIMAP4.EnableLogging = True
objIMAP4.LogFilePath = "C:\Temp\imap4_log.txt"

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username" ' Usually, email address
objIMAP4.Password = "access_token" ' You get it from the mail service provider using their proprietary API

' OAuth 2.0
objIMAP.AuthMethod = 6

' Connect to the server and log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then
    ' All is fine
    MsgBox "Inbox selected successfully"
  Else
    ' Display error information
    MsgBox "Error #" & objIMAP4.ErrCode
    MsgBox "Server response: " & objIMAP4.ServerResponse
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  MsgBox "Error #" & objIMAP4.ErrCode
  MsgBox "Server response: " & objIMAP4.ServerResponse
End If

[ASP]:

lt;%
Dim objIMAP4, objMsg

' Create IMAP4 object
Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Enable logging IMAP4 session into a file
objIMAP4.EnableLogging = True
objIMAP4.LogFilePath = "C:\Temp\imap4_log.txt"

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username" ' Usually, email address
objIMAP4.Password = "access_token" ' You get it from the mail service provider using their proprietary API

' OAuth 2.0
objIMAP.AuthMethod = 6

' Connect to the server and log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then
    ' All is fine
    Response.Write "Inbox selected successfully"
  Else
    ' Display error information
    Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
    Response.Write "Server response: " & objIMAP4.ServerResponse
  End If

  ' Close the connection
  objIMAP4.Disconnect
Else
  ' Display error information
  Response.Write "Error #" & objIMAP4.ErrCode & "<br>"
  Response.Write "Server response: " & objIMAP4.ServerResponse
End If
%>
See Also:
AuthMethod Property

Send feedback to AfterLogic


Advanced

Validating e-mail address | Testing whether email address is correct.
Forwarded messages | Handling messages encapsulated in another messages.

Send feedback to AfterLogic


Validating e-mail address

Visual Basic Code | ASP Code

This sample validates e-mail address. First time, the address is validated for syntax only, second time, the address is also validated for e-mail address domain existence.

ValidateEmailAddress is a key method of this sample.

Note 1: Testing for domain existence can take some time (up to a few seconds) if particular domain does not exist.

Note 2: Even if e-mail address syntax is correct and domain exists, this still doesn't guarantee that e-mail address is valid. The only 100%-accurate way to validate e-mail address is to send e-mail to this address, wait some time and then check whether bounced e-mail has returned from this address.

[Visual Basic]:

Dim objMsg

' We manually create Message object here. In your code,
' you can also reuse any existing Message object, such
' as SMTP.Message
Set objMsg = CreateObject("MailBee.Message")

' Check email address for syntax only. Because
' "mailbox@non-existent-domain.com" email is
' syntactically correct, the method will return True
If objmsg.ValidateEmailAddress("mailbox@non-existent-domain.com") Then
  MsgBox "E-mail address syntax is correct"
Else
  MsgBox "Syntax check failed"
End If

' Check email address for syntax and for domain existence.
' If "non-existent-domain.com" host does not exist, the method
' will return False
If objmsg.ValidateEmailAddress("mailbox@non-existent-domain.com", 1) Then
  MsgBox "E-mail address is probably correct"
Else
  MsgBox "E-mail address is incorrect"
End If

[ASP]:

<%
Dim objMsg

' We manually create Message object here. In your code,
' you can also reuse any existing Message object, such
' as SMTP.Message
Set objMsg = Server.CreateObject("MailBee.Message")

' Check email address for syntax only. Because
' "mailbox@non-existent-domain.com" email is
' syntactically correct, the method will return True
If objmsg.ValidateEmailAddress("mailbox@non-existent-domain.com") Then
  Response.Write "E-mail address syntax is correct <br>"
Else
  Response.Write "Syntax check failed <br>"
End If

' Check email address for syntax and for domain existence.
' If "non-existent-domain.com" host does not exist, the method
' will return False
If objmsg.ValidateEmailAddress("mailbox@non-existent-domain.com", 1) Then
  Response.Write "E-mail address is probably correct"
Else
  Response.Write "E-mail address is incorrect"
End If
%>
See Also:
ValidateEmailAddress Method

Send feedback to AfterLogic


Forwarded messages

Visual Basic Code | ASP Code

This sample takes a e-mail from POP3 server, detects forwarded messages (if any) and shows their bodies.

E-mail message "A" contains forwarded message "B" if the "B" message was forwarded as attachment of the "A" message.

Forwarded messages can contain another forwarded messages (e.g. some message was forwarded several times) so nesting level is potentially unlimited. This sample detects forwarded messages in recursive manner making it possible to detect every forwarded message at any nesting level.

The sample gets e-mail from POP3 server but you can use the same approach for IMAP4 and for messages taken from disk or database.

[Visual Basic]:

' The sub displays bodies of any forwarded messages
' within specified message (including messages within
' forwarded messages themsleves).
Sub DisplayForwardedBody(objMsg)
  Dim objForwardedMsg, objAttach

  ' Forwarded messages reside in Attachments list
  For Each objAttach In objMsg.Attachments
    ' Does the attachment hold a message inside?
    If objAttach.IsMessage Then

      ' Load the forwarded message from the attachment
      Set objForwardedMsg = CreateObject("MailBee.Message")
      objForwardedMsg.RawBody = objAttach.Content

      ' Display the body of the forwarded message
      MsgBox objForwardedMsg.BodyText

      ' The forwared message may contain another
      ' forwarded messages. Thus we repeat the procedure
      ' for every message found in the root message.
      DisplayForwardedBody objForwardedMsg
    End If
  Next
End Sub

Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Download a message
Set objMsg = objPOP3.RetrieveSingleMessage(1)

If Not objPOP3.IsError Then
  ' Display bodies of forwarded messages
  DisplayForwardedBody objMsg
End If

' Disconnect if needed
If objPOP3.Connected Then
  objPOP3.Disconnect
End If

[ASP]:

<%
' The sub displays bodies of any forwarded messages
' within specified message (including messages within
' forwarded messages themsleves).
Sub DisplayForwardedBody(objMsg)
  Dim objForwardedMsg, objAttach

  ' Forwarded messages reside in Attachments list
  For Each objAttach In objMsg.Attachments
    ' Does the attachment hold a message inside?
    If objAttach.IsMessage Then

      ' Load the forwarded message from the attachment
      Set objForwardedMsg = Server.CreateObject("MailBee.Message")
      objForwardedMsg.RawBody = objAttach.Content

      ' Display the body of the forwarded message
      Response.Write objForwardedMsg.BodyText & "<br><br>"

      ' The forwared message may contain another
      ' forwarded messages. Thus we repeat the procedure
      ' for every message found in the root message.
      DisplayForwardedBody objForwardedMsg
    End If
  Next
End Sub

Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Download a message
Set objMsg = objPOP3.RetrieveSingleMessage(1)

If Not objPOP3.IsError Then
  ' Display bodies of forwarded messages
  DisplayForwardedBody objMsg
End If

' Disconnect if needed
If objPOP3.Connected Then
  objPOP3.Disconnect
End If
%>
See Also:
Attachment.IsMessage Property
Message.RawBody Property

Send feedback to AfterLogic


MailBee Tutorials

These tutorails cover different aspects of MailBee usage in Visual Basic (e.g. client) and ASP (e.g. server) environments. However, MailBee can be used in practically every client and server environment which supports ActiveX technology: .NET, Delphi, Cold Fusion, etc.

Creating and sending HTML-formatted messages
Displaying HTML-formatted messages (Visual Basic)
Displaying HTML-formatted messages (ASP)
Receiving message headers from POP3 server (Visual Basic)
Receiving message headers from POP3 server (ASP)
Receiving new messages from POP3 server (Visual Basic)
Receiving new messages from POP3 server (ASP)

OAuth 2.0 samples for Gmail and Office 365 can be found in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder.

Send feedback to AfterLogic


Creating and sending HTML-formatted messages (Part 1)

Sending simple HTML e-mail Summary: Demonstrates sending simple HTML e-mail. Focuses on connecting to the SMTP server and sending e-mail rather than message composing.

Tutorial map:
Part 1 - Sending simple HTML e-mail
Part 2 - Importing HTML file into message body
Part 3 - Assembling body text from different sources
Part 4 - Building alternative message body
Part 5 - Advanced topics

To send an e-mail, we need to create MailBee.SMTP object first.

Once SMTP object is created and valid LicenseKey is assigned, next step is to set the properties of the e-mail itself, and specify SMTP server which will actually deliver our e-mail. We'll set the following properties of the e-mail itself:

  • SMTP.Message.FromAddr - "From:" field of the message
  • SMTP.Message.ToAddr - "To:" field of the message
  • SMTP.Message.Subject - "Subject:" field of the message
  • SMTP.Message.BodyText - the message's body text
  • SMTP.Message.BodyFormat - the message's body format (i.e. plain-text or HTML)
and the following property of the SMTP server:
  • SMTP.ServerName - SMTP server name
Once all properties are set, call Send method to perform actual sending. Finally, call Disconnect method to close the SMTP session.

Code example:

Dim Mailer

' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")

' Unlock MailBee.SMTP object
Mailer.LicenseKey = "put your license key here"

' SMTP server name
Mailer.ServerName = "mail.server.com"

' Recipients
Mailer.Message.ToAddr = "you@yourdomain.com"

' Sender
Mailer.Message.FromAddr = "me@mydomain.com"

' Subject
Mailer.Message.Subject = "Hello"

' HTML body text
Mailer.Message.BodyText = "<html>Hello</html>"

' Mark that body has HTML format
Mailer.Message.BodyFormat = 1

' Send it!
Mailer.Send

' Close the SMTP session
Mailer.Disconnect

E-mails are not sent: SMTP authentication required

Sometimes e-mails are not sent if only the SMTP server name is specified. This occurs if the SMTP server's administrator restricted access to the server by any means. For example, e-mails may be delivered to local addresses only or may not be delivered at all.

As a rule, SMTP servers give unrestricted access to authenticated users only. To authenticate on SMTP server, just set AuthMethod, UserName and Password properties of SMTP object prior to calling Send method.

Values of UserName and Password properties are specific to each user, usually they are the same as the user account name and the password of the user's POP3 account on the same mail server.

AuthMethod property denotes type of the procedure to be used to authenticate user on the SMTP server. Value of 2 (LOGIN authentication) is supported by most SMTP servers. MSN servers require to use value of 5 (MSN authentication).

E-mails are still not sent. Any ideas?

In rare cases, e-mails are not being sent even if SMTP authentication is used. Typical reasons: the SMTP server is down, it rejects your IP-address, size of the e-mail you are trying to send is out of quota, some of the recipients are invalid or not allowed, etc.

To find-out what is the problem's source, you can analyze MailBee log file or the values of ErrCode and ServerResponse properties.

To force MailBee to create log file, set EnableLogging and LogFilePath properties. Also, you can add ClearLog method call to clear log file on each run.

Sample code description

The sample below sends the same e-mail as in the previous sample, but connects to the SMTP server using SMTP authentication, logs SMTP session into a file, and notifies user about errors.

Code example:

Dim Mailer

'Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")
'
' Also, in ASP use Response.Write instead of MsgBox

' Enable logging and clear log file
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.EnableLogging = True
Mailer.ClearLog

' Unlock MailBee.SMTP object
Mailer.LicenseKey = "put your license key here"

' SMTP server name
Mailer.ServerName = "mail.server.com"

' Set SMTP Authentication properties
Mailer.AuthMethod = 2
Mailer.Username = "username"
Mailer.Password = "password"

' Set message properties
Mailer.Message.ToAddr = "you@yourdomain.com"
Mailer.Message.FromAddr = "me@mydomain.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "<html>Hello</html>"
Mailer.Message.BodyFormat = 1

' Try to send the e-mail
If Mailer.Send Then
  ' Succeeded ;-)
  MsgBox "Sent successfully"
Else
  ' Error :-(
  MsgBox "Error #" & Mailer.ErrCode & _
    ", Server responded:" & Mailer.ServerResponse
End If

' Close the SMTP session
Mailer.Disconnect

See Also:

Part 2 (Importing HTML file into message body)

Send Method


Creating and sending HTML-formatted messages (Part 2)

Importing HTML file into message body Summary: Briefly explains how to import HTML file into the message body and automatically attach pictures and other objects this HTML file depends on.

Tutorial map:
Part 1 - Sending simple HTML e-mail
Part 2 - Importing HTML file into message body
Part 3 - Assembling body text from different sources
Part 4 - Building alternative message body
Part 5 - Advanced topics

Message.ImportBodyText method reads content of the file specified in FilePath parameter into the message body. This is the only required parameter of ImportBodyText method.

Because message body may have various formats (usually plain-text and HTML), ImportBodyText also supports optional parameter HTMLImport that denotes whether to treat the content as plain-text or as HTML.

If HTMLImport=False (this is default value), the file content is just copied into message body and the body is marked as plain-text.

If used for importing HTML (HTMLImport=True), the body is marked as HTML, and ImportBodyText method also parses imported HTML document looking for any objects related to the document (such as images, scripts and stylesheets). Every object found is appended to the message as inline attachment.

Code example:

Dim Mailer

'Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.site.com"

Mailer.Message.ToAddr = "Bill Smith<bill@server1.com>, Dex<dex1979@server2.com>"
Mailer.Message.FromAddr = "John Doe <jdoe@site.com>"
Mailer.Message.Subject = "This is HTML message"

' Import "email.htm" file as HTML (including embedded pictures, scripts, etc.)
' If related images/scripts/etc are available on the disk, they will be added as
' inline attachments (i.e. embedded objects)
Mailer.Message.ImportBodyText "C:\docs\email.htm", True

Mailer.Send
Mailer.Disconnect

See Also:

Part 3 (Assembling body text from different sources)

ImportBodyText Method


Creating and sending HTML-formatted messages (Part 3)

Assembling body text from different sources Summary: Shows various ways to create HTML body of the message.

Tutorial map:
Part 1 - Sending simple HTML e-mail
Part 2 - Importing HTML file into message body
Part 3 - Assembling body text from different sources
Part 4 - Building alternative message body
Part 5 - Advanced topics

Message body content is actually stored in BodyText property of the Message object.

Body format (plain-text, HTML, etc.) is specified through BodyFormat property.

If you already have HTML file that you want to be used as message body, use ImportBodyText method (see Part 2). However, if the file is not available, you can set BodyText property's value manually.

Note: ImportBodyText method sets BodyFormat property itself. However, if ImportBodyText is not used, you have to specify BodyFormat explicitly.

Code example:

' The code below is common for all examples in this topic

Dim Mailer

' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' The code below is specific to this sample

Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "<html><body>HTML Text here</body></html>"

' Mark that body as HTML body
Mailer.Message.BodyFormat = 1

Mailer.Send
Mailer.Disconnect

Sometimes you already have HTML file you want to be imported into message body, but you also want some additional content to be placed into the body (before or after HTML section imported from the file). Another case is when you want to import several files into the same message body (for example, if every file contains incomplete HTML such as Table).

ImportBodyText method of the Message object also supports optional parameter AppendMode that tells MailBee to do not overwrite existing message body, but extend it with new content instead.

You can mix ImportBodyText method calls with direct modifications of BodyText property's value. Sample below uses this technique: Opening and closing tags are set directly in code, but intermediate content is taken from files using ImportBodyText method.

Code example:

' The code below is common for all examples in this topic

Dim Mailer

' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' The code below is specific to this sample

Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"

' Set opening tags of HTML body
Mailer.Message.BodyText = "<html><body>"

' Append 1-st file to HTML body
Mailer.Message.ImportBodyText "C:\docs\email_part1.htm", True, True

' Append 2-nd file to HTML body
Mailer.Message.ImportBodyText "C:\docs\email_part2.htm", True, True

' Add closing tags to HTML body
Mailer.Message.BodyText = Mailer.Message.BodyText & "</body></html>"

' BodyFormat is already set by ImportBodyText method,
' but for clarity, we set it explicitly.
Mailer.Message.BodyFormat = 1

Mailer.Send
Mailer.Disconnect

See Also:

Part 4 (Building alternative message body)

ImportBodyText Method
BodyText Property
BodyFormat Property


Creating and sending HTML-formatted messages (Part 4)

Building alternative message body Summary: Discusses various methods of supplying alternative plain-text body in addition to main HTML body of the message.

Tutorial map:
Part 1 - Sending simple HTML e-mail
Part 2 - Importing HTML file into message body
Part 3 - Assembling body text from different sources
Part 4 - Building alternative message body
Part 5 - Advanced topics

HTML-formatted email messages often provide plain-text version of their content (it is called alternative body). If alternative body is present in a message such message can be also viewed with older email clients that do not provide HTML support.

If you already have text file that you want to be used as alternative message body, use ImportAltBodyText method.

Code example:

' The code below is common for all examples in this topic

Dim Mailer

' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' The code below is specific to this sample

Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"

' Import "email.htm" into HTML body
Mailer.Message.ImportBodyText "C:\docs\email.htm", True

' Import plain-text version of email into plain-text body
Mailer.Message.ImportAltBodyText "C:\docs\email.txt"

Mailer.Send

However, if plain-text version of the body is not available, MailBee can create it for you.

MakeAltBody method of the Message object converts value of BodyText property into plain form and places the result into AltBodyText property's value.

Code example:

' The code below is common for all examples in this topic

Dim Mailer
' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' The code below is specific to this sample

Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"

' Import email.htm into HTML body
Mailer.Message.ImportBodyText "C:\docs\email.htm", True

' Generate alternative plain-text body from HTML body
Mailer.Message.MakeAltBody

Mailer.Send
Mailer.Disconnect

Finally, you can generate alternative body manually. Also, you can create alternative body using MakeAltBody method and then manually edit generated alternative body.

Alternative body content is actually stored in AltBodyText property. You can read or modify it the same way as BodyText property.

Note: Unlike BodyFormat, there is no AltBodyFormat property because alternative body is always plain-text.

Code example:

' The code below is common for all examples in this topic

Dim Mailer

' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' The code below is specific to this sample

Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"

' Import email.htm into HTML body
Mailer.Message.ImportBodyText "C:\docs\email.htm", True

' Generate alternative plain-text code using
' another method (which allows to get plain-text
' version of any HTML source, not necessarily
' BodyText property value)
Mailer.Message.AltBodyText = _
  Mailer.Message.GetPlainFromHtml(Mailer.Message.BodyText)

Mailer.Send
Mailer.Disconnect

See Also:

Part 5 (Advanced topics)

ImportAltBodyText Method
GetPlainFromHtml Method
AltBodyText Property


Creating and sending HTML-formatted messages (Part 5)

Advanced topics Summary: Covers body and alternative body encoding usage and limitations. Compares encoding methods available in MailBee (Quoted-Printable and Base64).

Tutorial map:
Part 1 - Sending simple HTML e-mail
Part 2 - Importing HTML file into message body
Part 3 - Assembling body text from different sources
Part 4 - Building alternative message body
Part 5 - Advanced topics

HTML documents may contain symbols that are not allowed by email standards. For example, some mail gateways truncate all 8bit symbols to 7bit making it's impossible for extended characters (with ASCII codes bigger than 127) to pass through such gateways.

The process of encoding converts source text into form that can be freely transmitted by all mail gateways. Once received, the text is decoded, and original text is restored.

Different encoding methods fit better for different text patterns. If the source contains mostly 7bit characters, Quoted-Printable encoding is preferred. Base64 encoding is more suitable for binary data (binaries usually contain lots of 8bit characters) or for texts written in extended charsets such as UTF-8 or Cyrillic.

Default BodyEncoding setting is Quoted-Printable (QP for short).

Note 1: You might need to change default encoding setting only if you are concerned about the message body size (in some cases, Quoted-Printable is more space-consuming than Base64 or "no encoding" encodings) or if you have to support very old e-mail clients which do not support Quoted-Printable (in this case, you should use "no encoding" method BodyEncoding=0).

Note 2: The side (usually positive) effect of using Base64 or Quoted-Printable encoding instead of "no encoding" is keeping original line-wrapping of plain-text content (see FAQ for details).

Code example:

' The code below is common for all examples in this topic

Dim Mailer

' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' The code below is specific to this sample

Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"

' Put extended char (trademark character) into the body
Mailer.Message.BodyText = "<html><body>MailBeeT</body></html>"

' Set HTML format for the body
Mailer.Message.BodyFormat = 1

' Force Quoted-Printable (QP) encoding.
' However, QP is a default setting, so the next
' line can be omitted, and shown for clarity only
Mailer.Message.BodyEncoding = 2

Mailer.Send
Mailer.Disconnect

If the message includes alternative body (AltBodyText is non-empty), it's recommended to encode this body too.

AltBodyEncoding property sets encoding method for AltBodyText in the same manner as BodyEncoding sets encoding for BodyText.

Code example:

' The code below is common for all examples in this topic

Dim Mailer
' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")

Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' The code below is specific to this sample

Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"

' Put extended char (trademark character) into HTML body
Mailer.Message.BodyText = "<html><body>MailBeeT</body></html>"

' Put extended char (trademark character) into plain-text body
Mailer.Message.AltBodyText = "MailBeeT"

' Set HTML format for the body
Mailer.Message.BodyFormat = 1

' Enable Base64 encoding.
' In fact, QP is more efficient here,
' so Base64 is used for illustration purposes only.
Mailer.Message.AltBodyEncoding = 3

' Enable QP encoding to illustrate that
' HTML body and plain-text body can use
' different encoding methods
Mailer.Message.BodyEncoding = 2

Mailer.Send
Mailer.Disconnect

See Also:

BodyEncoding Property
AltBodyEncoding Property


Displaying HTML-formatted messages (Part 1)

Quickly display e-mail with inline pictures Summary: Discusses displaying HTML-formatted e-mail messages using ASP, including handling embedded (inline) objects.

Tutorial map:

Part 1 - Quickly display e-mail with inline pictures
Part 2 - Using temporary filenames for embedded objects
Part 3 - Removing temporary files after use
Part 4 - Advanced topics

HTML messages often contain embedded pictures, sounds, scripts, style-sheets, etc. Usually HTML message refers them by URLs but quite often these objects are just attached to the message (they called inline objects). In order to correctly render HTML content, these objects must be saved to disk first.

GetBodyWithEmbeddedObjectsEx method of MailBee.Message object saves the message's embedded objects into temporary location (by default, the current user's temporary folder) and modifies URLs of these objects in HTML source to match their new locations. GetBodyWithEmbeddedObjectsEx returns modified HTML body text, original Message.BodyText property value is not affected.

GetBodyWithEmbeddedObjectsEx method takes into account the fact that files are saved under physical path (e.g. "c:\inetpub\wwwroot\test\data"), but correponding URL looks like "http://www.server.com/test/data", i.e. some physical path must be mapped to corresponding virtual path in order to be visible to the clients accessing the site.

GetBodyWithEmbeddedObjectsEx method supports several physical-to-virtual path mappings. DIRECT mode is the simplest case: some physical root is mapped to corresponding virtual root, and physical paths relative to physical root directly repeat virtual paths relative to virtual root. I.e. "c:\inetpub\wwwroot\test\data\dir1\picture.gif" is mapped into "http://www.server.com/test/data/dir1/picture.gif".

TempDirectoryPath parameter sets physical path to the location where temporary files will be stored.

VirtualPath parameter is a virtual path to the location specified by TempDirectoryPath physical path.

PathBuildingMode parameter sets physical-to-virtual mapping mode. To enable DIRECT mode, set PathBuildingMode=1.

Rest of parameters are not important for now, so leave them with the default values.

Note: TempDirectoryPath folder must have full-control permissions for the IIS account MailBee is running on (usually IUSR_<YOUR_SERVER_NAME>).

The code below prints HTML message to the user, saving all necessary files into physical location "c:\test_project\files" accessible from the web as "http://www.server.com/test/files"

Code example:

Dim objPOP3, objMsg
Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Mailbox not empty?
  If objPOP3.MessageCount > 0 Then

    ' Get a message
    Set objMsg = objPOP3.RetrieveSingleMessage(1)

    ' Save embedded images and display message body
    Response.Write _
      objMsg.GetBodyWithEmbeddedObjectsEx("c:\test_project\files", _
      "http://www.server.com/test/files", , 1)
  End If

  objPOP3.Disconnect
Else
  Response.Write objPOP3.ErrDesc
End If

See Also:

Part 2 (Using temporary filenames for embedded objects)

GetBodyWithEmbeddedObjectsEx Method


Displaying HTML-formatted messages (Part 2)

Using temporary filenames for embedded objects Summary: Explains usage of indexed filenames and downloader scripts for accessing embedded objects.

Tutorial map:

Part 1 - Quickly display e-mail with inline pictures
Part 2 - Using temporary filenames for embedded objects
Part 3 - Removing temporary files after use
Part 4 - Advanced topic

Advantages of INDEX path building mode

DIRECT path building mode (PathBuildingMode=1) highlighted in the Part 1 assumes that embedded objects are saved into temporary files under their real filenames. This approach causes problems when the message has two or more embedded objects under the same filename (this happens if these files were taken from different directories during message composing). In this case, all files will be saved under the same filename during GetBodyWithEmbeddedObjectsEx method execution, and each file will overwrite the previous one.

INDEX path building mode (PathBuildingMode=2) forces GetBodyWithEmbeddedObjectsEx method to use number-based filenames (such as "1.gif", "2.jpg", "3.jpg") for the embedded objects. Filename extensions ("gif", "jpg", etc.) remain unchanged while filenames themselves are replaced with numbers. Thus INDEX path building mode is free from the drawback discussed above.

Using SCRIPT path building mode

SCRIPT path building mode (PathBuildingMode=3) allows you to avoid using direct links to the files on your web server. Instead, resulting URL of the embedded object will contain the path to the page capable of downloading files to the users including parameters required to locate the file to download.

This downloader page is called script here, however, it may also be ISAPI DLL, EXE or any other valid path on the server capable of getting dynamic content to the user.

When using SCRIPT path building mode, VirtualPath parameter of GetBodyWithEmbeddedObjectsEx method must contain URL of the downloader script and the string of parameters you want to be passed to it. GetBodyWithEmbeddedObjectsEx method will also add two additional parameters to this URL and use it as a virtual path of the embedded object.

E.g. if:

VirtualPath = "http://www.server.com/email/download_file.asp?user_id=1",

then SRC attribute value of the tag referencing the embedded object will look like:

"http://www.server.com/email/download_file.asp?user_id=1&dir_id=6a7ca92bcce7ad6df6f21ebec50aed8a&file_id=1.gif".

If the URL you pass as a virtual path does not have your own parameters, add "?" to the end of it:

VirtualPath = "http://www.server.com/email/download_file.asp?".

Downloader script requirements

This script must recognize two parameters added by MailBee:

  • dir_id - the message directory name. MailBee creates this directory inside temporary location specified through TempDirectoryPath parameter of GetBodyWithEmbeddedObjectsEx method. All embedded objects for the message are stored there
  • file_id - filename (including extension) of the embedded object file inside dir_id directory
The downloader script must read the file under the following path (in ASP syntax):

FilePath = TempDirectoryPath & "\" & Request("dir_id") & "\" & Request("file_id")

Of course, TempDirectoryPath value used in this path must be equal to that used in GetBodyWithEmbeddedObjectsEx method call.

Finally, the file content must be put in response binary stream.

Note: TempDirectoryPath folder must have full-control permissions for the IIS account MailBee is running on (usually IUSR_<YOUR_SERVER_NAME>).

Generic pure-ASP downloader script sample is shown at the end of this page.

Higher security and flexibility through SCRIPT path building mode

Unlike other path building modes, SCRIPT mode does not require embedded object files to be visible from the web. This means you can easily restrict access to these files so they only may be accessed through downloader script. This script may check user permissions, prevent users from peeping other users' files, cancel unauthorized access, gather download statistics, and much more.

The code below prints HTML message to the user, saving all necessary files into physical location "c:\test_project\files" accessible through the downloader script at "http://www.server.com/test/download.asp"

Code example:

' HTML message viewer
Dim objPOP3, objMsg
Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"
' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Mailbox not empty?
  If objPOP3.MessageCount > 0 Then

    ' Get a message
    Set objMsg = objPOP3.RetrieveSingleMessage(1)

    ' Save embedded images and display message body. Embedded
    ' images will be available through "download.asp" script
    Response.Write _
      objMsg.GetBodyWithEmbeddedObjectsEx("c:\test_project\files", _
      "http://www.server.com/test/download.asp?", , 3)
  End If

  objPOP3.Disconnect
Else
  Response.Write objPOP3.ErrDesc
End If

Downloader script sample code below constructs file path assuming "c:\test_project\files" to be a temporary directory path. For simplicity, no user authentication or error checking is performed. Also, in real environments it's preferred to use specialized download components.

It's assumed this script can be accessed at "http://www.server.com/test/download.asp"

Code example:

' Downloader script.

' It takes "dir_id" and "file_id" parameters as input and downloads
' file located in the following directory:
' "c:\test_project\files\" & Request("dir_id") & "\" & Request("file_id")

Dim Msg

' Create MailBee.Message object
Set Msg = Server.CreateObject("MailBee.Message")

' Download file contents
Response.BinaryWrite Msg.GetFileAsArray("c:\test_project\files\" & _
  Request("dir_id") & "\" & Request("file_id"))

See Also:

Part 3 (Removing temporary files after use)

GetBodyWithEmbeddedObjectsEx Method


Displaying HTML-formatted messages (Part 3)

Removing temporary files after use Summary: Shows how to remove temporarily saved embedded objects.

Tutorial map:
Part 1 - Quickly display e-mail with inline pictures
Part 2 - Using temporary filenames for embedded objects
Part 3 - Removing temporary files after use
Part 4 - Advanced topics

When the user has finished viewing the message containing embedded objects, it's a time to delete all temporary files because they are no longer needed.

When GetBodyWithEmbeddedObjectsEx method of the Message object is called and embedded objects are present in the message, this Message object remembers the path to the saved temporary files. These files are stored in the special directory created by GetBodyWithEmbeddedObjectsEx method in the TempDirectoryPath directory. So, each message holds its temporary files in its own directory (called message directory), and all these directories are located in TempDirectoryPath directory.

Once GetBodyWithEmbeddedObjectsEx method was called, you may get the path to the message directory by obtaining value returned by GetMessageDirectoryPath method. Store this value in the Session, you will need it later.

Some time later the user clicks "Logout" button (or the Session expires due the user's inactivity), and clean-up script is executed. To delete all temporary data, this script must delete the message directory including all its contents.

To do this, call RemoveMessageDirectory method of the Message object, passing the message directory path stored in the Session as a value of MessageDirectoryPath parameter.

Note: Many (even most) emails do not contain embedded objects, and the message directory is not created for such messages. GetMessageDirectoryPath method returns empty string in this case. However, it's safe to call RemoveMessageDirectory method passing empty string as a parameter. It will just do nothing.

The sample below adds the message directory path storing to the sample from Part 2. The path is stored in the session variable named "strMessageDir".

Code example:

' HTML message viewer
Dim objPOP3, objMsg
Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then
  If objPOP3.MessageCount > 0 Then
    Set objMsg = objPOP3.RetrieveSingleMessage(1)
    Response.Write _
      objMsg.GetBodyWithEmbeddedObjectsEx("c:\test_project\files", _
      "http://www.server.com/test/download.asp?", , 3)
    Session("strMessageDir") = objMsg.GetTemporaryDirectoryPath
  End If
  objPOP3.Disconnect
Else
  Response.Write objPOP3.ErrDesc
End If

Sample code below is a script that should be called whenever clean-up takes place (logout and session expiration are common examples).

The script assumes the message directory path is stored in "strMessageDir" session variable.

Code example:

' Temporary files remover
Dim objMsg
Set objMsg = Server.CreateObject("MailBee.Message")
objMsg.RemoveMessageDirectory Session("strMessageDir")

See Also:

Part 4 (Advanced topics)

GetBodyWithEmbeddedObjectsEx Method
RemoveMessageDirectory Method
GetMessageDirectoryPath Method


Displaying HTML-formatted messages (Part 4)

Advanced topics Summary: Briefly covers usage of optional parameters of previously discussed methods. Lists additional methods useful for embedded objects management.

Tutorial map:
Part 1 - Quickly display e-mail with inline pictures
Part 2 - Using temporary filenames for embedded objects
Part 3 - Removing temporary files after use
Part 4 - Advanced topics

GetBodyWithEmbeddedObjectsEx method supports additional parameters that may be useful for advanced applications. Also, Message object provides several subsidiary methods related to the topic.
Overriding defaults

You can use custom name for message directory created by MailBee in the temporary folder (use MessageDirectoryName parameter of GetBodyWithEmbeddedObjects method). By default, message directory name is generated as MD5-digest of Message-ID. This is fine for most applications but you may override this if you need.

RemoveMessageDirectory method provides an option to delete only the directory content but not delete the directory itself - DeleteContentOnly parameter. By the way,
RemoveMessageDirectory method can be used for deleting or clearing any directories, not necessarily created by MailBee.

Getting info on message directory path

You may check whether message directory exists and it is a folder (not a file) using MessageDirectoryExists method. You may also use this method for testing "is the path is a directory" for any file paths, not necessarily related to MailBee.

To manually get MD5-digest of Message-ID (by default, this digest is used as a message directory name), use GetMD5Digest method. You may also use it for getting MD5 digests of any strings.

"Viewing e-mail securely" sample

The sample below displays HTML message.

Code example:

' HTML message viewer
Dim objPOP3, objMsg

Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"
If objPOP3.Connect("mail.server.com", 110, "test", "pass") Then
  If objPOP3.MessageCount > 0 Then
    Set objMsg = objPOP3.RetrieveSingleMessage(1)
    Response.Write _
      objMsg.GetBodyWithEmbeddedObjectsEx("c:\test_project\files", _
      "http://www.server.com/test/download.asp?", , 3, )
    Session("strMessageDir") = objMsg.GetMessageDirectoryPath
  End If
  objPOP3.Disconnect
Else
  Response.Write objPOP3.ErrDesc
End If

See Also:

GetBodyWithEmbeddedObjectsEx Method
RemoveMessageDirectory Method
GetMessageDirectoryPath Method
MessageDirectoryExists Method
GetMD5Digest Method


Displaying HTML-formatted messages (Part 1)

Quickly display e-mail with inline pictures Summary: Discusses displaying HTML-formatted e-mail messages in a WebBrowser control, including handling embedded objects.

Tutorial map:

Part 1 - Quickly display e-mail with inline pictures
Part 2 - Removing temporary files after use
Part 3 - Advanced topics

HTML messages often contain embedded pictures, sounds, scripts, style-sheets, etc. In order correctly render HTML content, these embedded objects must be saved to disk first.

GetBodyWithEmbeddedObjectsEx method of MailBee.Message object saves the message's embedded objects into temporary location and modifies URLs of these objects in HTML source to match their new locations. GetBodyWithEmbeddedObjectsEx returns modified HTML body text, original Message.BodyText property value is not affected.

By default all embedded objects are saved somewhere in the current user's temporary folder.

Note: When the message is received from POP3 server, no temporary files are created (MailBee processes e-mails "in-memory" manner). Only explicit call of GetBodyWithEmbeddedObjectsEx method may cause some files to be saved.

GetBodyWithEmbeddedObjectsEx method supports several parameters but all of them are optional. So, in the simplest case HTML message may be displayed like in the code below:

Code example:

' Assume objWebBrowser is a valid WebBrowser control
' (It's included in Microsoft Internet Controls type library).

' This sample is for VB only, ASP samples are discussed in another tutorial

Dim objPOP3, objMsg

Set objPOP3 = CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then
  If objPOP3.MessageCount > 0 Then
    Set objMsg = objPOP3.RetrieveSingleMessage(1)

    ' This code is required to create Document object within objWebBrowser
    objWebBrowser.Navigate "about:blank"
    While objWebBrowser.Document Is Nothing
      DoEvents
    Wend

    ' Print prepared body text into WebBrowser control (objWebBrowser object)
    objWebBrowser.Document.Write objMsg.GetBodyWithEmbeddedObjectsEx
  End If
  objPOP3.Disconnect
Else
  MsgBox objPOP3.ErrDesc
End If

See Also:

Part 2 (Removing temporary files after use)

GetBodyWithEmbeddedObjectsEx Method


Displaying HTML-formatted messages (Part 2)

Removing temporary files after use Summary: Shows how to remove temporarily saved embedded objects.

Tutorial map:
Part 1 - Quickly display e-mail with inline pictures
Part 2 - Removing temporary files after use
Part 3 - Advanced topics

When the user has finished viewing the message containing embedded objects, it's a time to delete all temporary files because they are no longer needed.

When GetBodyWithEmbeddedObjects method of the Message object is called and embedded objects are present in the message, this Message object remembers the path to the saved temporary files. These files are stored in the special directory created by GetBodyWithEmbeddedObjectsEx method in the current user's temporary directory. So, each message holds its temporary files in its own directory (called message directory), and all these directories are located in the current user's temporary directory.

To perform files clean-up it's enough to call RemoveMessageDirectory method of the Message object.

RemoveMessageDirectory method gets message directory path stored in the Message object by GetBodyWithEmbeddedObjectsEx method call, and deletes the folder under this path. The folder content is also removed. If the message had no embedded objects, it's still safe to call this method. It just does nothing in such a case.

Note: It's important to understand that RemoveMessageDirectory method must be called for THE SAME Message object instance that was previously used for GetBodyWithEmbeddedObjectsEx method call.

For this purpose, the sample code below declares the Message object as global (not local, within a subroutine or a function) to keep it alive until the user has finished viewing the message.

The sample below displays the message on Command1_Click event and cleans-up on Form_Unload. The Message object is a global variable, so Form_Unload sub operates with the same instance of the Message object as that one previously set in Command1_Click.

Code example:

' Assume objWebBrowser is a valid WebBrowser control
' (It's included in Microsoft Internet Controls type library).

' This sample is for VB only, ASP samples are discussed in another tutorial

Dim objPOP3, objMsg

Private Sub Command1_Click()
  Set objMsg = Nothing
  Set objPOP3 = CreateObject("MailBee.POP3")
  objPOP3.LicenseKey = "put your license key here"
  If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then
    If objPOP3.MessageCount > 0 Then
      Set objMsg = objPOP3.RetrieveSingleMessage(1)
      objWebBrowser.Document.Write objMsg.GetBodyWithEmbeddedObjectsEx(, , , 4, , )
    End If
    objPOP3.Disconnect
  Else
    MsgBox objPOP3.ErrDesc
  End If
End Sub

Private Sub Form_Load()
  Set objMsg = Nothing
  objWebBrowser.Navigate "about:blank"
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If Not objMsg Is Nothing Then
    objMsg.RemoveMessageDirectory
  End If
End Sub

See Also:

Part 3 (Advanced topics)

GetBodyWithEmbeddedObjectsEx Method
RemoveMessageDirectory Method


Displaying HTML-formatted messages (Part 3)

Advanced topics Summary: Briefly covers usage of optional paramaters of previously discussed methods. Lists additional methods useful for embedded objects management.

Tutorial map:
Part 1 - Quickly display e-mail with inline pictures
Part 2 - Removing temporary files after use
Part 3 - Advanced topics

GetBodyWithEmbeddedObjectsEx and RemoveMessageDirectory methods support additional parameters that may be useful for advanced applications.

Making e-mail safe and secure

Overriding defaults

By default, GetBodyWithEmbeddedObjectsEx creates message folder in the current user's temporary folder (usually something like "C:\Documents and Settings\UserName\Local Settings\Temp", but this is OS-dependent). However, TempDirectoryPath parameter of GetBodyWithEmbeddedObjectsEx method allows you to use any path for the temporary folder.

You can also provide custom name for message directory created by MailBee in the temporary folder (use MessageDirectoryName parameter of GetBodyWithEmbeddedObjectsEx method). By default, message directory name is generated as MD5-digest of Message-ID. This is fine for most applications but you may override this if you need.

RemoveMessageDirectory method supports MessageDirectoryPath parameter, which overrides message directory path stored in the Message object. You may use it for deleting message directory if corresponding Message object (and the path stored inside) already gone. You may even delete any (not related to MailBee) directories. Also, there is an option to delete only the directory content but not delete the directory itself - DeleteContentOnly parameter.

Getting info on message directory path

Once GetBodyWithEmbeddedObjectsEx was called, you may obtain path to the message directory using GetMessageDirectoryPath method. You may store this value and then pass it as a value of MessageDirectoryPath parameter of RemoveMessageDirectory method. If GetMessageDirectoryPath returns empty string, this means the message has no embedded objects and corresponding message directory was not created.

You may check whether message directory exists and it is a folder (not a file) using MessageDirectoryExists method.

To manually get MD5-digest of Message-ID (by default, this digest is used as a message directory name), use GetMD5Digest method. You may also use it for getting MD5 digests of any strings.

We're also setting PathBuildingMode parameter to 4 (DIRECT and INDEX hybrid mode) which provides more accurate processing of inline attachments with the same filename. E-mails can have multiple inline attachments with the same filename (e.g. picture.gif) and to avoid saving them under the same filename (thus overwriting some of them), we need to be sure that each file is saved under a unique filename by adding a suffix.

All together

The sample below displays the message on Command1_Click event and cleans-up on Form_Unload. Now the Message object is a not a global variable. Instead, only the message directory path is stored in global variable.

Code example:

' Assume objWebBrowser is a valid WebBrowser control
' (It's included in Microsoft Internet Controls type library).

' This sample is for VB only, ASP samples are discussed in another tutorial

Dim strPath

Private Sub Command1_Click()
  Dim objPOP3, objMsg

  Set objPOP3 = CreateObject("MailBee.POP3")
  objPOP3.LicenseKey = "put your license key here"
  If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then
    If objPOP3.MessageCount > 0 Then
      Set objMsg = objPOP3.RetrieveSingleMessage(1)
      objWebBrowser.Document.Write objMsg.GetBodyWithEmbeddedObjectsEx(, , , 4, , )
      strPath = objMsg.GetMessageDirectoryPath
    End If
    objPOP3.Disconnect
  Else
    MsgBox objPOP3.ErrDesc
  End If
End Sub

Private Sub Form_Load()
  strPath = ""
  objWebBrowser.Navigate "about:blank"
End Sub

Private Sub Form_Unload(Cancel As Integer)
  Dim objMsg

  If strPath <> "" Then
    Set objMsg = CreateObject("MailBee.Message")
    objMsg.RemoveMessageDirectory strPath
  End If
End Sub

See Also:

GetBodyWithEmbeddedObjects Method
RemoveMessageDirectory Method
GetMessageDirectoryPath Method
MessageDirectoryExists Method
GetMD5Digest Method


Receiving message headers from POP3 server (Part 1)

Downloading the list of messages Summary: Demonstrates using POP3 object for building messages' list without downloading entire messages.

Tutorial map:
Part 1 - Downloading the list of messages
Part 2 - Detecting attachments
Part 3 - Retrieve a few body lines along with the headers

Many e-mail applications give users ability to select the messages to be retrieved from the list of messages available in the mailbox on the server. To build this list it's required to get some preview information on each message in the mailbox. For POP3, this information is message header.

Retrieving headers for all the messages in the mailbox

RetrieveHeaders method of POP3 object retrieves headers for all messages in the mailbox, and returns Messages collection which represents message list (if an error occurs, returned value is Nothing). Messages are returned in the same order they are located in the mailbox: first message is oldest, last is newest.

The sample code below prints "From:" fields of all messages in the mailbox.

Code example:

<%
Dim objPOP3, objMsg, colMsgs

Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Download headers for all messages
  Set colMsgs = objPOP3.RetrieveHeaders

  If objPOP3.IsError Then
    ' Handle errors
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  Else
    For Each objMsg In colMsgs
      ' Print "From:" field for each e-mail in the mailbox.
      ' We use HTMLEncode to convert '<' and '>' chars
      ' which often appear in e-mail addresses.
      Response.Write Server.HTMLEncode(objMsg.FromAddr) & "<br>"
    Next
  End If

  objPOP3.Disconnect
Else
  ' Handle errors
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If
%>

Reverse-order iterating through the collection of retrieved headers

It's often required to display messages in the order different from the order they appear in the returned collection. Another case is when you need to learn index of particular message for further processing (e.g. delete particular message from the server).

To iterate through the collection in arbitrary way, you can use For..To..Step syntax instead of simple but not flexible For..Each one.

The sample code below differs from the previous sample in that it prints "From:" values in reverse order (from newest messages to oldest ones) using For..To..Step syntax. Additionally, it deletes from the mailbox the messages having "remove" word in the "Subject:" field.

Code example:

<%
Dim objPOP3, colMsgs, I

Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Download headers for all messages
  Set colMsgs = objPOP3.RetrieveHeaders

  If objPOP3.IsError Then
    ' Handle errors
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  Else
    ' For each e-mail in the mailbox, starting from latest...
    For I = colMsgs.Count To 1 Step -1

      ' Display "From:" field
      Response.Write Server.HTMLEncode(colMsgs(I).FromAddr) & "<br>"

      If colMsgs(I).Subject = "remove" Then
        ' Delete message with "remove" in Subject
        objPOP3.DeleteMessage I
      End If
    Next
  End If

  objPOP3.Disconnect
Else
  ' Handle errors
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If
%>

Retrieving headers for the particular message

Sometimes you might need to download headers for particular messages only. Common cases are:

  • the mailbox contains large number of messages (hundreds or thousands), and you want to download only 10-20 headers (usually for displaying message list on per-page basis);
  • specific needs of your task. For example, your application uses some kind of database to maintain messages, and only new messages should be searched and/or received;
  • some messages were marked for deletion (using DeleteMessage method) and become unretrievalable. Presence of such messages will cause RetrieveHeaders to fail. Note that messages marked for deletion will be permanently deleted once Disconnect method is called, so you will never face the issue above if you never attempt to retrieve messages after marking some of them for deletion.
You can retrieve headers for single message using RetrieveSingleMessageHeaders method.

The sample code prints "From:" fields of K messages starting from message number N. For example, if N = 1, first K message headers are retrieved; if N = 21, K = 10 and there are 30 or more messages available, message headers from 21 to 30 will be retrieved. If N = 21, K = 10 but only 25 messages exist in the mailbox, message headers from 21 to 25 will be retrieved. Messages are returned in direct order (i.e. assumed that N = 1 corresponds to the first message in the mailbox).

Code example:

<%
Dim objPOP3, objMsg, I, N, B1, B2, K

Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Start from message #21
  N = 21

  ' Retrieve 10 message headers: from #21 to #30
  K = 10

  ' Lower boundary of the range to retrieve
  B1 = N

  ' Upper boundary of the range to retrieve
  B2 = N + K - 1

  ' Limit upper boundary by ordinal position
  ' of the last message in the mailbox
  If B2 > objPOP3.MessageCount Then
    B2 = objPOP3.MessageCount
  End If

  ' Loop through messages in the specified range
  For I = B1 To B2

    ' Get message headers
    Set objMsg = objPOP3.RetrieveSingleMessageHeaders(I)

    If objPOP3.IsError Then
      ' Handle errors
      Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
    Else
      ' Display "From:" field
      Response.Write Server.HTMLEncode(objMsg.FromAddr) & "<br>"
    End If
  Next

  objPOP3.Disconnect
Else
  ' Handle errors
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If
%>

See Also:

Part 2 (Detecting attachments)

RetrieveHeaders Method
RetrieveSingleMessageHeaders Method


Receiving message headers from POP3 server (Part 2)

Detecting attachments Summary: Highlights detecting whether the message has attachments when only message headers are available.

Tutorial map:
Part 1 - Downloading the list of messages
Part 2 - Detecting attachments
Part 3 - Retrieve a few body lines along with the headers

When displaying message list to user, it's common to show paper-clip for messages with attachments.

The POP3 protocol (unlike IMAP4) does not provide a mechanism to preview attachments. Fortunately, most messages with attachments have some specifics in their headers. This allows MailBee to detect attachments even if only message headers are available.

Message.HasAttachments property returns True if the message has one or more attachments.

However, Message.HasAttachments property is not 100% accurate: in rare cases, message headers do not conform to message contents.

100% reliable way to detect attachments is to download the message completely. For complete messages, Message.HasAttachments property is 100% accurate.

Sample code description

The sample code prints the information regarding attachments presense for each message in the mailbox.

Code example:

<%
Dim objPOP3, colMsgs, I, strInfo

Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Download headers for all messages
  Set colMsgs = objPOP3.RetrieveHeaders
  If objPOP3.IsError Then
    ' Handle errors
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  Else
    For I = 1 To objPOP3.MessageCount

      ' Add message number to string
      strInfo = "Message #" & I

      ' Detect attachment presence and
      ' add the results to string
      If colMsgs(I).HasAttachments Then
        strInfo = strInfo & " has attachment(s)"
      Else
        strInfo = strInfo & " has no attachment(s)"
      End If

      ' Print the string with the results
      Response.Write strInfo & "<br>"
    Next
  End If

  objPOP3.Disconnect
Else
  ' Handle errors
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If
%>

See Also:

Part 3 (Retrieve a few body lines along with the headers)

RetrieveHeaders Method

Message.HasAttachments Property


Receiving message headers from POP3 server (Part 3)

Retrieve a few body lines along with the headers Summary: Demostrates how to get a few lines of the body in addition to message headers when retrieving the list of messages from POP3 server.

Tutorial map:
Part 1 - Downloading the list of messages
Part 2 - Detecting attachments
Part 3 - Retrieve a few body lines along with the headers

In some cases, you may need to get somewhat more than just message headers. Often, contents of "From:" and "Subject:" fields don't answer "what is the message about?" question.

Fortunately, RetrieveHeaders and RetrieveSingleMessageHeaders methods support optional parameter BodyLinesCount which specifies how many lines of the body to retrieve in addition to the headers.

The larger BodyLinesCount, bigger piece of the body is returned and more traffic is produced. If BodyLinesCount is larger then actual number of body lines in the message, the entire message is returned. Typically, 20-40 lines of the body describe the message quite enough.

Note: Avoid setting BodyLinesCount to very small values (less than 20). Many e-mail messages have some special (non-textual) information in the first 5-10 lines of the body while the actual body text starts after these lines.

Detailed information on partial messages internals

Note: You may immediatel go to the sample code and skip reading this topic unless you want to deal with partial messages in advanced ways.

For MailBee parser (the module which converts messages into Message objects), there is no difference between entire or partial messages. Available content is fully parsed anyway. Thus, if retrieved piece of the message contains any attachments, they will be parsed and added into Attachments collection but the size and the contents of the attachment will be incorrect if the attachment is not entirely received. Those attachments which didn't fall into the scope of retrieved piece, will not be appended to Attachments collection at all. In other words, MailBee puts into Message object all the information available in the partial message even if the information on some part of the message is incomplete.

So, if you have 1 attachment (named "abc.gif" and sized 1234 bytes) in retrieved partial message, you can guarantee that full message contains AT LEAST one attachment (named "abc.gif") and the size of this attachment is NOT LESS THAN 1234 bytes.

However, if you have 2 attachments in retrieved partial message, you can guarantee that first attachment is retrieved completely and its size and contents correspond to real values. This is due the fact that attachments located in the message and added to Attachments collection sequentially, so each new object guarantees that previous object is finished.

Be aware that text bodies do not behave the same since they often depend on each other while attachments are independent. E.g. retrieved piece contains part of the plain-text body but the message itself is HTML-formatted (its HTML part just did not fall into retrieved piece). Such message will appear as plain-text (BodyFormat=0) or HTML (BodyFormat=1) when retrieved with different BodyLinesCount value.

On other hand, if HTML body is first part and it was partially loaded while plain-text part was not loaded at all (BodyLinesCount is not large), the plain-text part will be generated by MailBee using "HTML-to-plaintext" tool. Increasing BodyLinesCount will cause HTML part to be retrieved completely and plain-text part - partially. Now plain-text body will be taken from partially retrieved plain-text part, not from HTML part plained by MailBee.

Briefly speaking, the information such as body/attachment content or size can be incomplete and greatly dependent on BodyLinesCount value for partial messages.

Note: Message size (Message.Size property) is ALWAYS correct even if only message headers are retrieved. MailBee gets the message size using special POP3 command.

Sample code description

The sample code below gets message headers + 100 first lines of the body part and prints first line of the text body. The sample performs this for each message in the mailbox.

Code example:

<%
Dim objPOP3, objMsg, colMsgs

' First line of the text body
Dim strLine

Set objPOP3 = Server.CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Download headers + 100 body lines
  Set colMsgs = objPOP3.RetrieveHeaders(1, -1, 100)

  If objPOP3.IsError Then
    ' Handle errors
    Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  Else
    For Each objMsg In colMsgs

      ' Store available body text lines in the variable
      strLine = objMsg.BodyText

      ' Keep only 1 line of all available body text
      If InStr(strLine, vbCrLf) > 0 Then
        strLine = Left(strLine, InStr(strLine, vbCrLf))
      End If

      ' Print the first line of the body
      Response.Write strLine & "<br>"
    Next
  End If

  objPOP3.Disconnect
Else
  ' Handle errors
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If
%>

See Also:

RetrieveHeaders Method
RetrieveSingleMessageHeaders Method


Receiving message headers from POP3 server (Part 1)

Downloading the list of messages Summary: Demonstrates using POP3 object for building messages' list without downloading entire messages.

Tutorial map:
Part 1 - Downloading the list of messages
Part 2 - Detecting attachments
Part 3 - Retrieve a few body lines along with the headers

Many e-mail applications give users ability to select the messages to be retrieved from the list of messages available in the mailbox on the server. To build this list it's required to get some preview information on each message in the mailbox. For POP3, this information is message header.

Retrieving headers for all the messages in the mailbox

RetrieveHeaders method of POP3 object retrieves headers for all messages in the mailbox, and returns Messages collection which represents message list (if an error occurs, returned value is Nothing). Messages are returned in the same order they are located in the mailbox: first message is oldest, last is newest.

The sample code below fills ListBox control with "From:" fields of all messages in the mailbox. It's assumed VB form already contains ListBox control named List1.

Code example:

' You can place the code below into any Sub or Function of your app

Dim objPOP3, objMsg, colMsgs

Set objPOP3 = CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Download headers for all messages
  Set colMsgs = objPOP3.RetrieveHeaders

  If objPOP3.IsError Then
    ' Handle errors
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  Else
    For Each objMsg In colMsgs
      ' Add "From:" to ListBox
      List1.AddItem objMsg.FromAddr
    Next
  End If

  objPOP3.Disconnect
Else
  ' Handle errors
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If

Reverse-order iterating through the collection of retrieved headers

It's often required to display messages in the order different from the order they appear in the returned collection. Another case is when you need to learn index of particular message for further processing (e.g. delete particular message from the server).

To iterate through the collection in arbitrary way, you can use For..To..Step syntax instead of simple but not flexible For..Each one.

The sample code below differs from the previous sample in that it fills ListBox control in reverse order (from newest to oldest) using For..To..Step syntax. Additionally, it deletes from the mailbox the messages having "remove" word in the "Subject:" field.

Code example:

' You can place the code below into any Sub or Function of your app

Dim objPOP3, colMsgs, I

Set objPOP3 = CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Download headers for all messages
  Set colMsgs = objPOP3.RetrieveHeaders

  If objPOP3.IsError Then
    ' Handle errors
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  Else
    For I = colMsgs.Count To 1 Step -1

      ' Add "From:" to ListBox
      List1.AddItem colMsgs(I).FromAddr

      If colMsgs(I).Subject = "remove" Then
        ' Delete message with "remove" in Subject
        objPOP3.DeleteMessage I
      End If
    Next
  End If
  objPOP3.Disconnect
Else
  ' Handle errors
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If

Retrieving headers for the particular message

Sometimes you might need to download headers for particular messages only. Common cases are:

  • the mailbox contains large number of messages (hundreds or thousands), and you want to download only 10-20 headers (usually for displaying message list on per-page basis);
  • specific needs of your task. For example, your application uses some kind of database to maintain messages, and only new messages should be searched and/or received;
  • some messages were marked for deletion (using DeleteMessage method) and become unretrievalable. Presence of such messages will cause RetrieveHeaders to fail. Note that messages marked for deletion will be permanently deleted once Disconnect method is called, so you will never face the issue above if you never attempt to retrieve messages after marking some of them for deletion.
You can retrieve headers for single message using RetrieveSingleMessageHeaders method.

The sample code below fills ListBox control with "From:" fields of K messages starting from message number N. For example, if N = 1, first K message headers are retrieved; if N = 21, K = 10 and there are 30 or more messages available, message headers from 21 to 30 will be retrieved. If N = 21, K = 10 but only 25 messages exist in the mailbox, message headers from 21 to 25 will be retrieved. Messages are returned in direct order (i.e. assumed that N = 1 corresponds to the first message in the mailbox).

Code example:

' You can place the code below into any Sub or Function of your app

Dim objPOP3, objMsg, I, N, B1, B2, K

Set objPOP3 = CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Start from message #21
  N = 21

  ' Retrieve 10 message headers: from #21 to #30
  K = 10

  ' Lower boundary of the range to retrieve
  B1 = N

  ' Upper boundary of the range to retrieve
  B2 = N + K - 1

  ' Limit upper boundary by ordinal position
  ' of the last message in the mailbox
  If B2 > objPOP3.MessageCount Then
    B2 = objPOP3.MessageCount
  End If

  ' Loop through messages in the specified range
  For I = B1 To B2

    ' Get message headers
    Set objMsg = objPOP3.RetrieveSingleMessageHeaders(I)

    If objPOP3.IsError Then
      ' Handle errors
      MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
    Else
      ' Add "From:" to ListBox
      List1.AddItem objMsg.FromAddr
    End If
  Next

  objPOP3.Disconnect
Else
  ' Handle errors
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If

See Also:

Part 2 (Detecting attachments)

RetrieveHeaders Method
RetrieveSingleMessageHeaders Method


Receiving message headers from POP3 server (Part 2)

Detecting attachments Summary: Highlights detecting whether the message has attachments when only message headers are available.

Tutorial map:
Part 1 - Downloading the list of messages
Part 2 - Detecting attachments
Part 3 - Retrieve a few body lines along with the headers

When displaying message list to user, it's common to show paper-clip for messages with attachments.

The POP3 protocol (unlike IMAP4) does not provide a mechanism to preview attachments. Fortunately, most messages with attachments have some specifics in their headers. This allows MailBee to detect attachments even if only message headers are available.

Message.HasAttachments property returns True if the message has one or more attachments.

However, Message.HasAttachments property is not 100% accurate: in rare cases, message headers do not conform to message contents.

100% reliable way to detect attachments is to download the message completely. For complete messages, Message.HasAttachments property is 100% accurate.

Sample code description

The sample code below fills ListBox control with the information regarding attachments presense for each message in the mailbox.

Code example:

' You can place the code below into any Sub or Function of your app

Dim objPOP3, colMsgs, I, strInfo

Set objPOP3 = CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Download headers for all messages
  Set colMsgs = objPOP3.RetrieveHeaders
  If objPOP3.IsError Then
    ' Handle errors
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  Else
    For I = 1 To objPOP3.MessageCount

      ' Add message number to string
      strInfo = "Message #" & I

      ' Detect attachment presence and
      ' add the results to string
      If colMsgs(I).HasAttachments Then
        strInfo = strInfo & " has attachment(s)"
      Else
        strInfo = strInfo & " has no attachment(s)"
      End If

      ' Display string with the results in ListBox
      List1.AddItem strInfo
    Next
  End If

  objPOP3.Disconnect
Else
  ' Handle errors
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If

See Also:

Part 3 (Retrieve a few body lines along with the headers)

RetrieveHeaders Method

Message.HasAttachments Property


Receiving message headers from POP3 server (Part 3)

Retrieve a few body lines along with the headers Summary: Demostrates how to get a few lines of the body in addition to message headers when retrieving the list of messages from POP3 server.

Tutorial map:
Part 1 - Downloading the list of messages
Part 2 - Detecting attachments
Part 3 - Retrieve a few body lines along with the headers

In some cases, you may need to get somewhat more than just message headers. Often, contents of "From:" and "Subject:" fields don't answer "what is the message about?" question.

Fortunately, RetrieveHeaders and RetrieveSingleMessageHeaders methods support optional parameter BodyLinesCount which specifies how many lines of the body to retrieve in addition to the headers.

The larger BodyLinesCount, bigger piece of the body is returned and more traffic is produced. If BodyLinesCount is larger then actual number of body lines in the message, the entire message is returned. Typically, 20-40 lines of the body describe the message quite enough.

Note: Avoid setting BodyLinesCount to very small values (less than 20). Many e-mail messages have some special (non-textual) information in the first 5-10 lines of the body while the actual body text starts after these lines.

Detailed information on partial messages internals

Note: You may immediatel go to the sample code and skip reading this topic unless you want to deal with partial messages in advanced ways.

For MailBee parser (the module which converts messages into Message objects), there is no difference between entire or partial messages. Available content is fully parsed anyway. Thus, if retrieved piece of the message contains any attachments, they will be parsed and added into Attachments collection but the size and the contents of the attachment will be incorrect if the attachment is not entirely received. Those attachments which didn't fall into the scope of retrieved piece, will not be appended to Attachments collection at all. In other words, MailBee puts into Message object all the information available in the partial message even if the information on some part of the message is incomplete.

So, if you have 1 attachment (named "abc.gif" and sized 1234 bytes) in retrieved partial message, you can guarantee that full message contains AT LEAST one attachment (named "abc.gif") and the size of this attachment is NOT LESS THAN 1234 bytes.

However, if you have 2 attachments in retrieved partial message, you can guarantee that first attachment is retrieved completely and its size and contents correspond to real values. This is due the fact that attachments located in the message and added to Attachments collection sequentially, so each new object guarantees that previous object is finished.

Be aware that text bodies do not behave the same since they often depend on each other while attachments are independent. E.g. retrieved piece contains part of the plain-text body but the message itself is HTML-formatted (its HTML part just did not fall into retrieved piece). Such message will appear as plain-text (BodyFormat=0) or HTML (BodyFormat=1) when retrieved with different BodyLinesCount value.

On other hand, if HTML body is first part and it was partially loaded while plain-text part was not loaded at all (BodyLinesCount is not large), the plain-text part will be generated by MailBee using "HTML-to-plaintext" tool. Increasing BodyLinesCount will cause HTML part to be retrieved completely and plain-text part - partially. Now plain-text body will be taken from partially retrieved plain-text part, not from HTML part plained by MailBee.

Briefly speaking, the information such as body/attachment content or size can be incomplete and greatly dependent on BodyLinesCount value for partial messages.

Note: Message size (Message.Size property) is ALWAYS correct even if only message headers are retrieved. MailBee gets the message size using special POP3 command.

Sample code description

The sample code below gets message headers + 100 first lines of the body part and adds first line of the text body to ListBox control. The sample performs this for each message in the mailbox.

Code example:

' You can place the code below into any Sub or Function of your app

Dim objPOP3, objMsg, colMsgs

' First line of the text body
Dim strLine

Set objPOP3 = CreateObject("MailBee.POP3")
objPOP3.LicenseKey = "put your license key here"

' Connect to POP3 server
If objPOP3.Connect("mail.server.com", 110, "user", "pass") Then

  ' Download headers + 100 body lines
  Set colMsgs = objPOP3.RetrieveHeaders(1, -1, 100)

  If objPOP3.IsError Then
    ' Handle errors
    MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
  Else
    For Each objMsg In colMsgs

      ' Store available body text lines in the variable
      strLine = objMsg.BodyText

      ' Keep only 1 line of all available body text
      If InStr(strLine, vbCrLf) > 0 Then
        strLine = Left(strLine, InStr(strLine, vbCrLf))
      End If

      ' Add first line of the body to ListBox
      List1.AddItem strLine
    Next
  End If

  objPOP3.Disconnect
Else
  ' Handle errors
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
End If

See Also:

RetrieveHeaders Method
RetrieveSingleMessageHeaders Method


Receiving new messages from POP3 server (Part 1)

Getting new messages Summary: Demonstrates how to skip already downloaded messages and retrieve only new messages from the mailbox.

Tutorial map:

Part 1 - Getting new messages
Part 2 - Advanced topics

Typical scenario: The mail client checks whether new messages have arrived since last connection and wants to download new messages (if any).

Limitations: Some old POP3 servers do not support the command required for message search (UIDL command).

How to detect which messages are new

The POP3 protocol has no mechanism to determine whether a message has been already downloaded. Therefore, it's required to keep a list of identifiers of already downloaded messages in a local database maintained by your application.

Any time your application searches the mailbox for new messages, it queries the database for each message in the mailbox to determine if a message has already been downloaded. If the identifier of the particular message has not been found in the database, this message is new.

As the message identifier, Unique-ID can be used.

Message's Unique-ID (UID)

Unique-ID (UID for short) is a unique string assigned to each message in the mailbox. No two messages in the mailbox can have the same Unique-ID value. Sometimes Unique-ID is called GUID (globally unique identifier).

Unique-ID is not associated with "Message-ID:" header of the message.

POP3 object provides Search method which returns array of Unique-IDs of all the messages in the mailbox.

Sample code description

The sample code below receives new messages on RetrieveNewMessages() method call, and prints "Subject:" field of each new message found.

In real code, the sample function IsNewMessage() should query the database for specified Unique-ID value and return True only if this Unique-ID value is not found in the database. For demo purposes, this function always returns True.

Note: For simplicity, this sample has no error checking. In production code, you should not rely on successful completion of all operations.

Code example:

<%
' This is main function. It retrieves new messages from
' the POP3 server and prints "Subject:" field of each
' retrieved message to the output
Sub RetrieveNewMessages()
  Dim objPOP3, objMsg, I

  ' Array of Unique-IDs (taken from the POP3 server)
  Dim arrIDs

  Set objPOP3 = Server.CreateObject("MailBee.POP3")
  objPOP3.LicenseKey = "put your license key here"

  ' Connect to POP3 server
  If objPOP3.Connect("mail.server.com", 110, "jdoe", "secret") Then

    ' Get Unique-IDs for all the messages in the mailbox
    arrIDs = objPOP3.Search

    ' Iterate through all the messages in the mailbox
    For I = 1 To objPOP3.MessageCount

      ' Search Unique-ID of the message in the database
      If IsNewMessage(arrIDs(I)) Then

        ' Download entire message
        Set objMsg = objPOP3.RetrieveSingleMessage(I)

        ' Print the message's Subject
        Response.Write objMsg.Subject & "<br>"
      End If
    Next
    objPOP3.Disconnect
  Else
    Response.Write objPOP3.ErrDesc
  End If
End Sub

' This helper function should lookup the ID in the
' database, and then return True if the ID does not
' exist in the list of already downloaded messages.
Function IsNewMessage(ByVal ID)
  ' For demo purposes, the function always returns True.
  IsNewMessage = True
End Function
%>

See Also:

Part 2 (Advanced topics)

RetrieveSingleMessage Method
Search Method


Receiving new messages from POP3 server (Part 2)

Advanced topics Summary: Presents advanced code sample of receiving new messages. Highlights performance improvements, error-checking, old POP3 servers support and simple implementation of message identifiers database.

Tutorial map:

Part 1 - Getting new messages
Part 2 - Advanced topics

Typical scenario: The web-based mail client checks whether new messages have arrived since last connection and wants to download new messages (if any). The web-based mail client also handles all possible errors.

Limitations: None.

Performance improvements

In Part 1 code sample, Unique-IDs for all the messages in the mailbox are looked up in the database. In real-world situations, mailboxes usually contain only a small number of new messages beside total number of the messages. Another important fact is that new messages are always appended to the end of the mailbox. It's impossible that new message is followed by not new message. In other words:

  • Number of not new messages is usually larger than number of new messages
  • Once not new message is found, the mail client can expect that all messages from this message to the beginning of the mailbox are not new
According to the above, it is better to iterate through the messages in reverse order, from the last message to the first. If the message is new, retrieve it and proceed with previous message. Once already downloaded (not new) message found, the entire loop can be stopped - there are no more new messages in the mailbox.

Checking for errors

Connection to the POP3 server can be suddenly broken for a variety of reasons. Well-written application should take care of such situation. Also, your application should consider that not all POP3 servers support the command required for extracting Unique-IDs of the messages - Unique-IDs support is an optional extension of the POP3 protocol.

Search new messages when the POP3 server does not support Unique-IDs

If the POP3 server does not support Unique-IDs, smart mail client may consider using backup method to download new messages. This method uses Message-ID values taken from "Message-ID:" field of the messages' headers. Its disadvantage is the fact that headers for all the messages in the mailbox must be retrieved. This results in larger network traffic (relatively to retrieving Unique-IDs). However, in situation where Unique-IDs cannot be used, this method is still better than downloading all the messages entirely.

The idea is obvious:
  • Retrieve headers for the first message in the mailbox
  • Lookup Message-ID of the message in the database. If the Message-ID is not found, the message is new and should be retrieved entirely
  • In the same manner, proceed with subsequent messages till the end of the mailbox
Simple text-file database implementation for single email account

In the previous part, sample code has no implementation of the database, and IsNewMessage() function always returns True.

In this part, simple database implementation is provided. The database is stored in a text file. Each line of the file holds one Unique-ID value. If the server does not support Unique-IDs, Message-ID values are used instead.

Sample code description

The sample code below receives new messages on ASP page execution. For each new message found, "Subject:" field is printed to the output.

GetFirstOfNewMessages_UID helper function is used to get message number of the first of new messages in the mailbox. Also, this function returns the list of Unique-IDs of all the messages currently being in the mailbox.

GetFirstOfNewMessages_MID helper function is analog of GetFirstOfNewMessages_UID with only difference that it operates with Message-IDs instead of Unique-IDs. It is used when the POP3 server does not support Unique-IDs.

Besides that, the sample code includes performance optimizations (Unique-IDs are scanned in reverse order), and comprehensive error-checking.

License key, mail server name, user account name and password, database filename, and other settings are declared as constants at the top of the source.

Code example:

<%
' MailBee License key
Const LICENSE_KEY = "put your license key here"

' POP3 server name
Const SERVER_NAME = "mail.server.com"

' POP3 server port (usually 110)
Const SERVER_PORT = 110

' POP3 account name
Const ACCOUNT_NAME = "jdoe"

' POP3 account password
Const ACCOUNT_PASSWORD = "secret"

' Path to a file that will be used as database
Const DATABASE_FILENAME = "C:\database.txt"

' Succesful (No error)
Const ERR_OK = 0

' Error: The server does not support Unique-IDs
Const ERR_POP3_COMMAND_NOT_SUPPORTED = 216

' POP3 object
Dim objPOP3

' Displays a message describing the error occurred
Sub ReportError(objPOP3)
  Response.Write "Error #" & objPOP3.ErrCode & "," & objPOP3.ErrDesc & _
    ", Server responded: " & objPOP3.ServerResponse
End Sub

' Returns message number of first of new messages in the mailbox.
' The search is performed using Unique-IDs of the messages
'
' Parameters:
' objPOP3 - POP3 object in the connected state.
'
' strStoredUIDs - CRLF-separated list of Unique-IDs of all messages
'   in the mailbox as of moment of the previous connection.
'
' strCurrentUIDs - (output parameter) filled by this
'   function with CRLF-separated list of Unique-IDs of all messages
'   in the mailbox as of moment of the current connection.
'
Function GetFirstOfNewMessages_UID(objPOP3, strStoredUIDs, ByRef strCurrentUIDs)
  Dim I, J

  ' Array of Unique-IDs of all messages in the
  ' mailbox as of moment of the previous connection.
  Dim arrStoredUIDs

  ' Array of Unique-IDs of all messages in the
  ' mailbox as of moment of the current connection.
  Dim arrCurrentUIDs

  ' Convert CRLF-separated list into array
  arrStoredUIDs = Split(strStoredUIDs, vbCrLf)

  strCurrentUIDs = ""

  ' Get Unique-IDs of all messages from POP3 server
  arrCurrentUIDs = objPOP3.Search

  If objPOP3.ErrCode = ERR_OK Then
    ' Successfully got Unique-IDs array from POP3 server

    ' Convert array into CRLF-separated list
    strCurrentUIDs = Join(arrCurrentUIDs, vbCrLf)

    ' Iterate through old messages from last to first
    For I = UBound(arrStoredUIDs) To LBound(arrStoredUIDs) Step -1
      ' Lookup old message in current messages
      For J = UBound(arrCurrentUIDs) To LBound(arrCurrentUIDs) Step -1
        If arrStoredUIDs(I) = arrCurrentUIDs(J) Then
          ' Old message was found in the list of current messages.
          ' All messages after found message are new.
          GetFirstOfNewMessages_UID = J + 1
          Exit Function
        End If
      Next
    Next

    ' All messages have been scanned, but no matches with old
    ' messages have been found. All messages in the mailbox are new.
    GetFirstOfNewMessages_UID = 1
  ElseIf objPOP3.ErrCode = ERR_POP3_COMMAND_NOT_SUPPORTED Then
    ' Non-fatal error, must rollback to Message-ID
    GetFirstOfNewMessages_UID = 0
  Else
    ' Fatal error
    GetFirstOfNewMessages_UID = -1
  End If
End Function

' Returns message number of first of new messages in the mailbox.
' The search is performed using Message-IDs of the messages
'
' Parameters:
' objPOP3 - POP3 object in the connected state.
'
' strStoredMIDs - CRLF-separated list of Message-IDs of all messages
'   in the mailbox as of moment of the previous connection.
'
' strCurrentMIDs - (output parameter) filled by this
'   function with CRLF-separated list of Message-IDs of all messages
'   in the mailbox as of moment of the current connection.
'
Function GetFirstOfNewMessages_MID(objPOP3, strStoredMIDs, ByRef strCurrentMIDs)
  Dim I, J

  ' True if new message was found
  Dim blnNew

  ' Message object that holds message headers
  Dim objMsg

  ' Array of Message-IDs of all messages in the
  ' mailbox as of moment of the previous connection.
  Dim arrStoredMIDs

  ' Convert CRLF-separated list into array
  arrStoredMIDs = Split(strStoredMIDs, vbCrLf)

  strCurrentMIDs = ""

  ' No new messages found to the moment
  blnNew = False

  ' No new messages yet, so mark that first new
  ' message is outside the valid range.
  GetFirstOfNewMessages_MID = objPOP3.MessageCount + 1

  ' Iterate through all messages in the mailbox
  For I = 1 To objPOP3.MessageCount

    ' Get message headers from POP3 server
    Set objMsg = objPOP3.RetrieveSingleMessageHeaders(I)

    If objPOP3.ErrCode <> 0 Then
      ' Return error
      GetFirstOfNewMessages_MID = -1
      Exit Function
    End If
    If Not blnNew Then
      ' New messages not found yet

      ' Initially assume the message is new
      blnNew = True

      ' Try to find just retrived Message-ID
      ' in the array of old messages.
      For J = LBound(arrStoredMIDs) To UBound(arrStoredMIDs)
        If arrStoredMIDs(J) = objMsg.MessageID Then
          ' Message-ID was found, the message is not new
          blnNew = False
          Exit For
        End If
      Next
      If blnNew Then
        ' Message-ID was not found, the message is new.
        ' All subsequent messages will be new too.
        GetFirstOfNewMessages_MID = I
      End If
    End If

    ' Add Message-ID to the list of Message-IDs of current messages
    If Len(strCurrentMIDs) > 0 Then
      strCurrentMIDs = strCurrentMIDs & vbCrLf & objMsg.MessageID
    Else
      strCurrentMIDs = objMsg.MessageID
    End If
  Next
End Function

' Main part: check for new messages and print their "Subject:" field

Dim objMsg, I

Dim fso, f

' strStoredIDs - CRLF-separated list of IDs (Unique-IDs or
' Message-IDs, if Unique-IDs are not supported) of all
' messages in the mailbox as of moment of the previous connection.
Dim strStoredIDs

' strStoredIDs - CRLF-separated list of IDs (Unique-IDs or
' Message-IDs, if Unique-IDs are not supported) of all
' messages in the mailbox as of moment of the current connection.
Dim strCurrentIDs

' Message number of first of new messages. This message is newer
' than any old message, and older than any other new message.
Dim lFirstNew

Set objPOP3 = CreateObject("MailBee.POP3")
objPOP3.LicenseKey = LICENSE_KEY

' Connect to POP3 server
If objPOP3.Connect(SERVER_NAME, SERVER_PORT, ACCOUNT_NAME, ACCOUNT_PASSWORD) Then

  ' Open text file that holds the database
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set f = fso.OpenTextFile(DATABASE_FILENAME, 1, True)

  If Not f.AtEndOfStream Then
    ' Read array of IDs from the file
    strStoredIDs = f.ReadAll
  Else
    ' The file was empty
    strStoredIDs = ""
  End If

  f.Close

  ' Determine first of new messages using Unique-IDs
  lFirstNew = GetFirstOfNewMessages_UID(objPOP3, strStoredIDs, strCurrentIDs)

  If lFirstNew = 0 Then
    ' Unique-IDs are not supported by the POP3 server

    ' Determine first of new messages using Message-IDs
    lFirstNew = GetFirstOfNewMessages_MID(objPOP3, strStoredIDs, strCurrentIDs)
  End If

  If lFirstNew < 0 Then
    ' Report error to user
    ReportError objPOP3
  Else

    ' Loop from the first of new messages to the end of the
    ' mailbox. If lFirstNew > objPOP3.MessageCount, the loop
    ' is executed zero times (no new messages were found).
    For I = lFirstNew To objPOP3.MessageCount

      ' Download entire message
      Set objMsg = objPOP3.RetrieveSingleMessage(I)

      ' Display Subject of the message
      ' We use HTMLEncode to convert '<' and '>' into
      ' their HTML equivalents
      Response.Write Server.HTMLEncode(objMsg.Subject) & "<br>"
    Next

    ' Open the text file for writing
    Set f = fso.OpenTextFile(DATABASE_FILENAME, 2, True)

    ' Store IDs in the file
    f.Write strCurrentIDs

    f.Close
  End If

  ' Disconnect on finish
  objPOP3.Disconnect
Else
  ' Report connection error to user
  ReportError objPOP3
End If
%>

See Also:

RetrieveSingleMessage Method
RetrieveSingleMessageHeaders Method
Search Method


Receiving new messages from POP3 server (Part 1)

Getting new messages Summary: Demonstrates how to skip already downloaded messages and retrieve only new messages from the mailbox.

Tutorial map:

Part 1 - Getting new messages
Part 2 - Advanced topics

Typical scenario: The mail client checks whether new messages have arrived since last connection and wants to download new messages (if any).

Limitations: Some old POP3 servers do not support the command required for message search (UIDL command).

How to detect which messages are new

The POP3 protocol has no mechanism to determine whether a message has been already downloaded. Therefore, it's required to keep a list of identifiers of already downloaded messages in a local database maintained by your application.

Any time your application searches the mailbox for new messages, it queries the database for each message in the mailbox to determine if a message has already been downloaded. If the identifier of the particular message has not been found in the database, this message is new.

As the message identifier, Unique-ID can be used.

Message's Unique-ID (UID)

Unique-ID (UID for short) is a unique string assigned to each message in the mailbox. No two messages in the mailbox can have the same Unique-ID value. Sometimes Unique-ID is called GUID (globally unique identifier).

Unique-ID is not associated with "Message-ID:" header of the message.

POP3 object provides Search method which returns array of Unique-IDs of all the messages in the mailbox.

Sample code description

The sample code below receives new messages on RetrieveNewMessages() method call. "Subject:" field of each new message is added to ListBox control named List1.

In real code, the sample function IsNewMessage() should query the database for specified Unique-ID value and return True only if this Unique-ID value is not found in the database. For demo purposes, this function always returns True.

Note: For simplicity, this sample has no error checking. In production code, you should not rely on successful completion of all operations.

Code example:

' This is main function. It retrieves new messages from
' the POP3 server and displays "Subject:" field of each
' retrieved message in the ListBox control.
Sub RetrieveNewMessages()
  Dim objPOP3, objMsg, I

  ' Array of Unique-IDs (taken from the POP3 server)
  Dim arrIDs

  Set objPOP3 = CreateObject("MailBee.POP3")
  objPOP3.LicenseKey = "put your license key here"

  ' Connect to POP3 server
  If objPOP3.Connect("mail.server.com", 110, "jdoe", "secret") Then

    ' Get Unique-IDs for all the messages in the mailbox
    arrIDs = objPOP3.Search

    ' Iterate through all the messages in the mailbox
    For I = 1 To objPOP3.MessageCount

      ' Search Unique-ID of the message in the database
      If IsNewMessage(arrIDs(I)) Then

        ' Download entire message
        Set objMsg = objPOP3.RetrieveSingleMessage(I)

        ' Add the message's Subject to the ListBox control
        List1.AddItem objMsg.Subject
      End If
    Next
    objPOP3.Disconnect
  Else
    MsgBox objPOP3.ErrDesc
  End If
End Sub

' This helper function should lookup the ID in the
' database, and then return True if the ID does not
' exist in the list of already downloaded messages.
Function IsNewMessage(ByVal ID)
  ' For demo purposes, the function always returns True.
  IsNewMessage = True
End Function

See Also:

Part 2 (Advanced topics)

RetrieveSingleMessage Method
Search Method


Receiving new messages from POP3 server (Part 2)

Advanced topics Summary: Presents advanced code sample of receiving new messages. Highlights performance improvements, responsive user interface, error-checking, old POP3 servers support and simple implementation of message identifiers database.

Tutorial map:

Part 1 - Getting new messages
Part 2 - Advanced topics

Typical scenario: The mail client checks whether new messages have arrived since last connection and wants to download new messages (if any). The mail client allows user to abort operation, handles errors, keeps user interface responsive during email operation.

Limitations: None.

Performance improvements

In Part 1 code sample, Unique-IDs for all the messages in the mailbox are looked up in the database. In real-world situations, mailboxes usually contain only a small number of new messages beside total number of the messages. Another important fact is that new messages are always appended to the end of the mailbox. It's impossible that new message is followed by not new message. In other words:

  • Number of not new messages is usually larger than number of new messages
  • Once not new message is found, the mail client can expect that all messages from this message to the beginning of the mailbox are not new
According to the above, it is better to iterate through the messages in reverse order, from the last message to the first. If the message is new, retrieve it and proceed with previous message. Once already downloaded (not new) message found, the entire loop can be stopped - there are no more new messages in the mailbox.

Keeping user interface responsive when performing email operation

By default, Windows events are not processed when MailBee is busy with certain email operation. This gives maximum performance to your application, and fits fine for web applications such as ASP.

For desktop applications, however, it's common to give user ability to interact with your application even when it is busy. Mailer objects (POP3, SMTP, IMAP4) provide EnableEvents property for this purpose. Particularly, to enable events processing by POP3 object, you need to set POP3.EnableEvents=True before connecting to the mail server.

Checking for errors

Connection to the POP3 server can be suddenly broken for a variety of reasons. Well-written application should take care of such situation. Also, your application should consider that not all POP3 servers support the command required for extracting Unique-IDs of the messages - Unique-IDs support is an optional extension of the POP3 protocol.

Search new messages when the POP3 server does not support Unique-IDs

If the POP3 server does not support Unique-IDs, smart mail client may consider using backup method to download new messages. This method uses Message-ID values taken from "Message-ID:" field of the messages' headers. Its disadvantage is the fact that headers for all the messages in the mailbox must be retrieved. This results in larger network traffic (relatively to retrieving Unique-IDs). However, in situation where Unique-IDs cannot be used, this method is still better than downloading all the messages entirely.

The idea is obvious:
  • Retrieve headers for the first message in the mailbox
  • Lookup Message-ID of the message in the database. If the Message-ID is not found, the message is new and should be retrieved entirely
  • In the same manner, proceed with subsequent messages till the end of the mailbox
Simple text-file database implementation for single email account

In the previous part, sample code has no implementation of the database, and IsNewMessage() function always returns True.

In this part, simple database implementation is provided. The database is stored in a text file. Each line of the file holds one Unique-ID value. If the server does not support Unique-IDs, Message-ID values are used instead.

Sample code description

The sample code below receives new messages on Command1_Click method call. This occurs when user clicks CommandButton named Command1. "Subject:" field of each new message is added to ListBox control named List1.

GetFirstOfNewMessages_UID helper function is used to get message number of the first of new messages in the mailbox. Also, this function returns the list of Unique-IDs of all the messages currently being in the mailbox.

GetFirstOfNewMessages_MID helper function is analog of GetFirstOfNewMessages_UID with only difference that it operates with Message-IDs instead of Unique-IDs. It is used when the POP3 server does not support Unique-IDs.

Besides that, the sample code includes performance optimizations (Unique-IDs are scanned in reverse order), error-checking, Windows events processing.

Any time user can shutdown the application so the connection to mail server will be immediately aborted (POP3.Abort method is called in Form_Unload routine). The application does not "freezes" during performing certain email operation.

License key, mail server name, user account name and password, database filename, and other settings are declared as constants at the top of the source.

Code example:

' MailBee License key
Const LICENSE_KEY = "put your license key here"

' POP3 server name
Const SERVER_NAME = "mail.server.com"

' POP3 server port (usually 110)
Const SERVER_PORT = 110

' POP3 account name
Const ACCOUNT_NAME = "jdoe"

' POP3 account password
Const ACCOUNT_PASSWORD = "secret"

' Path to a file that will be used as database
Const DATABASE_FILENAME = "C:\database.txt"

' Succesful (No error)
Const ERR_OK = 0

' Error: The server does not support Unique-IDs
Const ERR_POP3_COMMAND_NOT_SUPPORTED = 216

' POP3 object declared global because it is used in
' more than one routine.
Dim objPOP3

' If True, email operation was aborted by user
Dim blnAborted

' Displays a message describing the error occurred
Sub ReportError(objPOP3)
  MsgBox "Error #" & objPOP3.ErrCode & "," & objPOP3.ErrDesc & _
    ", Server responded: " & objPOP3.ServerResponse
End Sub

' Returns message number of first of new messages in the mailbox.
' The search is performed using Unique-IDs of the messages
'
' Parameters:
' objPOP3 - POP3 object in the connected state.
'
' strStoredUIDs - CRLF-separated list of Unique-IDs of all messages
'   in the mailbox as of moment of the previous connection.
'
' strCurrentUIDs - (output parameter) filled by this
'   function with CRLF-separated list of Unique-IDs of all messages
'   in the mailbox as of moment of the current connection.
'
Function GetFirstOfNewMessages_UID(objPOP3, strStoredUIDs, ByRef strCurrentUIDs)
  Dim I, J

  ' Array of Unique-IDs of all messages in the
  ' mailbox as of moment of the previous connection.
  Dim arrStoredUIDs

  ' Array of Unique-IDs of all messages in the
  ' mailbox as of moment of the current connection.
  Dim arrCurrentUIDs

  ' Convert CRLF-separated list into array
  arrStoredUIDs = Split(strStoredUIDs, vbCrLf)

  strCurrentUIDs = ""

  ' Get Unique-IDs of all messages from POP3 server
  arrCurrentUIDs = objPOP3.Search

  If objPOP3.ErrCode = ERR_OK Then
    ' Successfully got Unique-IDs array from POP3 server

    ' Convert array into CRLF-separated list
    strCurrentUIDs = Join(arrCurrentUIDs, vbCrLf)

    ' Iterate through old messages from last to first
    For I = UBound(arrStoredUIDs) To LBound(arrStoredUIDs) Step -1
      ' Lookup old message in current messages
      For J = UBound(arrCurrentUIDs) To LBound(arrCurrentUIDs) Step -1
        If arrStoredUIDs(I) = arrCurrentUIDs(J) Then
          ' Old message was found in the list of current messages.
          ' All messages after found message are new.
          GetFirstOfNewMessages_UID = J + 1
          Exit Function
        End If
      Next
    Next

    ' All messages have been scanned, but no matches with old
    ' messages have been found. All messages in the mailbox are new.
    GetFirstOfNewMessages_UID = 1
  ElseIf objPOP3.ErrCode = ERR_POP3_COMMAND_NOT_SUPPORTED Then
    ' Non-fatal error, must rollback to Message-ID
    GetFirstOfNewMessages_UID = 0
  Else
    ' Fatal error
    GetFirstOfNewMessages_UID = -1
  End If
End Function

' Returns message number of first of new messages in the mailbox.
' The search is performed using Message-IDs of the messages
'
' Parameters:
' objPOP3 - POP3 object in the connected state.
'
' strStoredMIDs - CRLF-separated list of Message-IDs of all messages
'   in the mailbox as of moment of the previous connection.
'
' strCurrentMIDs - (output parameter) filled by this
'   function with CRLF-separated list of Message-IDs of all messages
'   in the mailbox as of moment of the current connection.
'
Function GetFirstOfNewMessages_MID(objPOP3, strStoredMIDs, ByRef strCurrentMIDs)
  Dim I, J

  ' True if new message was found
  Dim blnNew

  ' Message object that holds message headers
  Dim objMsg

  ' Array of Message-IDs of all messages in the
  ' mailbox as of moment of the previous connection.
  Dim arrStoredMIDs

  ' Convert CRLF-separated list into array
  arrStoredMIDs = Split(strStoredMIDs, vbCrLf)

  strCurrentMIDs = ""

  ' No new messages found to the moment
  blnNew = False

  ' No new messages yet, so mark that first new
  ' message is outside the valid range.
  GetFirstOfNewMessages_MID = objPOP3.MessageCount + 1

  ' Iterate through all messages in the mailbox
  For I = 1 To objPOP3.MessageCount

    ' Get message headers from POP3 server
    Set objMsg = objPOP3.RetrieveSingleMessageHeaders(I)

    If objPOP3.ErrCode <> 0 Then
      ' Return error
      GetFirstOfNewMessages_MID = -1
      Exit Function
    End If
    If Not blnNew Then
      ' New messages not found yet

      ' Initially assume the message is new
      blnNew = True

      ' Try to find just retrived Message-ID
      ' in the array of old messages.
      For J = LBound(arrStoredMIDs) To UBound(arrStoredMIDs)
        If arrStoredMIDs(J) = objMsg.MessageID Then
          ' Message-ID was found, the message is not new
          blnNew = False
          Exit For
        End If
      Next
      If blnNew Then
        ' Message-ID was not found, the message is new.
        ' All subsequent messages will be new too.
        GetFirstOfNewMessages_MID = I
      End If
    End If

    ' Add Message-ID to the list of Message-IDs of current messages
    If Len(strCurrentMIDs) > 0 Then
      strCurrentMIDs = strCurrentMIDs & vbCrLf & objMsg.MessageID
    Else
      strCurrentMIDs = objMsg.MessageID
    End If
  Next
End Function

' Checks for new messages and displays Subject field
' of each new message in the ListBox.
Sub Command1_Click()
  Dim objMsg, I

  Dim fso, f

  ' strStoredIDs - CRLF-separated list of IDs (Unique-IDs or
  ' Message-IDs, if Unique-IDs are not supported) of all
  ' messages in the mailbox as of moment of the previous connection.
  Dim strStoredIDs

  ' strStoredIDs - CRLF-separated list of IDs (Unique-IDs or
  ' Message-IDs, if Unique-IDs are not supported) of all
  ' messages in the mailbox as of moment of the current connection.
  Dim strCurrentIDs

  ' Message number of first of new messages. This message is newer
  ' than any old message, and older than any other new message.
  Dim lFirstNew

  Set objPOP3 = CreateObject("MailBee.POP3")
  objPOP3.LicenseKey = LICENSE_KEY

  ' Make user interface responsive
  objPOP3.EnableEvents = True

  ' Connect to POP3 server
  If objPOP3.Connect(SERVER_NAME, SERVER_PORT, ACCOUNT_NAME, ACCOUNT_PASSWORD) Then

    ' Open text file that holds the database
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set f = fso.OpenTextFile(DATABASE_FILENAME, 1, True)

    If Not f.AtEndOfStream Then
      ' Read array of IDs from the file
      strStoredIDs = f.ReadAll
    Else
      ' The file was empty
      strStoredIDs = ""
    End If

    f.Close

    ' Determine first of new messages using Unique-IDs
    lFirstNew = GetFirstOfNewMessages_UID(objPOP3, strStoredIDs, strCurrentIDs)

    If lFirstNew = 0 Then
      ' Unique-IDs are not supported by the POP3 server

      ' Determine first of new messages using Message-IDs
      lFirstNew = GetFirstOfNewMessages_MID(objPOP3, strStoredIDs, strCurrentIDs)
    End If

    ' Exit the routine if user wants to close the app
    If blnAborted Then Exit Sub

    If lFirstNew < 0 Then
      ' Report error to user
      ReportError objPOP3
    Else

      ' Loop from the first of new messages to the end of the
      ' mailbox. If lFirstNew > objPOP3.MessageCount, the loop
      ' is executed zero times (no new messages were found).
      For I = lFirstNew To objPOP3.MessageCount

        ' Download entire message
        Set objMsg = objPOP3.RetrieveSingleMessage(I)

        ' Exit the routine if user wants to close the app
        If blnAborted Then Exit Sub

        ' Display Subject of the message
        List1.AddItem objMsg.Subject
      Next

      ' Open the text file for writing
      Set f = fso.OpenTextFile(DATABASE_FILENAME, 2, True)

      ' Store IDs in the file
      f.Write strCurrentIDs

      f.Close
    End If

    ' Disconnect on finish
    objPOP3.Disconnect
  ElseIf Not blnAborted Then
    ' Report connection error to user
    ReportError objPOP3
  End If
End Sub

' Initialize
Sub Form_Load()
  blnAborted = False
  Set objPOP3 = Nothing
End Sub

' Abort operation when user wants to exit the app
Sub Form_Unload(Cancel As Integer)
  If Not objPOP3 Is Nothing Then
    blnAborted = True
    objPOP3.Abort
  End If
End Sub

See Also:

RetrieveSingleMessage Method
RetrieveSingleMessageHeaders Method
Search Method


MailBee Reference

MailBee Objects library provides many useful objects and collections to help you create, send, entirely/partially download and manage e-mail messages, along with auxiliary features such as e-mail address validation, text conversion routines, HTML messages creating and viewing helper and more.

Class | Use to
SMTP Object | Create and send e-mails to the SMTP server, IIS SMTP pickup folder or to MailBee Message Queue or MailBee.NET Queue.
POP3 Object | Receive e-mails and their headers from the POP3 server into Message objects, and manage e-mail on the POP3 server.
IMAP4 Object | Receive e-mails, their headers and envelopes from the IMAP4 server into Message objects, search and manage e-mail and mailboxes on the POP3 server.
SSL Object | Enable secure SSL/TLS connections to SMTP, POP3 and IMAP4 servers, select, search and verify client and server certificates.
SMIME Object | Enable e-mails securing, digital message signing, e-mails encryption and decryption, examining and saving the digital certificates according to the S/MIME standard.
Message Object | Set e-mail properties like body, subject, attachments, etc. when composing new message, or examine these properties when the message was received from the POP3 or IMAP4 server. When downloading message headers only, they are also stored in Message objects. The Message object can be also used on its own to perform advanced features such as e-mail address validation, HTML-to-plaintext, string-to-date, text-to-UTF8 conversions, and much more.
Attachment Object | Examine properties of an attachment to the message, or save the attached file to disk.
BodyPartStructure Object | Determine the message structure without actually downloading the entire message. This is IMAP4-only feature.
Envelope Object | Determine general information about a message without actually downloading the entire message. This is IMAP4-only feature.
Mailbox Object | Examine properties of an individual mailbox in the IMAP4 mail account.
CertInfo Object | Examine properties of a client of server certificate.

See Also

SMTP Samples, POP3 Samples, IMAP4 Samples, Advanced Samples

Send feedback to AfterLogic


SMTP Object

You can use the SMTP object to compose and send single and bulk e-mails.

The SMTP object supports a lot of SMTP authentication methods, including OAuth 2.0 and NTLM). See AuthMethod property for details.

The SMTP object uses the Message object as a source of the e-mail to be sent. Thus, all the functionality of the Message object can be used with the SMTP object too.

The SMTP object can also send e-mails stored on disk as files (RelayMessage method). For quick sending large amounts of e-mails, message queuing option is available through IIS SMTP pickup folder or external MailBee Message Queue (legacy) or MailBee .NET Queue (modern) system. MailBee.NET Queue (needs .NET Framework) has more features than MailBee Message Queue and supports SSL.

SMTP.Message property specifies the Message object which represents the e-mail to be sent. To compose the message, you must set properties of this Message object. For example, you can use the code below to specify the message subject:

objSMTP.Message.Subject = "Meeting request"

The SMTP object includes several methods and properties which allow shorter syntax for setting main attributes of the message. For example, the code below produces exactly the same result as the code above:

objSMTP.Subject = "Meeting request"

Syntax

SMTP.property|method

Properties
AllowRefusedRecipients | Lets MailBee tolerate rejected recipients during sending in case if at least one recipient gets accepted by the server.
AltBodyEncoding | Specifies which encoding method to use for the message alternative body.
AltBodyText | Contains alternative plain-text body of the message if the primary body is HTML-formatted.
AuthMethod | Specifies the authentication method to use when connecting to the SMTP server.
BCCAddr | The e-mail addresses of the blind-carbon-copy recipients.
BodyEncoding | Specifies which encoding method to use for the message primary body.
BodyFormat | Indicates the primary body format: Plain-Text, HTML, etc.
BodyText | The primary body text.
Busy | Indicates whether the SMTP object is in the progress of sending or receiving data.
CCAddr | The e-mail addresses of the carbon-copy recipients.
Charset | Specifies the charset that was used for composing the message body.
ClientRequest | Returns the last command string sent to the SMTP server.
Connected | Indicates whether the SMTP session is active.
Domain | Specifies the sender's domain. Not required by most of SMTP servers.
Enable8bitEncoding | Indicates whether 8bit characters are permitted in the message body.
EnableEvents | Specifies whether the SMTP object will handle and fire events.
EnableLogging | Specifies whether the SMTP object must log the SMTP session into a file.
ErrCode | Completion status of the last command.
ErrDesc | Contains textual error description if the last command has completed with an error.
FromAddr | The e-mail address of the sender.
IsError | Indicates whether the last command has completed with errors.
ISQueueIIS | Gets or sets if the e-mail queue folder belongs to IIS SMTP service.
Licensed | Indicates whether valid license key has been assigned to the SMTP object.
LicenseKey | Sets the license key to be used with the SMTP object.
LogFilePath | Sets filename of the SMTP session log file.
MailFromDSN | Optional DSN suffix for MAIL FROM command.
Message | Specifies the Message object which represents the e-mail to be sent.
Password | The password of the user account on the SMTP server, if SMTP authentication is used.
PortNumber | The port number of the SMTP service on the server. Defaults to 25.
RcptToDSN | Optional DSN suffix for RCPT TO commands.
ServerName | The SMTP server name.
ServerResponse | Returns the string that contains the entire last reply from the SMTP server.
SSL | Specifies the SSL object to be used to establish secure TLS connection with the SMTP server.
Subject | The subject of the message.
SupportsDSN | Indicates whether the SMTP server supports DSN (Delivery Status Nofitications).
SupportsStartTLS | Indicates whether the SMTP server supports STARTTLS command.
TargetName | The SPN of the server (only used with Kerberos authentication).
Timeout | The timeout value in seconds.
ToAddr | The e-mail addresses of the primary recipients.
UserDomain | The name of the user domain on the SMTP server (only used with MS specific authentication types like NTLM).
UserName | The name of the user account on the SMTP server, if SMTP authentication is used.
Methods
Abort | Aborts current operation and immediately closes the SMTP session.
AddAttachment | Attaches a file to the message.
AddHeader | Adds custom header to the message.
ClearLog | Clears the SMTP session log file.
Connect | Connects to the SMTP server, and authenticates the sender if SMTP authentication is used.
Disconnect | Disconnects from the SMTP server.
EncodeHeaderText | Encodes a string in the specified charset.
ExecuteCommand | Sends specified string of data to the SMTP server.
GetAcceptedRecipients | Returns the comma-separated string which lists the e-mail addresses which have been accepted by the server during sending.
GetRelayServerFromEmailAddress | Gets the host name of the domain willing to accept the mails for the specified e-mail address or an empty string if error occurred.
GetRefusedRecipients | Returns the comma-separated string which lists the e-mail addresses which have been rejected by the server during sending.
GetLastDataFromClient | Gets the data chunk sent by the client during the last I/O operation.
GetLastDataFromServer | Gets the data chunk received by the client from the server during the last I/O operation.
ImportAltBodyText | Loads the specified file contents into the message alternative body.
ImportBodyText | Loads the specified file contents into the message primary body and, optionally, scans the loaded HTML body for embedded objects and appends them as attachments.
MakeAltBody | Creates the alternative plain-text body from the current value of the HTML body.
RelayMessage | Relays the message stored as disk file to the specified recipients.
ResetMessage | Resets the Message object associated with the SMTP object.
ResolveHostName | Extracts the IP address of the specified host name.
Send | Sends the message to the SMTP server.
SendEx | Sends the message to the SMTP server, and allows you to override e-mail addresses of the sender and the recipients specified in the message.
SendToQueue | Submits the message to IIS SMTP service or MailBee Message Queue system for delivery.
SendToQueueEx | Submits the message to IIS SMTP service or MailBee Message Queue system for delivery, and allows you to override e-mail addresses of the sender and the recipients specified in the message.
Events
OnMessageReady | Fires when the message data has been prepared for sending.
OnReceiveData | Fires when the client receives another data chunk from the server.
OnSendComplete | Fires when the message has been sent.
OnSendData | Fires when the client sends another data chunk to the server.
OnSendProgress | Fires when new portion of the message data has been sent.
OnSendStart | Fires when the SMTP object has got ready to send the message to the SMTP server.

Remarks

During the development, it's recommended to enable logging the SMTP session into a file by setting EnableLogging and LogFilePath properties. The log file allows you to discover typical problems quickly and easily.

You can find more information on typical problems resolution in Troubleshooting section of the SMTP samples.

Example

The following example creates and sends an HTML-formatted message with an attachment. SMTP Authentication is enabled. SMTP session log is written into "C:\Temp\smtp_log.txt" file.
Dim objSMTP

' Using Visual Basic to create object
Set objSMTP = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set objSMTP = Server.CreateObject("MailBee.SMTP")
'
' In ASP, use Response.Write instead of MsgBox

' Enable logging SMTP session into a file
objSMTP.EnableLogging = True
objSMTP.LogFilePath = "C:\Temp\smtp_log.txt"
objSMTP.ClearLog

' Unlock SMTP object
objSMTP.LicenseKey = "put your license key here"

' Set SMTP server name
objSMTP.ServerName = "mail.mydomain.com"

' Set SMTP Authentication method and
' user credentials
objSMTP.AuthMethod = 2
objSMTP.UserName = "jdoe"
objSMTP.Password = "secret"

' Set headers
objSMTP.Message.FromAddr = "John Doe <jdoe@mydomain.com>"
objSMTP.Message.ToAddr = "Bill Smith <b.smith@hisdomain.com>"
objSMTP.Message.Subject = "Question"

' Set HTML body
objSMTP.Message.BodyFormat = 1
objSMTP.Message.BodyText = "<html>How are <i>you</i>?</html>"

' Send message
If objSMTP.Send Then
  ' Succeeded!!
  MsgBox "Sent successfully"
Else
  ' Failed...
  MsgBox "Error #" & objSMTP.ErrCode & _
    ", Last server reply:" & objSMTP.ServerResponse
End If

' Close the connection
objSMTP.Disconnect

See Also

Message Object

Send feedback to AfterLogic


AllowRefusedRecipients Property

Set AllowRefusedRecipients=True to let MailBee ignore "recipient refused" errors from the mail server in case if at least one recipient of multi-recipient e-mail message gets passed through.

By default, refused recipients are not allowed and this property is False.

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' Comment next 3 lines if authentication is not required.
Mailer.AuthMethod = 2 ' Using LOGIN authentication
Mailer.UserName = "MyUserName" ' Mail account name
Mailer.Password = "MyPassword" ' Mail account password

If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Just subject and empty body"
  Mailer.AllowRefusedRecipients = True
  Mailer.Send
  MsgBox "GetRefusedRecipients: " & Mailer.GetRefusedRecipients
  MsgBox "GetAcceptedRecipients: " & Mailer.GetAcceptedRecipients
  Mailer.Disconnect
End If

See Also:

GetRefusedRecipients Method


AltBodyEncoding Property

This is equivalent of SMTP.Message.AltBodyEncoding property

See Also:

SMTP.Message Property


AltBodyText Property

This is equivalent of SMTP.Message.AltBodyText property

See Also:

SMTP.Message Property


AuthMethod Property

Specifies the method to authenticate the mail sender on the SMTP server.

By default, SMTP authentication is not used but most servers nowadays require it so you'll probably need to enable it.

The following authentication methods are allowed:

  • 0 - No Authentication (default value)
  • 1 - PLAIN. Most SMTP servers support it. However, the password is not encrypted during the transfer
  • 2 - LOGIN. Nearly all SMTP servers support it. The password is not encrypted
  • 3 - CRAM-MD5. The password is encrypted
  • 4 - NTLM authentication (sort of Secure Password Authentication - SPA). MS specific, supports IWA
  • 5 - MSN authentication (another name of SPA). MS specific, used very rarely
  • 6 - GSSAPI authentication with internal implementation via NTLM (MS specific, supports IWA)
  • 7 - GSSAPI authentication with internal implementation via Kerberos (MS specific, supports IWA)
  • 8 - XOAUTH2 authentication (OAuth 2.0)
  • 16 - do not authenticate, just connect and say hello.

IWA is an Integrated Windows Authentication (lets you authenticate against a server using the credentials of the currently logged Windows user, no login and password is required).

If your mail server requires users to authenticate themselves, enable SMTP authentication by setting AuthMethod, UserName, Password property values before calling Connect or Send methods.

With OAuth 2.0, you need to have an access token which can be obtained from the mail service provider (this mechanism is unique for each particular provider). They can offer software libraries or other guidelines on how can get access tokens for their service. MailBee Objects ships with VBScript OAuth 2.0 sample for Gmail. You can find it in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder.

Note: Some servers (usually in local networks) do not require and even do not support any kind of SMTP authentication.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer

' Using Visual Basic to create object
Set Mailer = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")
'
' In ASP, use Response.Write instead of MsgBox

' Unlock SMTP component
Mailer.LicenseKey = "put your license key here"

' Specify SMTP server name
Mailer.ServerName = "mail.server.com"

' Use LOGIN authentication method
Mailer.AuthMethod = 2
Mailer.UserName = "johndoe"
Mailer.Password = "secret"

Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "The message body"

' Try to send message
If Mailer.Send Then
  MsgBox "Sent successfully"
Else
  ' Notify user about error
  MsgBox "Error #" & Mailer.ErrCode
End If

' Close the connection
Mailer.Disconnect

See Also:

Connect Method
Domain Property
Password Property
UserName Property


BCCAddr Property

This is equivalent of SMTP.Message.BCCAddr property

See Also:

SMTP.Message Property


BodyEncoding Property

This is equivalent of SMTP.Message.BodyEncoding property

See Also:

SMTP.Message Property


BodyFormat Property

This is equivalent of SMTP.Message.BodyFormat property

See Also:

SMTP.Message Property


BodyText Property

This is equivalent of SMTP.Message.BodyText property

See Also:

SMTP.Message Property


Busy Property

Indicates whether SMTP object is performing long-run operation (such as connecting to the server or sending a message).

When SMTP object is busy, attempt to call any of its methods which exchange data with SMTP server will immediately exit. To cancel currently executing long-run operation, call Abort method.

Note: Busy property is useful on conditions that SMTP object operates in Async mode. See EnableEvents property description for details.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Option Explicit
Dim WithEvents objSMTP As Object

Private Sub Command1_Click()
  Set objSMTP = CreateObject("MailBee.SMTP")
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True ' Enable asynchronous mode
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then ' Long-run operation
    objSMTP.RelayMessage "C:\Data\email.eml", "from@addr.com", "to@addr.com" ' Long-run operation
    objSMTP.Disconnect ' Long-run operation
  End If
End Sub

Private Sub Form_Load()
  Set objSMTP = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If objSMTP Is Nothing Then Exit Sub
  If objSMTP.Busy Then objSMTP.Abort ' Cancel SMTP session on exit
End Sub

See Also:

EnableEvents Property
Abort Method


CCAddr Property

This is equivalent of SMTP.Message.CCAddr property

See Also:

SMTP.Message Property


Charset Property

This is equivalent of SMTP.Message.Charset property

See Also:

SMTP.Message Property


ClientRequest Property

Contains last command string sent to SMTP server by MailBee.

This property is useful for debugging purposes (in conjunction with ServerResponse property).

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  If Not Mailer.Send Then
    If Mailer.ErrCode > 100 Then ' SMTP-specific error, i.e. not connection error
      MsgBox "Last command sent: " & Mailer.ClientRequest
      MsgBox "Server rejected the message and responded: " & Mailer.ServerResponse
    Else
      MsgBox Mailer.ErrDesc ' Timeout occurred, connection lost, etc.
    End If
  End If
  Mailer.Disconnect
Else
  If Mailer.ErrCode > 100 Then ' SMTP-specific error, i.e. not connection error
    MsgBox "Last command sent: " & Mailer.ClientRequest
    MsgBox "Server rejected the connection and responded: " & Mailer.ServerResponse
  Else
    MsgBox Mailer.ErrDesc ' Server not responding, timeout during connecting, etc.
  End If
End If

See Also:

ServerResponse Property


Connected Property

Indicates whether MailBee.SMTP object is connected to SMTP server

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Connect Method


Domain Property

This property may optionally be set to domain name of email address of the sender (such as "host.com"). If this property is not specified, the domain is obtained by scanning FromAddr property (e.g. if FromAddr="joe@server.com", "server.com" would be used as a domain). If FromAddr property is empty or does not contain domain name then host name of the machine where MailBee is running will be used.

This property is used in SMTP HELO (or EHLO for advanced authentication) command to initiate authentication of the sender. Authentication takes place in Connect method, so you must set value of Domain property before calling this method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
Mailer.Domain = "allmighty_sender"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Connect Method
AuthMethod Property
Message Property
Message.FromAddr Property


Enable8bitEncoding Property

This is equivalent of SMTP.Message.Enable8bitEncoding property

See Also:

SMTP.Message Property


EnableEvents Property

MailBee.SMTP object is capable of background processing, so the program's user interface does not hang, and responds to Windows events - this is called "Async mode".

Also, MailBee.SMTP object can fire events itself during long-run long-run methods (Send and RelayMessage) - this is called "Event firing".

When events are turned on, you can abort current operation by calling SMTP.Abort method (for example, in CommandClick sub of Cancel button) or by setting Proceed=False in SMTP event handler (OnSendStart, OnSendProgress, etc).

By default events are turned off because their usage slightly reduces performance. Set EnableEvents=True to enable events. You can then disable them again by setting EnableEvents=False.

Order of firing SMTP events is as following:

  • OnMessageReady (not fired by RelayMessage method)
  • OnSendStart
  • OnSendProgress (may be fired multiple times for a message)
  • OnSendComplete
Note: To use events firing in VB, you also need to check MailBee type library in Project/References and create MailBee.SMTP object using "WithEvents" syntax (see an example below). To enable only Async mode, setting EnableEvents=True is enough ("WithEvents" syntax is not necessarily required).

Value Type: | Boolean
Parameters: | None
Remarks: | Events are useful in event-driven environments only (such as VB, VBA, Delphi, etc). ASP pages cannot handle events

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.RelayMessage "C:\Data\email1.eml", "from@addr.com", "to@addr.com"
    objSMTP.Disconnect
  End If
End Sub

Private Sub objSMTP_OnSendProgress(ByVal TotalBytesSent As Long, Proceed As Boolean)
    MsgBox TotalBytesSent & " bytes sent"
End Sub

See Also:

Abort Method
EnableEvents Property
OnMessageReady Event
OnSendStart Event
OnSendProgress Event
OnSendComplete Event


EnableLogging Property

Set EnableLogging=True to enable logging SMTP session into log file.

By default logging is turned off because it slightly reduces performance. Logging is recommeneded for debug purposes only.

Value Type: | Boolean
Parameters: | None
Remarks: | You can enable logging on even before assigning license key (for example, to determine how many days of trial period have gone up to date)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

See Also:

ClearLog Method
LogFilePath Property


ErrCode Property

Returns completion status of the last operation. This is an extended version of the IsError property. To get string version, use ErrDesc property.

The list of possible values is as follows (codes 0 - 14 are common for POP3, SMTP and IMAP4 objects, codes 1xx are specific to SMTP object):

  • 0 - No Error
  • 1 - Not connected
  • 2 - Already connected
  • 3 - Remote host not resolved
  • 4 - Connection failed (server not found)
  • 5 - Timeout occurred (No response from the server during an interval specified in Timeout property value)
  • 6 - Connection suddenly closed by the server (many servers close connection if the client has no activity for a while. Periodically calling Ping method, the developer can avoid this)
  • 7 - Connection aborted by client side (due to calling of POP3.Abort method)
  • 8 - Other connection-related errors
  • 11 - SSL STARTTLS not supported. SSL connection over regular port is not supported by the server
  • 12 - SSL Init failed. See SSLError property of SSL object for details
  • 13 - SSL Encrypt failed
  • 14 - SSL Decrypt failed
  • 101 - Not licensed (LicenseKey is not assigned, invalid, or expired)
  • 102 - Operation cancelled (If Proceed value in event handlers (OnSendProgress, etc.) is set to False)
  • 111 - ESMTP authentication is not supported by the server at all
  • 112 - Selected ESMTP authentication method is not supported by the server
  • 113 - Selected authentication method failed for unknown reason (should never occur, please contact Technical Support Team if you encounter such error)
  • 114 - Wrong UserName and/or Password. Authentication failed
  • 115 - local host name not resolved (local host name is used as a Domain property value if both Domain property and FromAddr are empty)
  • 116 - other command failure
  • 121 - a sender and at least one recipient must be specified
  • 122 - this sender is not allowed by this mail server
  • 123 - this recipient is not allowed by this mail server. This may also mean maximum allowable number of recipients is already reached
  • 124 - the server rejected DATA command
  • 131 - could not create new filename for queued message (message created with SendToQueue method). Perhaps DirPath parameter points to invalid directory
  • 132 - failed to save queued message file. Check if free space is available on target drive, permissions are set, etc.
  • 133 - could not read rfc822 message file from the specified location (RelayMessage causes this error if FilePath parameter points to invalid file path)

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Connect
If Mailer.IsError Then MsgBox "ErrCode = " & Mailer.ErrCode
Mailer.Disconnect

See Also:

IsError Property
ErrDesc Property
SendToQueue Method
RelayMessage Method
Abort Method


ErrDesc Property

Contains error description. This property is meaningful only if IsError=True.

Enable logging option on and check log file to get detailed error description.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

IsError Property
EnableLogging Property
LogFilePath Property


FromAddr Property

This is equivalent of SMTP.Message.FromAddr property

See Also:

SMTP.Message Property


IsError Property

True if last called MailBee.SMTP method completed with errors. Use ErrDesc property to get error information.

Enable logging option on and check log file to get detailed error description.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ErrDesc Property
EnableLogging Property
LogFilePath Property


IsQueueIIS Property

This property must be set to True if you're submitting e-mails to IIS SMTP queue (with SendToQueue or SendToQueueEx methods).

The default value is False which is suitable if you're using SubmitToQueue or SubmitToQueueEx methods to send to MailBee Message Queue or MailBee.NET Queue.

This property, when set to True, makes MailBee double every dot character when it appears at the first position on a line (as during SMTP conversation). IIS SMTP queue expects .EML files in the queue have these dots doubled while MailBee Message Queue (and MailBee.NET Queue) doubles the dots itself when it actually sends an e-mail to the SMTP server.

Note: this property has no effect if you're sending e-mails to SMTP server (rather than submitting them as .EML files to a pickup folder of MailBee Message Queue or IIS SMTP service).

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
Mailer.IsQueueIIS = True
if Not Mailer.SendToQueue("c:\Inetpub\mailroot\Pickup") Then MsgBox Mailer.ErrDesc

See Also:

SendToQueue Method


Licensed Property

True if MailBee.SMTP object can be used. This means correct LicenseKey has been assigned, and trial period is not yet expired or registered version is used.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Licensed Then
  MsgBox "SMTP object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

LicenseKey Property
ErrDesc Property
EnableLogging Property
LogFilePath Property


LicenseKey Property

License Key of your copy of MailBee.SMTP component.

This property must be set to correct value in order to successfully run MailBee.SMTP object. When Connect or SendToQueue methods are called, they check LicenseKey first. If LicenseKey is invalid or expired, the operation is aborted.

Value Type: | String
Parameters: | None
Remarks: | This property is write-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Licensed Then
  MsgBox "SMTP object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Licensed Property
ErrDesc Property
EnableLogging Property
LogFilePath Property


LogFilePath Property

Path to the log file.

LogFilePath is meaningful only if EnableLogging property is set to True.

Default value is "smtp_log.txt"

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Licensed Then
  MsgBox "SMTP object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ClearLog Method
EnableLogging Property


MailFromDSN Property

Optional DSN suffix for MAIL FROM command.

This is advanced property which lets you configure Delivery Status Notification settings for MAIL FROM command. If not empty, MailBee attaches this suffix to MAIL FROM command (which specifies the e-mail sender). Can be used in conjunction with RcptToDSN property.

Some servers do not support DSN. MailBee won't use append DSN suffix to any command in case if the server does not advertize support of DSN extension.

To learn the syntax of DSN suffixes, refer to RFC 1891 (ESMTP Delivery Status Notifications).

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' Comment next 3 lines if authentication is not required.
Mailer.AuthMethod = 2' Using LOGIN authentication
Mailer.UserName = "MyUserName" ' Mail account name
Mailer.Password = "MyPassword" ' Mail account password

If Mailer.Connect Then
  If Mailer.SupportsDSN Then MsgBox "This SMTP server supports DSN"
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.BodyText = "Test"
  Mailer.Message.MailFromDSN = "RET=HDRS ENVID=QQ314159"
  If Not Mailer.Send Then MsgBox Mailer.ErrDesc
  Mailer.Disconnect
End If

See Also:

RcptToDSN Property
SupportsDSN Property


Message Property

Specifies Message object to be sent by MailBee.SMTP component.

By default, when MailBee.SMTP is instantiated it also creates empty Message object accessible via Message property. However, you can always set Message property to another Message object (for example, the one created by MailBee.POP3 component). Thus you can easily organize message forwarding.

SMTP component has shortcut methods and properties to quickly access composing-oriented methods and properties of contained Message object. For example, SMTP.BodyEncoding is a synonym for SMTP.Message.BodyEncoding.

Value Type: | MailBee.Message
Parameters: | None

Usage example:

'Forwarding with MailBee
Dim objPOP3, objSMTP, Msg
'Using visual basic to create object
Set objPOP3 = CreateObject("MailBee.POP3")
Set objSMTP = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set objPOP3 = Server.CreateObject("MailBee.POP3")
'Set objSMTP = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
objPOP3.LicenseKey = "put your POP3 license key here"
objSMTP.LicenseKey = "put your SMTP license key here"
objPOP3.Connect "mailserver.com", 110, "MyName", "MyPassword"
If objPOP3.Connected Then
   If objPOP3.MessageCount > 0 Then
      Set Msg = objPOP3.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        Msg.ToAddr = "bill@host.com"
        Msg.CCAddr = "" ' Do not send to original CC's
        Msg.Subject = "FW: " & Msg.Subject
        objSMTP.ServerName = "mail.server.com"
        If objSMTP.Connect Then
          Set objSMTP.Message = Msg
          objSMTP.Send
          objSMTP.Disconnect
        End If
      End If
   End If
   objPOP3.Disconnect
End If

See Also:

SMTP Object
POP3 Object
Message Object


Password Property

The password of the user account on the mail server to be used for ESMTP authentication during connection (if AuthMethod>0).

If AuthMethod property has default value (AuthMethod=0), this property is not used.

To avoid sending password as clear text, set AuthMethod=3. This will enable secure CRAM-MD5 authentication. However, many SMTP servers do not support it. See AuthMethod property reference for details.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.AuthMethod = 3 ' Using CRAM-MD5 secure authentication
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected using secure ESMTP authentication"
  Mailer.Disconnect
End If

See Also:

UserName Property
AuthMethod Property
ServerName Property
Connect Method


PortNumber Property

SMTP port number. Default value is 25.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.PortNumber = 1111 ' If  mailserver.com operates on non-standard port
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

AuthMethod Property
ServerName Property
Connect Method


RcptToDSN Property

Optional DSN suffix for RCPT TO commands.

This is advanced property which lets you configure Delivery Status Notification settings for RCPT TO commands. If not empty, MailBee attaches this suffix to each RCPT TO command (which specifies the e-mail recipients). Can be used in conjunction with MailFromDSN property.

Some servers do not support DSN. MailBee won't use append DSN suffix to any command in case if the server does not advertize support of DSN extension.

To learn the syntax of DSN suffixes, refer to RFC 1891 (ESMTP Delivery Status Notifications).

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' Comment next 3 lines if authentication is not required.
Mailer.AuthMethod = 2' Using LOGIN authentication
Mailer.UserName = "MyUserName" ' Mail account name
Mailer.Password = "MyPassword" ' Mail account password

If Mailer.Connect Then
  If Not Mailer.SupportsDSN Then MsgBox "This SMTP server does not support DSN"
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.BodyText = "Test"
  Mailer.Message.RcptToDSN = "NOTIFY=SUCCESS,FAILURE"
  If Not Mailer.Send Then MsgBox Mailer.ErrDesc
  Mailer.Disconnect
End If

See Also:

MailFromDSN Property
SupportsDSN Property


ServerName Property

SMTP server address (like "mail.server.com"), or IP-address (like "123.456.789.123")

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

UserName Property
Password Property
AuthMethod Property
Connect Method


ServerResponse Property

Contains string sent by SMTP server as a response of last performed operation (string caused SMTP server to execute the action is available through ClientRequest property value).

You might consider using this property if you want to know exactly what server reply is. For example, if sending failed even if all parameters (such as sender, recipients) are correct and network connection is stable, you may check this property to determine why SMTP server rejected the sending. Logging feature is also helpful for debugging purposes (EnableLogging property).

In the rest of cases Licensed/ErrDesc/ErrCode/IsError properties would be enough for organizing error-handling mechanism.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  If Not Mailer.Send Then
    If Mailer.ErrCode > 100 Then ' SMTP-specific error, i.e. not connection error
      MsgBox "Server rejected the message and responded: " & Mailer.ServerResponse
    Else
      MsgBox Mailer.ErrDesc ' Timeout occurred, connection lost, etc.
    End If
  End If
  Mailer.Disconnect
Else
  If Mailer.ErrCode > 100 Then ' SMTP-specific error, i.e. not connection error
    MsgBox "Server rejected the connection and responded: " & Mailer.ServerResponse
  Else
    MsgBox Mailer.ErrDesc ' Server not responding, timeout during connecting, etc.
  End If
End If

See Also:

ClientRequest Property
Licensed Property
IsError Property
ErrCode Property
ErrDesc Property
EnableLogging Property
LogFilePath Property


SSL Property

Specifies the SSL object that will be used for managing secure SSL/TLS connections.

If SSL.Enabled is True, then SMTP object will operate in secure mode through SSL/TLS connection.

Note: Many mail servers do not support secure connections.

Value Type: | MailBee.SSL
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "Body"
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

SSL Object


Subject Property

This is equivalent of SMTP.Message.Subject property

See Also:

SMTP.Message Property


SupportsDSN Property

Indicates whether the SMTP server supports DSN (Delivery Status Nofitications).

You must be connected to the server in order to use this property. You can read more on DSN in MailFromDSN property documentation.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Connect
If Mailer.Connected Then
  If Mailer.SupportsDSN Then MsgBox "DSN Supported"
  Mailer.Disconnect
End If

See Also:

MailFromDSN Property


SupportsStartTLS Property

Indicates whether the SMTP server supports STARTTLS command which lets you switch regular connection into secure connection without the need to connect to a dedicated SSL port.

You must be connected to the server in order to use this property. You can read more on STARTTLS in SSL.UseStartTLS property documentation.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Connect
If Mailer.Connected Then
  If Mailer.SupportsStartTLS Then MsgBox "STARTTLS Supported"
  Mailer.Disconnect
End If

See Also:

SSL Property


TagetName Property

The service principal name (SPN) of the SMTP server.

This value can only be used with Kerberos authentication. If an empty string, it's autodetected as "SMTP/<server name>" (which is suitable in most cases). However, IIS SMTP server requires this name to be "SmtpSvc/<server name>" so you may need to set it manually.

To learn SPN of your server, you may use "SetSpn -L server_name" in the command-line of your server if it has SetSpn tool installed.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "host.com"
Mailer.TargetName = "SmtpSvc/host.com"
Mailer.AuthMethod = 7 ' Authenticate with Kerberos
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.AuthMethod = 1 ' Using PLAIN authentication method supported by most SMTP servers
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected using PLAIN authentication method"
  Mailer.Disconnect
End If

See Also:

Password Property
AuthMethod Property
ServerName Property
Connect Method


Timeout Property

Specifies timeout value (the maximum amout of time to wait for response from SMTP server before returning an error) in seconds. Default is 30 sec.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Timeout = 60 ' 1 min
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

UserName Property
Password Property
AuthMethod Property
Connect Method


ToAddr Property

This is equivalent of SMTP.Message.ToAddr property

See Also:

SMTP.Message Property


UserDomain Property

The name of the user domain on the mail server to be used for ESMTP authentication during connecting.

This value can only be used with MS-specific authentication methods like NTLM and GSSAPI. The default value is an empty string (which is suitable in most cases).

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.company.com"
Mailer.UserDomain = "company.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.AuthMethod = 4' Using NTLM authentication method
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected using PLAIN authentication method"
  Mailer.Disconnect
End If

See Also:

Password Property
AuthMethod Property
ServerName Property
Connect Method


UserName Property

The name of the user account on the mail server to be used for ESMTP authentication during connection (if AuthMethod>0).

If AuthMethod property has default value (AuthMethod=0), this property is not used.

This can be left an empty string if you're using Integrated Windows Authentication. See AuthMethod property for details.

Usually this is the first part of the email address (e.g. "bill" for "bill@host.com"). Sometimes, however, it can be full email address or something else (it depends on SMTP account settings).

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.AuthMethod = 1 ' Using PLAIN authentication method supported by most SMTP servers
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected using PLAIN authentication method"
  Mailer.Disconnect
End If

See Also:

Password Property
AuthMethod Property
ServerName Property
Connect Method


Abort Method

Aborts currently performed long-run operation and immediately disconnects from the SMTP server. If no long-run operation is currently performed, the method does nothing.

Long-run operation is any action which causes data exchange with the SMTP server. Connecting to the server, sending a message, graceful disconnecting, etc. are all long-run operations.

To determine whether long-run operation is currently performing, examine Busy property value.

When long-run operation is aborted, rough disconnection procedure takes place (not graceful one) so "QUIT" SMTP command is not executed. This means that some servers may discard messages prepared for relay during the current SMTP session. However, most servers relay messages regardless whether the client has sent "QUIT" command.

Once the connection is aborted, ErrCode property of SMTP object is set to value of 7 (Connection aborted by client side).

Note: Abort method can be called only if SMTP.EnableEvents=True (Async mode is on). Calling Abort method does not immediately closes the connection, it just notifies SMTP object to close it. Closing itself occures after millisecond or so after calling Abort method. This is specifics of Async mode operation.

blnResult = ObjectName.Abort
Parameters: | None
Return value As Boolean | True if successful, False if error has occurred (nothing to abort because there is no long-run operation in progress)

Usage example:

Option Explicit
Dim WithEvents objSMTP As Object

Private Sub Command1_Click()
  Set objSMTP = CreateObject("MailBee.SMTP")
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True ' Enable asynchronous mode
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then ' Long-run operation
    objSMTP.RelayMessage "C:\Data\email.eml", "from@addr.com", "to@addr.com" ' Long-run operation
    objSMTP.Disconnect ' Long-run operation
  End If
End Sub

Private Sub Form_Load()
  Set objSMTP = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If objSMTP Is Nothing Then Exit Sub
  If objSMTP.Busy Then objSMTP.Abort ' Cancel SMTP session on exit
End Sub

See Also:

Busy Property
EnableEvents Property
ErrCode Property


AddAttachment Method

This is equivalent of SMTP.Message.AddAttachment method

See Also:

SMTP.Message Property


AddHeader Method

This is equivalent of SMTP.Message.AddHeader method

See Also:

SMTP.Message Property


ClearLog Method

Clears log file (if logging is on).

Consider calling this method each time your application starts or enters new cycle of processing. Otherwise, log file will increase in size with every SMTP session.

blnResult = ObjectName.ClearLog
Parameters: | None
Return value As Boolean | True if successful, False if logging is off or error occurred (path denoted by LogFilePath property is not accessible, file is locked, etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

See Also:

EnableLogging Property
LogFilePath Property


Connect Method

Connects to the SMTP server, sends hello and optionally authenticates the client.

Make sure to set at least the following properties before calling this method:

  • LicenseKey
  • ServerName
In most cases, you'll also need to use ESMTP authentication (EHLO command), also set AuthMethod and UserName/Password properties before calling Connect method. You'll not need this only if your server allows anonymous senders to relay e-mail which is quite uncommon nowadays.

It's not required to call this method in order to connect to SMTP server (though it's recommended). Methods of SMTP object (such as Send, SendEx, RelayMessage) automatically call it if the connection is not established.

With NTLM and GSSAPI authentication, you may also want to set UserDomain property. Also, GSSAPI/Kerberos method allows setting TargetName (SPN).

If you're using Integrated Windows Authentication (IWA), you may leave UserName and Password blank but must set AuthMethod property to use IWA-compatible authentication method.

Note: If ESMTP authentication is not used (AuthMethod=0), connection procedure starts with "HELO Your domain" command. You can specify "Your domain" explicitly using Domain property. If Domain property is empty, host name of the machine running MailBee will be used as a domain.

Domain and UserDomain properties have different meaning. UserDomain is used during authentication (NTLM or GSGAPI), UserDomain is linked with UserName property. Domain property, however, is used when the client says hello to the server and its value is should be the host name of the client (MailBee machine).

blnResult = ObjectName.Connect
Parameters: | None
Return value As Boolean | True if successful, False if connect procedure failed (mail server is not responding, username and/or password is incorrect, authentication method is not supported, license key is invalid). You may check ErrDesc property or log file to get more detailed error information

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.AuthMethod = 1 ' PLAIN ESMTP authentication
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send
  Mailer.Disconnect
Else
  ' Server not available, PLAIN is not supported or username/password is incorrect
  MsgBox Mailer.ErrDesc
End If

See Also:

ServerName Property
Domain Property
Message.FromAddr Property
PortNumber Property
UserName Property
Password Property
AuthMethod Property
Disconnect Method


Disconnect Method

Disconnects from the SMTP server.

It is not necessary (though it's recommended) to call this method. The SMTP object automatically disconnects from SMTP server when the object is to be freed.

blnResult = ObjectName.Disconnect
Parameters: | None
Return value As Boolean | True if successful, False if disconnect procedure failed (was not connected, mail server is not responding). You can check ErrDesc property or log file to get more detailed error information
Remarks: | Even if this method failed, connection will be closed anyway. This means that Connected property will be always False after calling Disconnect method.

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.Domain = "mydomain"
If Mailer.Connect
  Mailer.RelayMessage "C:\msg.eml", "from@me.com", "to@you.com"
  If Mailer.Disconnect Then
    MsgBox "Connection gracefully closed"
  Else
    MsgBox "Connection aborted"
  End If
End If

See Also:

Connect Method


EncodeHeaderText Method

This is equivalent of SMTP.Message.EncodeHeaderText method

See Also:

SMTP.Message Property


ExecuteCommand Method

ExecuteCommand method sends specified string of data to the SMTP server. Commands must end with CRLF pair (vbCrLf constant in Visual Basic and ASP).

blnResult = ObjectName.ExecuteCommand(Command)

Parameters: |
Value As String | A string expression containing command name for execution.
Return value As Boolean | True if successful, otherwise False.

Usage example:

' This sample sends the command 'ehlo' to the server and outputs its result

Dim Mailer
' Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.SMTP")
' In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
   Mailer.ExecuteCommand "ehlo yourdomain.com" & vbCrLf
   MsgBox Mailer.ServerResponse
   Mailer.Disconnect
End If

See Also:

SMTP Object


GetAcceptedRecipients Method

Returns the comma-separated string which lists the e-mail addresses of recipients which have been accepted by the server during sending.

This method makes sense only when AllowRefusedRecipients is True. Otherwise, if the message was sent successfully, this will means all the recipients have been accepted anyway.

[Visual Basic]

strData = ObjectName.GetAcceptedRecipients

Parameters: | None
Return valueAs String | The string containing the e-mail addresses separated with ", ".
Remarks: | For readility, the e-mail addresses are separated with "," followed by " " (extra space after each comma).

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' Comment next 3 lines if authentication is not required.
Mailer.AuthMethod = 2 ' Using LOGIN authentication
Mailer.UserName = "MyUserName" ' Mail account name
Mailer.Password = "MyPassword" ' Mail account password

If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Just subject and empty body"
  Mailer.AllowRefusedRecipients = True
  Mailer.Send
  MsgBox "GetRefusedRecipients: " & Mailer.GetRefusedRecipients
  MsgBox "GetAcceptedRecipients: " & Mailer.GetAcceptedRecipients
  Mailer.Disconnect
End If

See Also:

GetRefusedRecipients method


GetLastDataFromClient Method

Returns the last received portion of data sent by the client.

When OnSendData event occurs, you can use this method to actually receive the data for which this event was triggered. The method must be called once per OnSendData event occurrence. Next time this event triggers, GetLastDataFromClient will return the new portion of data, and so on.

[Visual Basic]

strData = ObjectName.GetLastDataFromClient

Parameters: | None
Return valueAs String | The string containing the last data chunk sent by the client to the server.

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.Message.ToAddr = "bill@yoursite.com"
    objSMTP.Message.FromAddr = "joe@mysite.com"
    objSMTP.Message.Subject = "Hello"
    objSMTP.Message.BodyText = "Body text"
    objSMTP.Send
    objSMTP.Disconnect
  End If
End Sub

Private Sub SMTP_OnReceiveData(ByVal BytesReceived As Long, Proceed As Boolean)
    Debug.Print "BytesReceived=" & BytesReceived
    Debug.Print "SMTP.GetLastDataFromServer=[" & SMTP.GetLastDataFromServer & "]"
End Sub

Private Sub SMTP_OnSendData(ByVal BytesSent As Long, Proceed As Boolean)
    Debug.Print "BytesSent=" & BytesSent
    Debug.Print "SMTP.GetLastDataFromClient=[" & SMTP.GetLastDataFromClient & "]"
End Sub

See Also:

GetLastDataFromServer method


GetLastDataFromServer Method

Returns the last received portion of data from the server.

When OnReceiveData event occurs, you can use this method to actually receive the data for which this event was triggered. The method must be called once per OnReceiveData event occurrence. Next time this event triggers, GetLastDataFromServer will return the new portion of data, and so on.

[Visual Basic]

strData = ObjectName.GetLastDataFromServer

Parameters: | None
Return valueAs String | The string containing the last data chunk received from the server.

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.Message.ToAddr = "bill@yoursite.com"
    objSMTP.Message.FromAddr = "joe@mysite.com"
    objSMTP.Message.Subject = "Hello"
    objSMTP.Message.BodyText = "Body text"
    objSMTP.Send
    objSMTP.Disconnect
  End If
End Sub

Private Sub SMTP_OnReceiveData(ByVal BytesReceived As Long, Proceed As Boolean)
    Debug.Print "BytesReceived=" & BytesReceived
    Debug.Print "SMTP.GetLastDataFromServer=[" & SMTP.GetLastDataFromServer & "]"
End Sub

Private Sub SMTP_OnSendData(ByVal BytesSent As Long, Proceed As Boolean)
    Debug.Print "BytesSent=" & BytesSent
    Debug.Print "SMTP.GetLastDataFromClient=[" & SMTP.GetLastDataFromClient & "]"
End Sub

See Also:

GetLastDataFromClient method


GetRefusedRecipients Method

Returns the comma-separated string which lists the e-mail addresses of recipients which have been rejected by the server during sending.

This method makes sense only when AllowRefusedRecipients is True and when the message has multiple recipients. When it's False, MailBee stops sending when it encounters any refused recipient. When the message has only one recipient, refusing it by the server also means the message cannot be sent.

[Visual Basic]

strData = ObjectName.GetRefusedRecipients

Parameters: | None
Return valueAs String | The string containing the e-mail addresses separated with ", ".
Remarks: | For readility, the e-mail addresses are separated with "," followed by " " (extra space after each comma).

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' Comment next 3 lines if authentication is not required.
Mailer.AuthMethod = 2 ' Using LOGIN authentication
Mailer.UserName = "MyUserName" ' Mail account name
Mailer.Password = "MyPassword" ' Mail account password

If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Just subject and empty body"
  Mailer.AllowRefusedRecipients = True
  Mailer.Send
  MsgBox "GetRefusedRecipients: " & Mailer.GetRefusedRecipients
  MsgBox "GetAcceptedRecipients: " & Mailer.GetAcceptedRecipients
  Mailer.Disconnect
End If

See Also:

GetAcceptedRecipients method


GetRelayServerFromEmailAddress Method

Gets the host name of the domain willing to accept the mails for the specified e-mail address or an empty string if error occurred.

The developer can use the obtained name of SMTP server to send the message to the account on this server without any authentication.

[Visual Basic]

blnResult = ObjectName.GetRelayServerFromEmailAddress(EmailAddress,[DNSServer],[SingleAttemptOnly],[Timeout])
Parameters:
EmailAddress As String | The e-mail address.
DNSServer As String

(optional) The IP address of the DNS server. If this parameter is ommited, MailBee extracts it from Windows settings.

Also, the developer can also specify two DNS servers to increase the reliability of DNS MX lookup operation. The semicolon (;) is used as a delimeter character. For instance, the "125.145.34.4" or "45.15.6;45.22.22.2" values are supported.
SingleAttemptOnly As String | (optional) If True, MailBee won't send request second time if the first one fails. Less reliable but faster. The default is False.
Timeout as Long | (optional) Number of seconds to wait for response from the DNS servers. The default value is 3.
Return valueAs String | The string containing the name of SMTP MX server. For instance, if the "brown@domain.com" address is specified, the "smtp.domain.com" value could be returned.

Usage example:

' This example creates a new message and sends it without any authentication

Dim Mailer

Mailer.LicenseKey = "Put your license key here"

' Specify the e-mail address of message sender
Mailer.FromAddr = "john@domain.com"

' Specify the e-mail address of message recipient
Mailer.ToAddr = "barbara@domain.com"

' Specify the subject of the message
Mailer.Subject = "Hi, Barbara."

' Specify the text of the message body
Mailer.BodyText = "How are you?"

' Extract the name of the SMTP server to be used to sent the message
Mailer.ServerName = objSMTP.GetRelayServerFromEmailAddress("barbara@domain.com")

' Send the composed message without any authentication
Mailer.Send

' Disconnect from the mail server
Mailer.Disconnect

See Also:

ServerName Property


ImportAltBodyText Method

This is equivalent of SMTP.Message.ImportAltBodyText method

See Also:

SMTP.Message Property


ImportBodyText Method

This is equivalent of SMTP.Message.ImportBodyText method

See Also:

SMTP.Message Property


MakeAltBody Method

This is equivalent of SMTP.Message.MakeAltBody method

See Also:

SMTP.Message Property


RelayMessage Method

Relays (forwards) previously saved message to one or more recipients.

The message file must be in RFC822 format (Message.SaveMessage method produces such files, and many other mail programs also understand this format).

blnResult = ObjectName.RelayMessage(FilePath, FromAddr, Recips)
Parameters: |
FilePath As String | Path to the RFC822-formatted file to send
FromAddr As String | E-mail address of the sender. This value can differ from the value of the "From" header in the message itself
Recips As String | comma-separated list of recipients' email addresses. This value can differ from the value of the "To", "CC" headers in the message itself
Return value As Boolean | True if successful, False otherwise

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
If Mailer.Connect Then
  Mailer.RelayMessage "C:\Docs\msg.eml", "alex@myhost.com","joe@hishost.com,jane@hershost.com"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Connect Method
Send Method


ResetMessage Method

Destroys contained Message object and creates new one thus resetting all properties and collections of contained Message object to their default values.

You may use this method to create and send multiple messages over the same connection.

ObjectName.ResetMessage
Parameters: | None
Return value | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send ' First message will have HTML body
  Mailer.ResetMessage
  Mailer.Message.ToAddr = "john@server1.com"
  Mailer.Message.FromAddr = "ed@server2.com"
  Mailer.Subject = "How are you?"
  Mailer.Send ' Second message will have empty body
  Mailer.Disconnect
End If

See Also:

Message Property
Send Method


ResolveHostName Method

Returns the IP address of the specified host name.

[Visual Basic]

strIPAddr = ObjectName.ResolveHostName(HostName)

Parameters: |
HostName As String | The name of the host to be resolved into the IP address.
Return value As String | The IP address associated with the specified host name.

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox

' Display the IP address of the specified host name
MsgBox objSMTP.ResolveHostName("www.afterlogic.com")

See Also:

ServerName Property


Send Method

Sends the message to SMTP server.

To send from fake address, use SendEx method. Sending from fake address commonly used in group mailings to make sure bounce mails are all arrive to the same address.

Note: Many SMTP servers require user authentication in order to send emails. See AuthMethod property reference for details. Sample code below uses authentication. If it is not required or not supported by your server, comment corresponding lines or just set AuthMethod=0.

blnResult = ObjectName.Send
Parameters: | None
Return value As Boolean | True if successful, False otherwise

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' Comment next 3 lines if authentication is not required.
Mailer.AuthMethod = 1 ' Using PLAIN authentication
Mailer.UserName = "MyUserName" ' Mail account name
Mailer.Password = "MyPassword" ' Mail account password

If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  If Not Mailer.Send Then MsgBox Mailer.ErrDesc
  Mailer.Disconnect
End If

See Also:

"Creating and sending HTML-formatted messages" Tutorial

Connect Method
SendEx Method
SendToQueue Method
RelayMessage Method


SendEx Method

Sends the message to SMTP server. In addition to standard sending functionality, it allows sending messages from fake addresses (From header is ignored) to addresses different from those specified in To/CC/BCC headers.

When used without parameters, this method behaves identically to Send method.

Note: You may use this method for messages blind-forwarding (i.e. resending messages wihout any modifications).

blnResult = ObjectName.SendEx([FromAddr], [Recips])
Parameters: |
FromAddr As String | (optional) If specified, overrides SMTP.Message.FromAddr setting. This may be used if you want to send email from address different from those specified in From header (sending from fake address)
Recips As String | (optional) If specified, overrides SMTP.Message.ToAddr/CCAddr/BCCAddr setting. This may be used if you want to send email to addresses different from those specified in To/CC/BCC headers
Return value As Boolean | True if successful, False otherwise. Note, that if error occurred because SMTP server rejected the message (wrong sender, recipient, message too large, etc.), Send method returns False but no automatic Disconnect occurs (so you can fix the problem and resend the message over the same connection)
Remarks: | Some servers do not allow email address overriding (sending from fake address). However, if you are sending from real (not fake) address but this address is different from those specified in From header, you may try to add Resent-From header to the message (see example below)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.AddHeader "Resent-From", "myrealaddress@myownsite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  If Not Mailer.SendEx("myrealaddress@myownsite.com", _
    "George Jones<george@abc.com>") Then MsgBox Mailer.ErrDesc
  Mailer.Disconnect
End If

See Also:

"Creating and sending HTML-formatted messages" Tutorial

Connect Method
Send Method
SendToQueue Method
RelayMessage Method


SendToQueue Method

Submits the message to IIS SMTP queue (pickup folder) or to MailBee Message Queue (legacy) or MailBee.NET Queue (modern) system for delivery.

MailBee Message Queue (MMQ) is a message queuing system which intercepts mail transmissions from the SMTP object and sends them in the background. This allows the SMTP object to operate very quickly. MailBee.NET Queue is a modern version, it adds SSL/TLS support, direct send without SMTP relay server, and many other features. MailBee.NET Queue, however, needs .NET Framework. From the point of view of MailBee SMTP component, both versions behave identically.

IIS SMTP server is also capable of bypassing SMTP protocol and picking messages directly from the file system.

Another reason to use submitting to the pickup folder (especially in the case of IIS SMTP queue) is security. Often, firewalls do not allow applications to send mail via SMTP. In this case, the only way is to submit messages into the pickup folder of IIS SMTP queue.

Both MMQ and IIS SMTP use the same queue file format and thus it's possible to use this method to submit into any of these queues. However, IIS SMTP pickup service cannot double first dots on a line as required by the SMTP protocol and thus it's the responsibility of the application which produces .EML files.

In short, before submitting to IIS SMTP pickup service, set IsQueueIIS property value to True.

To send from fake address, use SendToQueueEx method. Sending from fake address commonly used in group mailings to make sure bounce mails are all arrive to the same address.

Unlike Send method, SendToQueue method does not require established connection to SMTP server. Actual connection and data transfer is made by MMQ (or IIS SMTP) system. However, LicenseKey property must be still specified.

blnResult = ObjectName.SendToQueue(DirPath)
Parameters: |
DirPath As String | Path to the directory used by IIS SMTP (usually, C:\Inetpub\mailroot\pickup) or by MMQ as a storage of message files (QueueDirPath parameter in mmq.ini file) or by MailBee.NET Queue (the default is "c:\MailBeeNetQueue Files\Pickup")
Return value As Boolean | True if successful, False otherwise (invalid license key, queue dir doesn't exist, i/o error, etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
if Not Mailer.SendToQueue("C:\MMQ Files") Then MsgBox Mailer.ErrDesc

See Also:

"Creating and sending HTML-formatted messages" Tutorial

LicenseKey Property
IsQueueIIS Property

SendToQueueEx Method


SendToQueueEx Method

Submits the message to IIS SMTP pickup folder or to MailBee Message Queue (legacy) or MailBee.NET Queue (modern) system for delivery.

In addition to standard "send-to-queue" functionality, it allows sending messages from fake addresses (From header is ignored) to addresses different from those specified in To/CC/BCC headers.

Sending from fake address commonly used in group mailings to make sure bounce mails are all arrive to the same address.

MailBee Message Queue (MMQ) is a message queuing system which intercepts mail transmissions from the SMTP object and sends them in the background. This allows the SMTP object to operate very quickly. MailBee.NET Queue is a modern version, it adds SSL/TLS support, direct send without SMTP relay server, and many other features. MailBee.NET Queue, however, needs .NET Framework. From the point of view of MailBee SMTP component, both versions behave identically.

IIS SMTP server is also capable of bypassing SMTP protocol and picking messages directly from the file system.

Both MMQ and IIS SMTP use the same queue file format and thus it's possible to use this method to submit into any of these queues. However, IIS SMTP pickup service cannot double first dots on a line as required by the SMTP protocol and thus it's the responsibility of the application which produces .EML files.

In short, before submitting to IIS SMTP pickup service, set IsQueueIIS property value to True.

Another reason to use submitting to the pickup folder (especially in the case of IIS SMTP queue) is security. Often, firewalls do not allow applications to send mail via SMTP. In this case, the only way is to submit messages into the pickup folder of IIS SMTP queue.

Unlike Send/SendEx methods, SendToQueueEx method does not require established connection to SMTP server. Actual connection and data transfer is made by MMQ system. However, LicenseKey property must be still specified.

blnResult = ObjectName.SendToQueueEx(DirPath, [FromAddr], [Recips])
Parameters: |
DirPath As String | Path to the directory used by IIS SMTP (usually, C:\Inetpub\mailroot\pickup) or by MMQ as a storage of message files (QueueDirPath parameter in mmq.ini file) or by MailBee.NET Queue (the default is "c:\MailBeeNetQueue Files\Pickup")
FromAddr As String | (optional) If specified, overrides SMTP.Message.FromAddr setting. This may be used if you want to send email from address different from those specified in From header (sending from fake address)
Recips As String | (optional) If specified, overrides SMTP.Message.ToAddr/CCAddr/BCCAddr setting. This may be used if you want to send email to addresses different from those specified in To/CC/BCC headers
Return value As Boolean | True if successful, False otherwise (invalid license key, queue dir doesn't exist, i/o error, etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
Mailer.IsQueueIIS = True
if Not Mailer.SendToQueueEx("C:\Inetpub\mailroot\pickup", "realsender@server.com") Then MsgBox Mailer.ErrDesc

See Also:

"Creating and sending HTML-formatted messages" Tutorial

Connect Method
Send Method
IsQueueIIS Property
LicenseKey Property


OnMessageReady Event

Fired by SMTP object after generating MIME-formatted message body.

This is the first event fired by Send and SendEx methods. RelayMessage method does not fire this event because raw body is not generated by this method.

Parameters: |
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue sending message data. You can set it to False to immediately abort SMTP session and disconnect from SMTP server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.Message.ToAddr = "bill@yoursite.com"
    objSMTP.Message.FromAddr = "joe@mysite.com"
    objSMTP.Message.Subject = "Hello"
    objSMTP.Message.ImportBodyText "C:\docs\letter.htm", True
    objSMTP.Message.BodyEncoding = 2
    objSMTP.Send
    objSMTP.Disconnect
  End If
End Sub

Private Sub objSMTP_OnMessageReady(Proceed As Boolean)
    Proceed = (MsgBox("Proceed with sending?", vbYesNo) = vbYes)
End Sub

See Also:

EnableEvents Property
OnSendStart Event
OnSendProgress Event
OnSendComplete Event


OnReceiveData Event

Fired by SMTP object after receving a new chunk of data from the server.

Parameters: |
BytesReceived As Long | The size of the data chunk received at this time.
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue SMTP session. You can set it to False to immediately abort SMTP session and disconnect from SMTP server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.Message.ToAddr = "bill@yoursite.com"
    objSMTP.Message.FromAddr = "joe@mysite.com"
    objSMTP.Message.Subject = "Hello"
    objSMTP.Message.BodyText = "Body text"
    objSMTP.Send
    objSMTP.Disconnect
  End If
End Sub

Private Sub SMTP_OnReceiveData(ByVal BytesReceived As Long, Proceed As Boolean)
    Debug.Print "BytesReceived=" & BytesReceived
    Debug.Print "SMTP.GetLastDataFromServer=[" & SMTP.GetLastDataFromServer & "]"
End Sub

Private Sub SMTP_OnSendData(ByVal BytesSent As Long, Proceed As Boolean)
    Debug.Print "BytesSent=" & BytesSent
    Debug.Print "SMTP.GetLastDataFromClient=[" & SMTP.GetLastDataFromClient & "]"
End Sub

See Also:

EnableEvents Property
OnSendProgress Event


OnSendData Event

Fired by SMTP object after sending a new chunk of any data to the server.

This event is fired any time the client sending anything to the server, not only when the client sends the actual message data (like OnSendProgress event does).

Parameters: |
BytesSent As Long | The size of the data chunk sent at this time.
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue SMTP session. You can set it to False to immediately abort SMTP session and disconnect from SMTP server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.Message.ToAddr = "bill@yoursite.com"
    objSMTP.Message.FromAddr = "joe@mysite.com"
    objSMTP.Message.Subject = "Hello"
    objSMTP.Message.BodyText = "Body text"
    objSMTP.Send
    objSMTP.Disconnect
  End If
End Sub

Private Sub SMTP_OnReceiveData(ByVal BytesReceived As Long, Proceed As Boolean)
    Debug.Print "BytesReceived=" & BytesReceived
    Debug.Print "SMTP.GetLastDataFromServer=[" & SMTP.GetLastDataFromServer & "]"
End Sub

Private Sub SMTP_OnSendData(ByVal BytesSent As Long, Proceed As Boolean)
    Debug.Print "BytesSent=" & BytesSent
    Debug.Print "SMTP.GetLastDataFromClient=[" & SMTP.GetLastDataFromClient & "]"
End Sub

See Also:

EnableEvents Property
OnSendProgress Event


OnSendStart Event

Fired by SMTP object when it finished to send message envelope information (sender and recipients e-mail addresses) to the SMTP server and ready to submit the message itself.

Firing this event denotes that the mail server accepted the sender and recipients of the message. However, the server may still reject the message on the next stage due to too large size or inappropriate content of the message, etc.

This event can be fired by both Send and RelayMessage methods.

Parameters: |
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue sending message data. You can set it to False to immediately abort SMTP session and disconnect from SMTP server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.Message.ToAddr = "bill@yoursite.com"
    objSMTP.Message.FromAddr = "joe@mysite.com"
    objSMTP.Message.Subject = "Hello"
    objSMTP.Message.ImportBodyText "C:\docs\letter.htm", True
    objSMTP.Message.BodyEncoding = 2
    objSMTP.Send
    objSMTP.Disconnect
  End If
End Sub

Private Sub objSMTP_OnSendStart(Proceed As Boolean)
    Proceed = (MsgBox("Proceed with sending?", vbYesNo) = vbYes)
End Sub

See Also:

EnableEvents Property
OnMessageReady Event
OnSendProgress Event
OnSendComplete Event


OnSendProgress Event

Fired by SMTP object after sending new chunk of message data.

This event can be fired multiple times (because each chunk has only 8 Kbytes length).

This event can be fired by both Send and RelayMessage methods.

Parameters: |
TotalBytesSent As Long | Total count of message bytes already sent
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue sending message data. You can set it to False to immediately abort SMTP session and disconnect from SMTP server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.Message.ToAddr = "bill@yoursite.com"
    objSMTP.Message.FromAddr = "joe@mysite.com"
    objSMTP.Message.Subject = "Hello"
    objSMTP.Message.ImportBodyText "C:\docs\letter.htm", True
    objSMTP.Message.BodyEncoding = 2
    objSMTP.Send
    objSMTP.Disconnect
  End If
End Sub

Private Sub objSMTP_OnSendProgress(ByVal TotalBytesSent As Long, Proceed As Boolean)
    MsgBox TotalBytesSent & " bytes sent"
End Sub

See Also:

EnableEvents Property
OnMessageReady Event
OnSendStart Event
OnSendComplete Event


OnSendComplete Event

Fired by SMTP object when message sending is complete.

Firing this event denotes that SMTP server received all message data and returned response whether the message was accepted or not.

This event can be fired by both Send and RelayMessage methods.

Parameters: |
Accepted As Boolean | If True, SMTP server has accepted the message for delivery. False if the message was rejected (see SMTP.ErrDesc value for details)
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objSMTP As MailBee.SMTP

Private Sub Form_Load()
  Set objSMTP = New MailBee.SMTP
  objSMTP.LicenseKey = "put your license key here"
  objSMTP.EnableEvents = True
  objSMTP.ServerName = "mailserver.com"
  If objSMTP.Connect Then
    objSMTP.Message.ToAddr = "bill@yoursite.com"
    objSMTP.Message.FromAddr = "joe@mysite.com"
    objSMTP.Message.Subject = "Hello"
    objSMTP.Message.ImportBodyText "C:\docs\letter.htm", True
    objSMTP.Message.BodyEncoding = 2
    objSMTP.Send
    objSMTP.Disconnect
  End If
End Sub

Private Sub objSMTP_OnSendComplete(ByVal Accepted As Boolean)
    If Not Accepted Then MsgBox "The message was rejected by the server"
End Sub

See Also:

EnableEvents Property
OnMessageReady Event
OnSendStart Event
OnSendProgress Event


POP3 Object

You can use the POP3 object to establish the connection with the POP3 server and log in mail accounts, learn the number and the size of messages on the server, search for new messages, download message headers and entire messages, and delete messages from the mail account.

Another features of the POP3 object include secure authentication options (OAuth 2.0, APOP, NTLM, GSSAPI/Kerberos and others), Integrated Windows Authentication with no username/password specified, ability to execute user-supplied commands, keep-alive connections support, and more.

Note: By default, the POP3 object neither processes Windows events nor fires its own events. This ensures maximum performance in the server environment such as ASP, but causes the user interface of desktop applications to be not responsive. To enable event handling and firing, you can set EnableEvents property value to True.

Syntax

POP3.property|method

Properties
AuthMethod | Specifies the authentication method to use when logging in the POP3 mail account.
Busy | Indicates whether the POP3 object is in the progress of sending or receiving data.
ClientRequest | Returns the last command string sent to the POP3 server.
Connected | Indicates whether the POP3 session is active.
EnableEvents | Specifies whether the POP3 object will handle and fire events.
EnableLogging | Specifies whether the POP3 object must log the POP3 session into a file.
ErrCode | Completion status of the last command.
ErrDesc | Contains textual error description if the last command has completed with an error.
IsError | Indicates whether the last command has completed with errors.
Licensed | Indicates whether valid license key has been assigned to the POP3 object.
LicenseKey | Sets the license key to be used with the POP3 object.
LogFilePath | Sets filename of the POP3 session log file.
MessageCount | The total number of messages in the mail account.
Password | The password of the user account on the POP3 server.
PortNumber | The port number of the POP3 service on the server. Defaults to 110.
ServerName | The POP3 server name.
ServerResponse | Returns the string that contains the entire last reply from the POP3 server.
Size | Returns the size of the specified message in bytes.
SSL | Specifies the SSL object to be used to establish secure TLS connection with the POP3 server.
TargetName | The SPN of the server (only used with Kerberos authentication).
Timeout | The timeout value in seconds.
TotalSize | Returns the overall size in bytes of all messages in the mailbox.
UserDomain | The name of the user domain on the POP3 server (only used with MS specific authentication types like NTLM).
UserName | The name of the user account on the POP3 server.
Methods
Abort | Aborts current operation and immediately closes the POP3 session.
ClearLog | Clears the POP3 session log file.
Connect | Connects to the POP3 server and logs in the user mail account.
DeleteMessage | Marks the specified message as "Deleted".
Disconnect | Disconnects from the POP3 server.
GetLastReceivedDataChunk | Gets the data portion received from the server during last receive-data operation.
GetMessageNumberFromUID | Returns the ordinal position of a message given its Unique-ID.
GetMessageUID | Returns Unique-ID (UID) value for a message.
Ping | Sends NOOP command to the POP3 server.
RetrieveHeaders | Downloads all message headers from the mailbox.
RetrieveMessages | Downloads all messages from the mailbox.
RetrieveSingleMessage | Downloads a message from the mailbox.
RetrieveSingleMessageHeaders | Downloads the headers for a message from the mailbox.
Search | Returns an array which contains Unique-ID's (UID's) for all messages in the mailbox.
SendCommand | Executes user-supplied command on the POP3 server.
Events
OnMessageComplete | Fires when the message data just received has been successfully parsed and placed into the Message object.
OnReceiveComplete | Fires when the message data has been completely received from the POP3 server.
OnReceiveProgress | Fires when new portion of the message data has arrived.
OnReceiveStart | Fires when the POP3 object has got ready to retrieve a message from the POP3 server.

Remarks

During the development, it's recommended to enable logging the POP3 session into a file by setting EnableLogging and LogFilePath properties. The log file allows you to discover typical problems quickly and easily.

You can find more information on typical problems resolution in Troubleshooting section of the POP3 samples.

Example

The following example downloads the headers for all messages in the mailbox, and displays common headers ("From:", "To:", "Subject:", "Date:") to the user. The sample is presented separately in Visual Basic version and ASP version since they differ quite enough.

[Visual Basic]
Dim objPOP3, objMsgs, I

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Download the headers for all messages in the mailbox
Set objMsgs = objPOP3.RetrieveHeaders

If objPOP3.IsError Then
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
Else
  ' Display the messages info
  For I = 1 To objMsgs.Count
    MsgBox _
      "From: " & objMsgs(I).FromAddr & vbCrLf & _
      "To: " & objMsgs(I).ToAddr & vbCrLf & _
      "Subject: " & objMsgs(I).Subject & vbCrLf & _
      "Date: " & objMsgs(I).Date
  Next
End If

' Close the connection
objPOP3.Disconnect

[ASP]
<%
Dim objPOP3, objMsgs, I

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Download the headers for all messages in the mailbox
Set objMsgs = objPOP3.RetrieveHeaders

If objPOP3.IsError Then
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
Else
  ' Display the messages info.
  ' We use Server.HTMLEncode to convert '<' and '>'
  ' characters which can disturb the output if they
  ' are contained in the message headers.
  For I = 1 To objMsgs.Count
    Response.Write _
      "From: " & Server.HTMLEncode(objMsgs(I).FromAddr) & "<br>" & _
      "To: " & Server.HTMLEncode(objMsgs(I).ToAddr) & "<br>" & _
      "Subject: " & Server.HTMLEncode(objMsgs(I).Subject) & "<br>" & _
      "Date: " & objMsgs(I).Date & vbCrLf & "<hr>"
  Next
End If

' Close the connection
objPOP3.Disconnect
%>

See Also

Message Object

Send feedback to AfterLogic


AuthMethod Property

MailBee.POP3 object can establish connection with the POP3 server using various authentication types.

Default setting is a regular authentication. All POP3 servers support it, but it is insecure if the connection itself is not secure. During regular authentication user password is sent to server in a plain-text form, so the password can be intercepted by a malicious person. In case if the connection is protected with SSL/TLS, this is not a problem.

However, MailBee also supports secure authentication methods and OAuth 2.0. All you need for using a secure connection is to set AuthMethod property value prior to connecting.

With OAuth 2.0, you need to have an access token which can be obtained from the mail service provider (this mechanism is unique for each particular provider). They can offer software libraries or other guidelines on how can get access tokens for their service. MailBee Objects ships with VBScript OAuth 2.0 sample for Gmail. You can find it in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder.

Also, MailBee supports Integrated Windows Authentication (IWA) so you can use any of NTLM or GSSAPI methods specifying empty username. In this case, MailBee will automatically obtain the current user credentials from the operating system. This is widely used with Microsoft services like MS Exchange Server or IIS.

AuthMethod property must be set BEFORE calling Connect method, otherwise it will not take effect.

The following authentication method are allowed:

  • 0 - Regular (default value)
  • 1 - APOP command. Secure MD5-based authentication type, supported by most POP3 servers
  • 2 - NTLM authentication (sort of Secure Password Authentication - SPA). MS specific, supports IWA
  • 3 - MSN authentication (another name of SPA). MS specific, used very rarely
  • 4 - GSSAPI authentication with internal implementation via NTLM (MS specific, supports IWA)
  • 5 - GSSAPI authentication with internal implementation via Kerberos (MS specific, supports IWA)
  • 6 - XOAUTH2 authentication (OAuth 2.0)
  • 16 - do not authenticate, just connect.
Note: Particular POP3 server might not support secure authentication types.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.AuthMethod = 1 ' Using APOP secure authentication
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected using APOP command"
  Mailer.Disconnect
End If

See Also:

Connect Method


Busy Property

Indicates whether POP3 object is performing long-run operation (such as connecting to the server or retrieving messages).

When POP3 object is busy, attempt to call any of its methods which exchange data with POP3 server will immediately exit. To cancel currently executing long-run operation, call Abort method.

Note: Busy property is useful on conditions that POP3 object operates in Async mode. See EnableEvents property description for details.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Option Explicit
Dim objPOP3 As Object

Private Sub Command1_Click()
  Dim Msgs As Object
  Set objPOP3 = CreateObject("MailBee.POP3")
  objPOP3.LicenseKey = "put your license key here"
  objPOP3.EnableEvents = True ' Enable asynchronous mode
  If objPOP3.Connect("mailserver.com", 110, "MyName", "MyPassword") Then ' Long-run operation
    Set Msgs = objPOP3.RetrieveHeaders ' Long-run operation
    objPOP3.Disconnect ' Long-run operation
  End If
End Sub

Private Sub Form_Load()
    Set objPOP3 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
    If objPOP3 Is Nothing Then Exit Sub
    If objPOP3.Busy Then objPOP3.Abort ' Cancel POP3 session on exit
End Sub

See Also:

EnableEvents Property
Abort Method


ClientRequest Property

Contains last command string sent to the POP3 server by MailBee.

This property might be useful for debugging purposes (in conjunction with ServerResponse property).

Note: You may send your own commands to the POP3 server using SendCommand method.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
ElseIf Mailer.ErrCode > 200 Then ' POP3-specific error, i.e. not connection error
  MsgBox "Last command sent: " & Mailer.ClientRequest
  MsgBox "Server responded: " & Mailer.ServerResponse
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ServerResponse Property
SendCommand Method


Connected Property

Indicates whether MailBee.POP3 object is connected to POP3 server

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Connect Method


EnableEvents Property

MailBee.POP3 object is capable of background processing, so the program's user interface does not hang, and responds to Windows events - this is called "Async mode".

Also, MailBee.POP3 object can fire events itself during long-run operations such as receiving message or headers - this is called "Event firing".

When events are turned on, you can abort current operation by calling POP3.Abort method (for example, in CommandClick Sub of Cancel button) or by setting Proceed=False in POP3 event handler (OnReceiveStart, OnReceiveProgress, etc).

By default events are turned off because their usage slightly reduces performance. Set EnableEvents to True to enable events. You can then disable them by turning EnableEvents back to False.

Order of firing POP3 events is as following:

  • OnReceiveStart
  • OnReceiveProgress (can be fired multiple times for the same message)
  • OnReceiveComplete
  • OnMessageComplete
Note: To use events firing in VB, you also need to check MailBee type library in Project/References and create MailBee.POP3 object using "WithEvents" syntax (see an example below). To enable Async mode only, it's enough to set EnableEvents=True (WithEvents syntax is not necessarily required).

Value Type: | Boolean
Parameters: | None
Remarks: | Events are useful in event-driven environments only (such as VB, VBA, Delphi, etc). ASP pages cannot handle events

Usage example:

Option Explicit
Dim WithEvents objPOP3 As MailBee.POP3

Private Sub Form_Load()
  Dim Msgs As MailBee.Messages
  Set objPOP3 = New MailBee.POP3
  objPOP3.LicenseKey = "put your license key here"
  objPOP3.EnableEvents = True
  If objPOP3.Connect ("mailserver.com", 110, "MyName", "MyPassword") Then
    Set Msgs = objPOP3.RetrieveHeaders
    objPOP3.Disconnect
  End If
End Sub

Private Sub objPOP3_OnMessageComplete(ByVal Index As Long, Proceed As Boolean)
  MsgBox "Message " & Index & " done"
End Sub

See Also:

Abort Method
OnReceiveStart Event
OnReceiveProgress Event
OnReceiveComplete Event
OnMessageComplete Event


EnableLogging Property

Set EnableLogging to True to enable logging POP3 session into log file.

By default logging is turned off because it slightly reduces performance. Logging is recommeneded for debug purposes only.

Value Type: | Boolean
Parameters: | None
Remarks: | You can enable logging on even before assigning license key (for example, to determine how many days of trial period have gone up to date)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

ClearLog Method
LogFilePath Property


ErrCode Property

Returns completion status of the last operation. This is an extended version of the IsError property. To get string version, use ErrDesc property.

The list of possible values is as follows (codes 0 - 14 are common for POP3, SMTP and IMAP4 objects, codes 2xx are specific to POP3 object):

  • 0 - No Error
  • 1 - Not connected
  • 2 - Already connected
  • 3 - Remote host not resolved
  • 4 - Connection failed (server not found)
  • 5 - Timeout occurred (No response from the server during the interval specified by Timeout property value)
  • 6 - Connection suddenly closed by the server (many servers close connection if the client has no activity for a while. Periodically calling Ping method, the developer can avoid this)
  • 7 - Connection aborted by client side (due to call of POP3.Abort method)
  • 8 - Other connection-related errors
  • 11 - SSL STARTTLS not supported. SSL connection over regular port is not supported by the server
  • 12 - SSL Init failed. See SSLError property of SSL object for details
  • 13 - SSL Encrypt failed
  • 14 - SSL Decrypt failed
  • 201 - Not licensed (LicenseKey is not assigned, invalid, or expired)
  • 202 - Operation cancelled (If Proceed value in event handlers (OnReceiveProgress, etc.) is set to False)
  • 203 - Wrong parameter value (for example, attempt to receive message with index 5, if only 4 emails are in mailbox)
  • 211 - Selected authentication method is not supported by the server
  • 212 - Selected authentication method failed for unknown reason (should never occur, please contact Technical Support Team if you encounter such error)
  • 213 - Wrong UserName and/or Password. Authentication failed
  • 214 - connection established, but message count is not available
  • 215 - connection established, but messages' sizes are not available
  • 216 - other command failure

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.IsError Then MsgBox "ErrCode = " & Mailer.ErrCode
Mailer.Disconnect

See Also:

IsError Property
ErrDesc Property
Ping Method
Abort Method


ErrDesc Property

Contains error description. This property is meaningful only if IsError is True.

To get numeric error code, use ErrCode property.

Enable logging on and check log file to get detailed error description.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

IsError Property
ErrCode Property
EnableLogging Property
LogFilePath Property


IsError Property

True if last called MailBee.POP3 method completed with errors. Use ErrDesc or ErrCode properties to get error information.

Also, enable logging on and check log file to get detailed error description.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ErrDesc Property
ErrCode Property
EnableLogging Property
LogFilePath Property


Licensed Property

True if MailBee.POP3 object can be used. This means correct LicenseKey has been assigned, and trial period is not yet expired or registered version is used.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Licensed Then
  MsgBox "POP3 object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

LicenseKey Property
ErrDesc Property
EnableLogging Property
LogFilePath Property


LicenseKey Property

License Key of your copy of MailBee.POP3 component.

This property must be set to correct value in order to successfully run MailBee.POP3 object. When Connect method is called, it checks LicenseKey first. If LicenseKey is invalid or expired, connection to POP3 server is aborted.

Value Type: | String
Parameters: | None
Remarks: | This property is write-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Licensed Then
  MsgBox "POP3 object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Licensed Property
ErrDesc Property
EnableLogging Property
LogFilePath Property


LogFilePath Property

The path to the log file. LogFilePath is meaningful only if EnableLogging property is set to True.

Default value is "pop3_log.txt"

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Licensed Then
  MsgBox "POP3 object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ClearLog Method
EnableLogging Property


MessageCount Property

Returns total number of the messages in the currently opened mailbox.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  MsgBox Mailer.MessageCount & " message(s) in mailbox"
  Mailer.Disconnect
End If

See Also:

Messages.Count Property


Password Property

The password of the user account on the mail server.

To avoid sending password as clear text, set AuthMethod=1. This will enable secure APOP authentication. However, some POP3 servers might not support it. See AuthMethod property reference for details.

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.AuthMethod = 1 ' Using APOP secure authentication
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected using APOP command"
  Mailer.Disconnect
End If

See Also:

UserName Property
AuthMethod Property
ServerName Property
Connect Method


PortNumber Property

POP3 port number. Default value is 110.

Note: Usually you do not need to change POP3 port number. However, if you do, set this value BEFORE calling Connect method.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.PortNumber = 1234 ' If  mailserver.com operates on non-standard port
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

UserName Property
Password Property
AuthMethod Property
ServerName Property
Connect Method


ServerName Property

POP3 server address (like "mail.server.com"), or IP-address (like "123.456.789.123").

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

UserName Property
Password Property
AuthMethod Property
Connect Method


ServerResponse Property

Returns last reply of POP3 server. This reply is returned as a result of last command sent to the server (the text of this command is available through ClientRequest property value). Be aware that ServerResponse string is sometimes as big as message size (for example, when using RetrieveSingleMessage or RetrieveMessages methods).

Use this property if you need exact knowledge of what server reply is. For example, if user authentication failed even if UserName and Password were correct and network connection was stable, you may check this property to determine why POP3 server rejected the connection. Logging feature is also helpful for debugging purposes (EnableLogging property).

In the rest of cases Licensed/ErrDesc/ErrCode/IsError properties would be enough for organizing error-handling mechanism.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
ElseIf Mailer.ErrCode > 200 Then ' POP3-specific error, i.e. not connection error
  MsgBox "Server responded: " & Mailer.ServerResponse
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ClientRequest Property
Licensed Property
IsError Property
ErrCode Property
ErrDesc Property
EnableLogging Property
LogFilePath Property


Size Property

Size of particular message in e-mail account.

This property allows you to determine messages' sizes even before retrieving message headers because messages' sizes information is retrieved immediately after connection has been established.

Value Type: | Long
Parameters: |
Index As Long | Index of the message to get size for. Allowed range is: 1 <= Index <= POP3.MessageCount
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    MsgBox "First message size = " & Mailer.Size(1) & " bytes"
  End If
  Mailer.Disconnect
End If

See Also:

TotalSize Property
MessageCount Property


SSL Property

Specifies the SSL object that will be used for managing secure SSL/TLS connections.

If SSL.Enabled is True, then POP3 object will operate in secure mode through SSL/TLS connection.

Note: Many mail servers do not support secure connections.

Value Type: | MailBee.SSL
Parameters: | None

Usage example:

Dim Mailer, Messages, MessageHeader
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\pop3_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over dedicated port
Mailer.SSL.Enabled = True
Mailer.PortNumber = 995

Mailer.ServerName = "mail.server.com"
Mailer.UserName = "username"
Mailer.Pasword = "password"
If Mailer.Connect Then
  Set Messages = Mailer.RetrieveHeaders
  For Each MessageHeader In Messages
    MsgBox MessageHeader.Subject
  Next
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

SSL Object


TargetName Property

The service principal name (SPN) of the POP3 server.

This value can only be used with Kerberos authentication. If an empty string, it's autodetected as "POP3/<server name>" (which is suitable in most cases).

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "pop.host.com"
Mailer.TargetName = "POP/host.com"
Mailer.AuthMethod = 5 ' Authenticate with Kerberos
Mailer.UserName = "bill"
Mailer.Password = "bill's password"
Mailer.Connect ' Connect to bill@host.com account
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Password Property
AuthMethod Property
ServerName Property
Connect Method


Timeout Property

Specifies timeout value (the maximum amount of time to wait for response from POP3 server before returning an error) in seconds.

Default is 30 sec.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.Timeout = 60 ' 1 min
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

UserName Property
Password Property
AuthMethod Property
Connect Method


TotalSize Property

Total size of all messages in currently opened mailbox (in bytes).

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  MsgBox "Total size of all messages = " & Mailer.TotalSize & " bytes"
  Mailer.Disconnect
End If

See Also:

Size Property


UserDomain Property

The name of the user domain on the POP3 server.

This value can only be used with MS-specific authentication methods like NTLM and GSSAPI.

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "pop.company.com"
Mailer.AuthMethod = 2 ' Use NTLM authentication
Mailer.UserDomain = "company.com"
Mailer.UserName = "bill"
Mailer.Password = "bill's password"
Mailer.Connect ' Connect to bill@company.com account
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Password Property
AuthMethod Property
ServerName Property
Connect Method


UserName Property

The name of the user account on the POP3 server.

Usually this is the first part of the email address (e.g. "bill" for "bill@host.com"). Sometimes, however, it can be full email address or something else (it depends on POP3 account settings).

This can be left an empty string if you're using Integrated Windows Authentication. See AuthMethod property for details.

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "pop.host.com"
Mailer.UserName = "bill"
Mailer.Password = "bill's password"
Mailer.Connect ' Connect to bill@host.com account
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Password Property
AuthMethod Property
ServerName Property
Connect Method


Abort Method

Aborts currently performed long-run operation and immediately disconnects from the POP3 server. If no long-run operation is currently performed, the method does nothing.

Long-run operation is any action which causes data exchange with the POP3 server. Connecting to the server, retrieving messages or headers, graceful disconnecting, etc. are all long-run operations.

To determine whether long-run operation is currently performing, examine Busy property value.

When long-run operation is aborted, rough disconnection procedure takes place (not graceful one) so "QUIT" POP3 command is not executed. This means that if there are some messages marked for deletion, they will NOT be deleted.

Once the connection is aborted, ErrCode property of POP3 object is set to value of 7 (Connection aborted by client side).

Note: Abort method can be called only if POP3.EnableEvents=True (Async mode is on). Calling Abort method does not immediately closes the connection, it just notifies POP3 object to close it. Closing itself occures after millisecond or so after calling Abort method. This is a specificity of Async mode operation.

blnResult = ObjectName.Abort
Parameters: | None
Return value As Boolean | True if successful, False if error has occurred (nothing to abort because there is no long-run operation in progress)

Usage example:

Option Explicit
Dim objPOP3 As Object

Private Sub Command1_Click()
  Dim Msgs As Object
  Set objPOP3 = CreateObject("MailBee.POP3")
  objPOP3.LicenseKey = "put your license key here"
  objPOP3.EnableEvents = True ' Enable asynchronous mode
  If objPOP3.Connect("mailserver.com", 110, "MyName", "MyPassword") Then ' Long-run operation
    Set Msgs = objPOP3.RetrieveHeaders ' Long-run operation
    objPOP3.Disconnect ' Long-run operation
  End If
End Sub

Private Sub Form_Load()
    Set objPOP3 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
    If objPOP3 Is Nothing Then Exit Sub
    If objPOP3.Busy Then objPOP3.Abort ' Cancel POP3 session on exit
End Sub

See Also:

Busy Property
EnableEvents Property
ErrCode Property


ClearLog Method

Clears log file (if logging is on).

Consider calling this method each time your application starts or enters new cycle of processing. Otherwise, log file will increase in size with every POP3 session.

blnResult = ObjectName.ClearLog
Parameters: | None
Return value As Boolean | True if successful, False if logging is off or error occurred (path denoted by LogFilePath property is not accessible, file is locked, etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

See Also:

EnableLogging Property
LogFilePath Property


Connect Method

Connects to the POP3 server and logs in the specified user account.

Make sure to set the following properties before calling this method:

  • LicenseKey
  • ServerName
  • UserName
  • Password
If you want to use secure authentication and/or non-standard POP3 port, also set AuthMethod and/or PortNumber properties before calling Connect method.

If you're using Integrated Windows Authentication (IWA), you may leave UserName and Password blank but must set AuthMethod property to use IWA-compatible authentication method.

It's not required to call this method in order to connect to POP3 server (though it's recommended). Methods of POP3 object (such as RetrieveMessages, RetrieveHeaders, DeleteMessage, Ping, etc.) automatically call it if the connection is not established.

Note: You may quickly set values of ServerName, PortNumber, UserName, Password, UserDomain, TargetName properties by specifying them as parameters of Connect method.

blnResult = ObjectName.Connect([ServerName], [PortNumber], [UserName], [Password], [UserDomain], [TargetName])
Parameters: |
ServerName As String | (optional) If specified, will set POP3.ServerName property with new value
PortNumber As Long | (optional) If specified, will set POP3.PortNumber property with new value
UserName As String | (optional) If specified, will set POP3.UserName property with new value
Password As String | (optional) If specified, will set POP3.Password property with new value
UserDomain As String | (optional) The user domain name (only used with NTLM and Kerberos). If not specified, current UserDomain value will be used
TargetName As String | (optional) The SPN (only used with Kerberos). If not specified, current TargetName value will be used
Return value As Boolean | True if successful, False if connect procedure failed (mail server is not responding, username and/or password is incorrect, authentication method is not supported, license key is invalid). You can check ErrDesc property or log file to get more detailed error information

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
' Connect using default (110) PortNumber
If Mailer.Connect("mailserver.com", ,"MyName", "MyPassword") Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ServerName Property
PortNumber Property
UserName Property
Password Property
AuthMethod Property
Disconnect Method


DeleteMessage Method

Marks specified message for deletion.

It is not required to retrieve message or its headers prior to deleting. You can start deleting messages as soon as you have connected to POP3 server. However, you must gracefully disconnect. When you call DeleteMessage, the POP3 server remembers that you want to delete a message. The message actually gets deleted upon QUIT command which is sent by Disconnect method. If the connection was aborted for some reason, this won't occur and marking for deletion will be discarded.

Note that in Gmail you may not see any effect of messages deletion via POP3. Go to Gmail POP settings to configure this.

blnResult = ObjectName.DeleteMessage(Index)
Parameters: |
Index As Long | Index of the message to be deleted. Allowed range is: 1 <= Index <= POP3.MessageCount
Return value As Boolean | True if successful, False if error occurred (Index is out of range, connection failure, etc.)
Remarks: | This method just marks the message for deletion. Messages will be deleted later, after calling Disconnect method (this is peculiarity of POP3 protocol). That's why marking the message for deletion does not decrement MessageCount property.

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Mailer.DeleteMessage 1
  End If
  Mailer.Disconnect
End If

See Also:

MessageCount Property
Disconnect Method


Disconnect Method

Disconnects from the POP3 server.

It is not necessary (though it's recommended) to call this method. The POP3 object automatically disconnects from the POP3 server when the object is to be freed.

blnResult = ObjectName.Disconnect
Parameters: | None
Return value As Boolean | True if successful, False if disconnect procedure failed (was not connected, mail server is not responding). You can check ErrDesc property or log file to get more detailed error information
Remarks: | Even if this method failed, connection will be closed anyway. This means that Connected property will be always False after calling Disconnect method. However, only if connection was closed gracefully (Disconnect method returned True), messages marked for deletion by DeleteMessage will be really deleted

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect ("mailserver.com", 110, "MyName", "MyPassword")
  If Mailer.Disconnect Then
    MsgBox "Connection gracefully closed"
  Else
    MsgBox "Connection aborted"
  End If
End If

See Also:

Connect Method
DeleteMessage Method


GetLastReceivedDataChunk Method

Gets the last received data block of the server's response as a string.

Typically, you'll use this method in OnReceiveProgress event handler to monitor the data being received during the connection. Typically, 5-60KB data portion is returned per call. For instance, if you're downloading 1MB e-mail, OnReceiveProgress event will fire about 30-200 times as the overall data is split in 30-200 chunks.

The method should be called once per a single triggering of OnReceiveProgress event.

strData = ObjectName.GetLastReceivedDataChunk()
Parameters: | None
Return value As String | Data portion received with the last read data operation.

Usage example:

Option Explicit
Dim WithEvents objPOP3 As MailBee.POP3

Private Sub Form_Load()
  Dim Msg As MailBee.Message
  Set objPOP3 = New MailBee.POP3
  objPOP3.LicenseKey = "put your license key here"
  objPOP3.EnableEvents = True
  If objPOP3.Connect ("mailserver.com", 110, "MyName", "MyPassword") Then
    If objPOP3.MessageCount > 0 Then
      Set Msg = objPOP3.RetrieveSingleMessage(1)
    End If
    objPOP3.Disconnect
  End If
End Sub

Private Sub objPOP3_OnReceiveProgress(ByVal Index As Long, ByVal TotalBytesReceived As Long, Proceed As Boolean)
  Debug.Print objPOP3.GetLastReceivedDataChunk
End Sub

See Also:

OnReceiveProgress Event


GetMessageNumberFromUID Method

Returns the ordinal position of a message given its Unique-ID.

To get the list of all UIDs in the mailbox, use Search method.

lngMessageNumber = ObjectName.GetMessageNumberFromUID(UID)
Parameters: | None
UID As String | Unique-ID of a message to return message number for
Return value As Long | If successful, ordinal position of given message in the mailbox (starting from 1). If given Unique-ID is not found, return value is 0. If error occurs, return value is -1.

Usage example:

Dim Mailer, strUID
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 110, "MyName", "MyPassword") Then
  If Mailer.MessageCount > 0 Then

    ' Get Unique-ID of the message #1
    strUID = Mailer.GetMessageUID(1)

    ' Get and display message number of the message
    ' with given Unique-ID.
    ' Should display "1".
    MsgBox Mailer.GetMessageNumberFromUID(strUID)
  End If
  Mailer.Disconnect
End If

See Also:

GetMessageUID Method
Search Method


GetMessageUID Method

Returns Unique-ID (UID) value for a message.

To get the list of all UIDs in the mailbox, use Search method.

strUID = ObjectName.GetMessageUID(MessageNumber)
Parameters: | None
MessageNumber As Long | Ordinal position of the message in the mailbox
Return value As String | If successful, Unique-ID of the message. If an error occurs, empty string will be returned (check ErrCode property for exact error reason).

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 110, "MyName", "MyPassword") Then
  If Mailer.MessageCount > 0 Then
    ' Display Unique-ID of the first message
    MsgBox Mailer.GetMessageUID(1)
  End If
  Mailer.Disconnect
End If

See Also:

GetMessageNumberFromUID Method
Search Method


Ping Method

Sends "noop" command to POP3 server.

You may use this method to keep connection with POP3 server alive.

blnResult = ObjectName.Ping
Parameters: | None
Return value As Boolean | True if successful, False if error occurred (usually connection failure)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  ' Start doing some long-lasting job here
  Mailer.Ping ' Call Ping to remind the server about us
  ' Continue long-lasting job
  Mailer.Disconnect
End If

See Also:

POP3 Object


RetrieveHeaders Method

Retrieves headers for the specified range or for all messages in the e-mail account. You can also specify partial downloading of messages' bodies (for message preview purposes).

No messages are deleted by this method.

To retrieve headers for a single message, use RetrieveSingleMessageHeaders method.

Note that in Gmail you may not receive via POP3 all messages which you see in the web interface. Go to Gmail POP settings to configure this.

objMessages = ObjectName.RetrieveHeaders([First], [Last], [BodyLinesCount])
Parameters: |
First | (optional) The first index in the range to download. Default is 1.
Last | (optional) The last index in the range to download. Default is -1 which denotes the last message in the inbox (POP3.MessageCount).
BodyLinesCount As Long | (optional) Number of body lines to download for each message. Default value is 0 (i.e. only header lines are downloaded). You can specify value greater than actual lines number in particular message - in this case RetrieveHeaders method will just return full message (as if RetrieveMessages method was executed for this message)
Return value As Messages | Messages collection of Message objects where each object stores all header information (and, optionally, downloaded body part). If error occurred, return value is Nothing.

Usage example:

Dim Mailer, Msgs, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  Set Msgs = Mailer.RetrieveHeaders(,,10) ' Download headers plus first 10 lines of body for all emails in inbox
  If Not Msgs Is Nothing Then
    For Each Msg In Msgs
      MsgBox "Subject: " & Msg.Subject
    Next
  End If
  Mailer.Disconnect
End If

See Also:

RetrieveSingleMessageHeaders Method
RetrieveSingleMessage Method
RetrieveMessages Method
Message Object
Messages Collection


RetrieveMessages Method

Retrieves all messages or the specified range of messages from the e-mail account.

No messages are deleted by this method.

To retrieve single message, use RetrieveSingleMessage method.

Note that in Gmail you may not receive via POP3 all messages which you see in the web interface. Go to Gmail POP settings to configure this.

objMessages = ObjectName.RetrieveMessages([First], [Last])
Parameters: |
First | (optional) The first index in the range to download. Default is 1.
Last | (optional) The last index in the range to download. Default is -1 which denotes the last message in the inbox (POP3.MessageCount).
Return value As Messages | Messages collection of Message objects where each object stores all message information. If error has occurred, return value is Nothing.

Usage example:

Dim Mailer, Msgs, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  Set Msgs = Mailer.RetrieveMessages
  If Not Msgs Is Nothing Then
    For Each Msg In Msgs
      MsgBox "Attachments count: " & Msg.Attachments.Count
    Next
  End If
  Mailer.Disconnect
End If

See Also:

RetrieveSingleMessageHeaders Method
RetrieveSingleMessage Method
RetrieveHeaders Method
Message Object
Messages Collection


RetrieveSingleMessage Method

Retrieves a message from the e-mail account.

No messages are deleted by this method.

To retrieve all messages, use RetrieveMessages method.

objMessage = ObjectName.RetrieveSingleMessage(Index)
Parameters: |
Index As Long | Index of the message to retrieve. Allowed range is: 1 <= Index <= POP3.MessageCount
Return value As Message | Message object filled with all message information. If error has occurred, return value is Nothing.

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      MsgBox "Body: " & Msg.BodyText
    End If
  End If
  Mailer.Disconnect
End If

See Also:

RetrieveSingleMessageHeaders Method
RetrieveHeaders Method
RetrieveMessages Method
Message Object


RetrieveSingleMessageHeaders Method

Retrieves headers for a particular message from the e-mail account. You can also specify partial downloading of message body (for message preview purposes).

No messages are deleted by this method.

To retrieve headers for all messages, use RetrieveHeaders method.

objMessage = ObjectName.RetrieveSingleMessageHeaders(Index, [BodyLinesCount])
Parameters: |
Index As Long | Index of the message to retrieve headers for. Allowed range is: 1 <= Index <= POP3.MessageCount
BodyLinesCount As Long | (optional) Number of body lines to download for the message. Default value is 0 (i.e. only header lines are downloaded). You can specify value greater than actual lines number in the message - in this case RetrieveSingleMessageHeaders method will just return full message (as if RetrieveSingleMessage method was executed for this message)
Return value As Message | Message object filled with all headers information (and, optionally, downloaded body part). If error has occurred, return value is Nothing.

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessageHeaders(1, 10) ' Also download first 10 lines of body
    If Not Msg Is Nothing Then
      MsgBox "Body preview: " & Msg.BodyText
    End If
  End If
  Mailer.Disconnect
End If

See Also:

RetrieveSingleMessage Method
RetrieveHeaders Method
RetrieveMessages Method
Message Object


Search Method

On success, retrieves UIDs (unique IDs) of all messages in currently opened mailbox. These IDs are returned as an array of strings. Lower bound of the array is 1 and upper bound is MessageCount.

On failure, returns Empty. In Visual Basic or ASP, you can use IsEmpty(Expression) function to handle this situation. Use ErrCode or ErrDesc properties to get detailed error description.

Don't confuse UID with MessageID. UID is a string which is unique for each message in the mailbox. MessageID is a message header (not a number) unique for each distinct message. However, if the same message is placed into mailbox twice, both copies will have the same MessageIDs but different UIDs.

UIDs are very useful for locating new messages because UIDs are retrieved MUCH FASTER then MessageIDs. For example, if you have database table where UIDs of existing messages are stored, it becomes very simple to determine that new messages have arrived. Just call Search method and then search returned values in the UIDs database table. If particular UID is not there, the message is new.

Often (but this depends on mail server implementation), UIDs returned by this method are the same UIDs that returned by Search method of IMAP4 object for "Inbox" folder. However, POP3 UIDs are returned as strings (which may or may not to be presented as numbers) while IMAP4 UIDs are always numbers.

Note: UID functionality is an extension to POP3 protocol, and implementations may vary from server to server (some servers might not support UID at all).

arrUIDs = ObjectName.Search
Parameters: | None
Return value As Variant | Array (1 to MessageCount) of Variant/String, each value is UID of the message. If error has occurred (connection error or UID functionality is not supported), return value is Empty

Usage example:

Dim Mailer, UIDs, I
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 110, "MyName", "MyPassword") Then
  UIDs = Mailer.Search ' Get UIDs
  If Not IsEmpty(UIDs) Then
    For I = LBound(UIDs) To UBound(UIDs)
      MsgBox "Message #" & I & " has UID: " & UIDs(I)
    Next
  End If
  Mailer.Disconnect
End If

See Also:

RetrieveHeaders Method
MessageCount Property

Message.MessageId Property

IMAP4.Search Method


SendCommand Method

Sends user-defined text to POP3 server.

You may use this method to send specific POP3 commands to the server. You must have some knowledge of POP3 protocol for using this method. Keep in mind the following considerations:

  • Most commands must end with CRLF pair (vbCrLf constant in Visual Basic and ASP)
  • POP3 server can produce positive response in different formats (single-line and multi-line). You must choose proper format for positive response using ExpectMultilineResponse parameter. The format is dependent on which command was issued. Most commands produce single-line response. RETR and TOP commands always produce multi-line response. LIST and UIDL commands produce multi-line response when used without parameters. If LIST or UDIL is called with a parameter, single-line response is returned
  • If the command failed, POP3 server returns negative response that is always single-line. ExpectMultilineResponse parameter does not affect this
  • To determine whether the command was successful, use IsError property of the POP3 object

strResult = ObjectName.SendCommand(Command)
Parameters: |
Command As String | Text to be sent. This text must be properly formatted POP3 command
ExpectMultilineResponse As Boolean | (optional) If True, it is expected POP3 server will reply with a multi-line positive response to the given command. Default is False
Return value As String | Response from POP3 server to the custom command

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Mailer.DeleteMessage 1 ' Mark the message for deletion
    Mailer.SendCommand "rset" & vbCrLf  ' Unmark messages marked for deletion
  End If
  Mailer.Disconnect
End If

See Also:

IsError Property


OnReceiveStart Event

Fires when POP3 object is going to start retrieving message or message headers.

Parameters: |
Index As Long | Index of the message being retrieved. Allowed range is: 1 <= Index <= POP3.MessageCount
ByRef Proceed As Boolean | Default value is True, which tells MailBee to start receiving message data. You can set it to False to immediately abort POP3 session and disconnect from POP3 server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objPOP3 As MailBee.POP3

Private Sub Form_Load()
  Dim Msgs As MailBee.Messages
  Set objPOP3 = New MailBee.POP3
  objPOP3.LicenseKey = "put your license key here"
  objPOP3.EnableEvents = True
  If objPOP3.Connect ("mailserver.com", 110, "MyName", "MyPassword") Then
    Set Msgs = objPOP3.RetrieveHeaders
    objPOP3.Disconnect
  End If
End Sub

Private Sub objPOP3_OnReceiveStart(ByVal Index As Long, Proceed As Boolean)
  ' Abort pop3 session if there are more than 100 messages in the mailbox
  If Index > 100 Then Proceed = False
End Sub

See Also:

EnableEvents Property
OnReceiveProgress Event
OnReceiveComplete Event
OnMessageComplete Event


OnReceiveProgress Event

Fires when POP3 object receives new chunk of message/headers data.

This event can be fired multiple times (because each chunk has limited length, usually not more than 50-60KB, while the message being downloaded can be of many megabytes in size).

Parameters: |
Index As Long | Index of the message being retrieved. Allowed range is: 1 <= Index <= POP3.MessageCount
TotalBytesReceived As Long | Total count of bytes already received for the current message
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue receiving message data. You can set it to False to immediately abort POP3 session and disconnect from POP3 server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objPOP3 As MailBee.POP3

Private Sub Form_Load()
  Dim Msg As MailBee.Message
  Set objPOP3 = New MailBee.POP3
  objPOP3.LicenseKey = "put your license key here"
  objPOP3.EnableEvents = True
  If objPOP3.Connect ("mailserver.com", 110, "MyName", "MyPassword") Then
    If objPOP3.MessageCount > 0 Then
      Set Msg = objPOP3.RetrieveSingleMessage(1)
    End If
    objPOP3.Disconnect
  End If
End Sub

Private Sub objPOP3_OnReceiveProgress(ByVal Index As Long, ByVal TotalBytesReceived As Long, Proceed As Boolean)
  If TotalBytesReceived > 10000 Then Proceed = False ' Abort pop3 session if message data too large
End Sub

See Also:

EnableEvents Property
OnReceiveStart Event
OnReceiveComplete Event
OnMessageComplete Event


OnReceiveComplete Event

Fires when POP3 object has received message data from POP3 server. After firing this event POP3 object will decode the message from MIME format.

Parameters: |
Index As Long | Index of the message being retrieved. Allowed range is: 1 <= Index <= POP3.MessageCount
ByRef Proceed As Boolean | Default value is True, which tells MailBee to start decoding message data. You can set it to False to immediately abort POP3 session and disconnect from POP3 server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objPOP3 As MailBee.POP3

Private Sub Form_Load()
  Dim Msgs As MailBee.Messages
  Set objPOP3 = New MailBee.POP3
  objPOP3.LicenseKey = "put your license key here"
  objPOP3.EnableEvents = True
  If objPOP3.Connect ("mailserver.com", 110, "MyName", "MyPassword") Then
    Set Msgs = objPOP3.RetrieveHeaders
    objPOP3.Disconnect
  End If
End Sub

Private Sub objPOP3_OnReceiveComplete(ByVal Index As Long, Proceed As Boolean)
  ' Abort pop3 session if there are more than 100 messages in the mailbox
  If Index > 100 Then Proceed = False
End Sub

See Also:

EnableEvents Property
OnReceiveStart Event
OnReceiveProgress Event
OnMessageComplete Event


OnMessageComplete Event

Fires when POP3 object has finished Message object creation. After firing this event POP3 object will return newly created Message object to the caller code (or in the case of RetrieveMessages and RetrieveHeaders methods POP3 object will start retrieving next message).

Parameters: |
Index As Long | Index of the message being retrieved. Allowed range is: 1 <= Index <= POP3.MessageCount
ByRef Proceed As Boolean | Default value is True, which tells MailBee to return Message object. You can set it to False to immediately abort POP3 session, disconnect from POP3 server and return Nothing
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
Dim WithEvents objPOP3 As MailBee.POP3

Private Sub Form_Load()
  Dim Msgs As MailBee.Messages
  Set objPOP3 = New MailBee.POP3
  objPOP3.LicenseKey = "put your license key here"
  objPOP3.EnableEvents = True
  If objPOP3.Connect ("mailserver.com", 110, "MyName", "MyPassword") Then
    Set Msgs = objPOP3.RetrieveHeaders
    objPOP3.Disconnect
  End If
End Sub

Private Sub objPOP3_OnMessageComplete(ByVal Index As Long, Proceed As Boolean)
  ' Abort pop3 session if there are more than 100 messages in the mailbox
  If Index > 100 Then Proceed = False
End Sub

See Also:

EnableEvents Property
OnReceiveStart Event
OnReceiveProgress Event
OnReceiveComplete Event


IMAP4 Object

You can use the IMAP4 object to establish the connection with the IMAP4 server, select and manage the IMAP4 mailboxes, examine and alter properties of the messages, search for messages that match a criteria, and download entire messages.

Another features of the IMAP4 object include secure authentication options (OAuth 2.0, NTLM, GSSAPI/Kerberos and others), Integrated Windows Authentication with no username/password specified, ability to execute user-supplied commands, upload messages to the server and copy messages between mailboxes, and more.

Note: By default, the IMAP4 object neither processes Windows events nor fires its own events. This ensures maximum performance in the server environment such as ASP, but causes the user interface of desktop applications to be not responsive. To enable event handling and firing, you can set EnableEvents property value to True.

Syntax

IMAP4.property|method

Properties
AuthMethod | Specifies the authentication method to use when logging in the IMAP4 mail account.
Busy | Indicates whether the IMAP4 object is in the progress of sending or receiving data.
ClientRequest | Returns the last command string sent to the IMAP4 server.
Connected | Indicates whether the IMAP4 session is active.
EnableEvents | Specifies whether the IMAP4 object will handle and fire events.
EnableLogging | Specifies whether the IMAP4 object must log the IMAP4 session into a file.
ErrCode | Completion status of the last command.
ErrDesc | Contains textual error description if the last command has completed with an error.
IsError | Indicates whether the last command has completed with errors.
Licensed | Indicates whether valid license key has been assigned to the IMAP4 object.
LicenseKey | Sets the license key to be used with the IMAP4 object.
LogFilePath | Sets filename of the IMAP4 session log file.
MessageCount | The total number of messages in the currently selected mailbox.
MessageSet | Specifies the sequence of ordinal message numbers or UIDs to be processed.
Password | The password of the user account on the IMAP4 server.
PortNumber | The port number of the IMAP4 service on the server. Defaults to 143.
QuotaUsage | Gets the size of the occupied space in the mailbox in kilobytes.
RecentCount | The number of recent messages in the currently selected mailbox.
Selected | Indicates whether a mailbox has been selected.
SendDelay | Gets or sets the delay in milliseconds between two successive requests to the IMAP server.
ServerName | The IMAP4 server name.
ServerResponse | Returns the string that contains the entire last reply from the IMAP4 server.
ServerStatusResponse | The string containing completion status part of the last reply from the IMAP4 server.
SmartParsing | Enables better error recovery from bad-formatted responses from some IMAP servers.
SSL | Provides access to the SSL settings.
TargetName | The SPN of the server (only used with Kerberos authentication).
Timeout | The timeout value in seconds.
UIDNext | Returns UIDNEXT value of the currently selected IMAP4 mailbox.
UIDPlusResult | Returns UIDPLUS result of the last IMAP4 command, such as APPEND, COPY, or MOVE.
UIDValidity | Returns UIDVALIDITY value of the currently selected IMAP4 mailbox.
Unseen | Gets the ordinal message number of the first unseen message in the currently selected mailbox.
UserDomain | The name of the user domain on the IMAP4 server (only used with MS specific authentication types like NTLM).
UserName | The name of the user account on the IMAP4 server.
UTF7EncodeMailboxNames | Tells MailBee whether to automatically encode IMAP mailbox names to UTF-7M when sending requests to the server.
Methods
Abort | Aborts current operation and immediately closes the IMAP4 session.
AppendMessage | Uploads a message to the specified mailbox.
ClearLog | Clears the IMAP4 session log file.
Connect | Connects to the IMAP4 server and logs in the user mail account.
CopyMessages | Copies specified messages from the currently selected mailbox to another mailbox.
CreateMailbox | Creates a mailbox in the user account on the IMAP4 server.
DeleteMailbox | Deletes specified mailbox from the user account.
DeleteMessages | Marks the specified message in the currently selected mailbox as "Deleted".
Disconnect | Disconnects from the IMAP4 server.
ExamineMailbox | Selects specified mailbox on the IMAP4 server for read-only access.
Expunge | Permanently removes all messages marked as "Deleted" from the currently selected mailbox.
ExpungeAndClose | Permanently removes all messages marked as "Deleted" and closes currently selected mailbox.
FromUTF7 | Decodes the specified UTF-7M string into regular string.
GetCapabilities | Gets the the list of capabilities of this server or checks if the specified capability is supported by this server.
GetLastReceivedDataChunk | Gets the data portion received from the server during last receive-data operation.
GetMailboxQuota | Retrieves the quota size for the mailbox or the entire mail account in kilobytes.
GetMailboxStatus | Retrieves some statistics for a mailbox (total and unseen message count, etc).
Idle | Receives status notifications from the server in IDLE mode.
MoveMessages | Moves specified messages from the currently selected mailbox to another mailbox (the server must support MOVE extension).
Ping | Sends NOOP command to the IMAP4 server.
RenameMailbox | Renames specified mailbox on the IMAP4 server.
RetrieveEnvelopes | Retrieves one or more message envelopes from the currently selected mailbox.
RetrieveEnvelopesEx | Retrieves message envelopes with extended information from the currently selected mailbox.
RetrieveMailboxes | Retrieves a list of mailboxes available in the user account on the IMAP4 server.
RetrieveMailboxesEx | Retrieves Mailboxes collection which contains those mailboxes of the IMAP4 account which meet the specified criteria. Supports XLIST, SPECIAL-USE, CHILDREN extensions and special folder flags like Sent or Drafts.
RetrieveMessagesSize | Retrieves total size in bytes of one or more messages in the currently selected mailbox.
RetrieveSingleMessage | Downloads entire message from the currently selected IMAP4 mailbox.
RetrieveSingleMessageHeaders | Downloads headers for the message from the currently selected IMAP4 mailbox.
RetrieveTotalSize | Retrieves total size in bytes of all messages in the currently selected mailbox.
Search | Searches the currently selected mailbox for messages that conform to specified criteria.
SelectMailbox | Selects specified mailbox on the IMAP4 server.
SendCommand | Executes user-supplied command on the IMAP4 server.
SetFlagsForMessage | Sets the flags for specified message in the currently selected mailbox.
SetFlagsForMessageAsString | Sets the flags for specified message in the currently selected mailbox, allowing for non-standard flags.
Subscribe | Subscribes specified mailbox.
ToUTF7 | Encodes the specified string into UTF-7M.
Unsubscribe | Unsubscribes specified mailbox.
Events
OnAlert | Fires when there is an [ALERT] message in the IMAP4 server response.
OnEnvelopeDownloaded | Fires when IMAP4 object parses an envelope (FETCH response) in the data received from the IMAP server.
OnIdle | Fires when another 10 millisecond period elapses during idling.
OnReceiveData | Fires when the IMAP4 object receives new chunk of data from the IMAP server.
OnStatusChange | Fires when mailbox status changes: new message has arrived, a message has been deleted, number of messages changes, and so on.

Remarks

During the development, it's recommended to enable logging the IMAP4 session into a file by setting EnableLogging and LogFilePath properties. The log file allows you to discover typical problems quickly and easily.

You can find more information on typical problems resolution in Troubleshooting section of the IMAP4 samples.

Example

The following example retrieves new messages from the user account on the IMAP4 server, and displays each retrieved message. The sample is presented separately in Visual Basic version and ASP version since they differ quite enough.

Note: For simplicity, the example neither handles errors nor logs the IMAP4 session into a file. Search for new messages sample provides the code for error-checking and logging the IMAP4 session.

[Visual Basic]
Dim objIMAP4, objMsg, arrNew, I

' Create IMAP4 object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  objIMAP4.SelectMailbox "Inbox"

  ' Get Unique-IDs of new messages
  arrNew = objIMAP4.Search(True, "new")

  ' Loop through new messages
  For I = LBound(arrNew) To UBound(arrNew)

    ' Completely retrieve message by its Unique-ID
    Set objMsg = objIMAP4.RetrieveSingleMessage(arrNew(I), True)

    ' Display the message
    MsgBox _
      "From: " & objMsg.FromAddr & vbCrLf & _
      "To: " & objMsg.ToAddr & vbCrLf & _
      "Subject: " & objMsg.Subject & vbCrLf & _
      "Date: " & objMsg.GetDateFromString(objMsg.Date) & vbCrLf & vbCrLf & _
      objMsg.BodyText
  Next

  ' Close the connection
  objIMAP4.Disconnect
End If

[ASP]
<%
Dim objIMAP4, objMsg, arrNew, I

' Create IMAP4 object
Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "username"
objIMAP4.Password = "password"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  objIMAP4.SelectMailbox "Inbox"

  ' Get Unique-IDs of new messages
  arrNew = objIMAP4.Search(True, "new")

  ' Loop through new messages
  For I = LBound(arrNew) To UBound(arrNew)

    ' Completely retrieve message by its Unique-ID
    Set objMsg = objIMAP4.RetrieveSingleMessage(arrNew(I), True)

    ' Display the message.
    ' We use Server.HTMLEncode to convert '<' and '>'
    ' characters which can disturb the output if they
    ' are contained in the message headers.
    Response.Write _
      "From: " & Server.HTMLEncode(objMsg.FromAddr) & "<br>" & _
      "To: " & Server.HTMLEncode(objMsg.ToAddr) & "<br>" & _
      "Subject: " & Server.HTMLEncode(objMsg.Subject) & "<br>" & _
      "Date: " & objMsg.GetDateFromString(objMsg.Date) & "<br><br>" & _
      objMsg.BodyText
  Next

  ' Close the connection
  objIMAP4.Disconnect
End If
%>

See Also

Envelope Object, Message Object, RetrieveEnvelopes Method

Send feedback to AfterLogic


AuthMethod Property

MailBee.IMAP4 object can establish connection with the IMAP4 server using various authentication types.

Default setting is a regular authentication. Most IMAP4 servers support it, but it is insecure if the connection itself is not secure. During regular authentication user password is sent to server in a plain-text form, so the password can be intercepted by a malicious person. In case if the connection is protected with SSL/TLS, this is not a problem.

However, MailBee also supports secure authentication methods and OAuth 2.0. All you need for using a secure connection is to set AuthMethod property value prior to connecting.

With OAuth 2.0, you need to have an access token which can be obtained from the mail service provider (this mechanism is unique for each particular provider). They can offer software libraries or other guidelines on how can get access tokens for their service. MailBee Objects ships with VBScript OAuth 2.0 sample for Gmail. You can find it in My Documents/MailBee Objects/Samples/OAuth2_VBScript folder.

Also, MailBee supports Integrated Windows Authentication (IWA) so you can use any of NTLM or GSSAPI methods specifying empty username. In this case, MailBee will automatically obtain the current user credentials from the operating system. This is widely used with Microsoft services like MS Exchange Server or IIS.

AuthMethod property must be set BEFORE calling Connect method, otherwise it will not take effect.

The following authentication method are allowed:

  • 0 - Regular (default value)
  • 1 - CRAM-MD5 command. Secure MD5-based authentication type, supported by many IMAP4 servers
  • 2 - NTLM authentication (sort of Secure Password Authentication - SPA). MS specific, supports IWA
  • 3 - MSN authentication (another name of SPA). MS specific, used very rarely
  • 4 - GSSAPI authentication with internal implementation via NTLM (MS specific, supports IWA)
  • 5 - GSSAPI authentication with internal implementation via Kerberos (MS specific, supports IWA)
  • 6 - XOAUTH2 authentication (OAuth 2.0)
  • 16 - do not authenticate, just connect. Can be used if you only need to get supported extensions or authentication methods (with GetCapabilities method)
UserDomain property is not used with regular or CRAM-MD5 authentication. TargetName is only used with GSSAPI/Kerberos.

Note: Particular IMAP4 server might not support some authentication types.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.AuthMethod = 1 ' Using CRAM-MD5 secure authentication
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected using CRAM-MD5 secure authentication"
  Mailer.Disconnect
End If

See Also:

Connect Method


Busy Property

Indicates whether IMAP4 object is performing long-run operation (such as connecting to the server or retrieving messages).

When IMAP4 object is busy, attempt to call any of its methods which exchange data with IMAP4 server will immediately exit. To cancel currently executing long-run operation, call Abort method.

Note: Busy property is useful on conditions that IMAP4 object operates in Async mode. See EnableEvents property description for details.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Option Explicit
Dim objIMAP4 As Object

Private Sub Command1_Click()
  Dim Envelopes As Object
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"
  objIMAP4.EnableEvents = True ' Enable asynchronous mode
  If objIMAP4.Connect("mailserver.com", 143, "MyName", "MyPassword") Then ' Long-run operation
    If objIMAP4.SelectMailbox("Inbox") Then ' Long-run operation
       Set Envelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False) ' Long-run operation
    End If
    objIMAP4.Disconnect ' Long-run operation
  End If
End Sub

Private Sub Form_Load()
    Set objIMAP4 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
    If objIMAP4 Is Nothing Then Exit Sub
    If objIMAP4.Busy Then objIMAP4.Abort ' Cancel IMAP4 session on exit
End Sub

See Also:

EnableEvents Property
Abort Method


ClientRequest Property

Returns last command string sent to the IMAP4 server by MailBee.

This property might be useful for debugging purposes (in conjunction with ServerResponse or ServerStatusResponse properties).

Note: You may send your own commands to the IMAP4 server using SendCommand method.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
ElseIf Mailer.ErrCode > 300 Then ' IMAP4-specific error, i.e. not connection error
  MsgBox "Last command sent: " & Mailer.ClientRequest
  MsgBox "Server reports: " & Mailer.ServerStatusResponse
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ServerResponse Property
ServerStatusResponse Property
SendCommand Method


Connected Property

Indicates whether MailBee.IMAP4 object is connected to the IMAP4 server

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.Connect
If Mailer.Connected Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Connect Method


EnableEvents Property

Enables or disables MailBee's ability to process Windows events and fire its own events during operations.

When EnableEvents property is set to True, MailBee allows your application to be responsive while MailBee is performing long-run operation (this is called "Async mode"). Also, MailBee can fire several types of events notifying your application about data receiving progress, status changes, or server alerts. This is convenient for Windows applications.

When EnableEvents property is set to False (default setting), MailBee does not process or fire any events and operates slightly faster. This mode fits well for server environments such as ASP.

When events are turned on, you can abort current operation by calling Abort method of IMAP4 object. Another way to do not proceed with current operation is to set Proceed=False in IMAP4 event handler (OnReceiveData, OnAlert, OnStatusChange).

While events are turned on and IMAP4 object is busy with some long-run operation, Busy property is True. This means any call of long-run methods of this IMAP4 object will immediately fail.

Note: To handle MailBee's events (OnReceiveData, OnAlert, OnStatusChange) in Visual Basic, make sure MailBee's type library is checked in "Project/References" menu and MailBee.IMAP4 object is created using "WithEvents" syntax (see sample code below). To handle only Windows events, it's enough to set EnableEvents=True ("WithEvents" syntax is not necessarily required).

Value Type: | Boolean
Parameters: | None
Remarks: | Events are useful in event-driven environments only (such as VB, VBA, Delphi, etc). ASP pages cannot handle events

Usage example:

Option Explicit
' Early binding and "WithEvents" syntax required for handling MailBee's events
Dim WithEvents objIMAP4 As MailBee.IMAP4

Private Sub Command1_Click()
  Dim Envelopes As MailBee.Envelopes
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"
  objIMAP4.EnableEvents = True ' Enable Async mode
  If objIMAP4.Connect("mailserver.com", 143, "MyName", "MyPassword") Then ' Long-run operation
    If objIMAP4.SelectMailbox("Inbox") Then ' Long-run operation
      Set Envelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False) ' Long-run operation
    End If
    objIMAP4.Disconnect ' Long-run operation
  End If
End Sub

' Respond to MailBee's OnReceiveData event and print how many data bytes received
Private Sub objIMAP4_OnReceiveData(ByVal BytesReceived As Long, Proceed As Boolean)
  Debug.Print BytesReceived & " bytes received"
End Sub

Private Sub Form_Load()
  Set objIMAP4 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If objIMAP4 Is Nothing Then Exit Sub
  If objIMAP4.Busy Then objIMAP4.Abort ' Cancel IMAP4 session on exit
End Sub

See Also:

Abort Method

Busy Property

OnAlert Event
OnReceiveData Event
OnStatusChange Event


EnableLogging Property

Set EnableLogging to True to enable logging IMAP4 session into log file.

By default logging is turned off because it slightly reduces performance. Logging is recommeneded for debug purposes only.

Value Type: | Boolean
Parameters: | None
Remarks: | You can enable logging on even before assigning license key (for example, to determine how many days of trial period have gone up to date)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

ClearLog Method
LogFilePath Property


ErrCode Property

Returns completion status of the last operation.

ErrCode is an extended numeric version of the IsError property. To get text message, use ErrDesc or ServerStatusResponse property.

The list of possible values is as follows (codes 0 - 14 are common for POP3, IMAP4 and SMTP objects, codes 3xx are specific to IMAP4 object):

  • 0 - No Error
  • 1 - Not connected
  • 2 - Already connected
  • 3 - Remote host not resolved
  • 4 - Connection failed (server not found)
  • 5 - Timeout occurred (No response from the server during the interval specified by Timeout property value)
  • 6 - Connection suddenly closed by the server (many servers close connection if the client has no activity for a while. Periodically calling Ping method, the developer can avoid this)
  • 7 - Connection aborted by client side (due to call of Abort method)
  • 8 - Other connection-related errors
  • 11 - SSL STARTTLS not supported. SSL connection over regular port is not supported by the server
  • 12 - SSL Init failed. See SSLError property of SSL object for details
  • 13 - SSL Encrypt failed
  • 14 - SSL Decrypt failed
  • 301 - Not licensed (LicenseKey is not assigned, invalid, or expired)
  • 302 - Operation cancelled by the user. This happens if Proceed parameter value was manually set to False in the event handlers (such as OnReceiveData)
  • 303 - Supplied UserName was empty
  • 304 - Authentication method selected is not supported by the server
  • 305 - No mailbox selected. The requested command requires selected mailbox to execute
  • 311 - IMAP4 server responded "BAD". See ServerStatusResponse property for details
  • 312 - IMAP4 server responded "NO". See ServerStatusResponse property for details
  • 313 - IMAP4 server responded with unknown reply
  • 314 - IMAP4 server responded with unexpected reply. Requested item was not found in the reply

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample tries to select non-existent mailbox and checks for errors
Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 143, "MyName", "MyPassword"
Mailer.SelectMailbox "Non-existent mailbox"
If Mailer.ErrCode > 0 Then
  MsgBox "ErrCode = " & Mailer.ErrCode
  MsgBox "ErrDesc = " & Mailer.ErrDesc
  If Mailer.ErrCode > 310 Then
    ' It seems the server returned error message for us
    MsgBox "Server responded: " & Mailer.ServerStatusResponse
  End If
End If
Mailer.Disconnect

See Also:

IsError Property
ErrDesc Property
ServerStatusResponse Property


ErrDesc Property

Contains textual description of the last error. This property is meaningful only if IsError is True.

To get numeric code of the error, use ErrCode property.

Also, you can enable logging on (using EnableLogging and LogFilePath properties) and check log file to get detailed error description.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

IsError Property
ErrCode Property
ServerStatusResponse Property

EnableLogging Property
LogFilePath Property


IsError Property

True if last called MailBee.IMAP4 method completed with errors. Use ErrDesc, ServerStatusResponse or ErrCode properties to get extended error information.

Also, enable logging on and check log file to get detailed error description.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ErrDesc Property
ErrCode Property
ServerStatusResponse Property

EnableLogging Property
LogFilePath Property


Licensed Property

True if MailBee.IMAP4 object can be used. This means correct LicenseKey has been assigned, and trial period is not yet expired or registered version is used.

To determine license status (is registered version used, number of days trial version will function yet) enable logging on and look into log file.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Enable logging and clear log file
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog

Mailer.LicenseKey = "put your license key here" ' Set license key

If Mailer.Licensed Then
  MsgBox "IMAP4 object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

LicenseKey Property
ErrCode Property
ErrDesc Property

EnableLogging Property
LogFilePath Property


LicenseKey Property

License key of your copy of MailBee.IMAP4 component.

If this property is not set to valid license key, IMAP4 object will not connect to IMAP4 server.

To determine whether supplied LicenseKey is valid, use Licensed property.

Value Type: | String
Parameters: | None
Remarks: | This property is write-only. Any attempt to read it will return empty string

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Licensed Then
  MsgBox "IMAP4 object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Licensed Property
ErrDesc Property

EnableLogging Property
LogFilePath Property


LogFilePath Property

The path to the log file. LogFilePath is meaningful only if EnableLogging property is set to True.

Default value is "imap4_log.txt"

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Licensed Then
  MsgBox "IMAP4 object is ready for use"
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ClearLog Method
EnableLogging Property


MessageCount Property

Contains total number of the messages in the currently selected mailbox.

Total number of the messages changes each time the messages are added to or removed from the mailbox. When it is possible that multiple users access the mailbox at the same time, you may periodically call Ping method to refresh MessageCount value.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample examines "Inbox" mailbox and displays total number of messages there

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.ExamineMailbox("Inbox") Then
    MsgBox Mailer.MessageCount & " messages in Inbox"
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

RecentCount Property

Ping Method


MessageSet Property

The sequence of ordinal message numbers or UIDs to be processed.

By default, all methods of this class which deal with messages, headers or envelopes take "First:Last" ranges as input parameters (RetrieveEnvelopes method is a typical example). However, you can set First parameter to -1 to let the method know that you want to process an arbitrary set of messages (IMAP4 protocol allows this). In this case, you specify the message set via this property.

Message set is a comma-separated list of message numbers or UIDs. Ranges are also allowed. Some valid examples: 568, 1-100, 5,6,8, 2-5,7,14,21-35,39. This property does not control if the values are message numbers or UIDs. You should specify this in AsUID parameter of the method for which you set this property (see the sample code below).

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'This sample shows Subjects of all unread emails, also doing some error checking
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
If Mailer.Connect Then
  If Mailer.SelectMailbox("Inbox") Then
    arrUIDs = Mailer.Search(True, "UNSEEN")
    Mailer.MessageSet = Join(arrUIDS, ",")
    If Mailer.MessageSet = "" Then
      MsgBox "No unread messages"
    Else
      Set Envelopes = Mailer.RetrieveEnvelopes(-1, -1, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          MsgBox Envelope.Subject
        Next
      Else
        MsgBox "Error #" & CStr(Mailer.ErrCode)
        If Mailer.ErrCode = 311 Or Mailer.ErrCode = 312 Then
          MsgBox Mailer.ServerStatusResponse
        End If
      End If
    End If
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

CopyMessages Method
DeleteMessages Method
MoveMessages Method
RetrieveEnvelopes Method
RetrieveEnvelopesEx Method
RetrieveMessagesSize Method
SetFlagsForMessage Method
SetFlagsForMessageAsString Method


Password Property

The password of the user account on the IMAP4 server.

This can be left an empty string if you're using Integrated Windows Authentication. See AuthMethod property for details.

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
If Mailer.Connect Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
  If Mailer.ErrCode > 310 Then MsgBox Mailer.ServerStatusResponse
End If

See Also:

UserName Property
ServerName Property

Connect Method


PortNumber Property

IMAP4 port number. Default value is 143.

Note: Usually you do not need to change IMAP4 port number. However, if you do, set this value BEFORE calling Connect method.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.PortNumber = 1234 ' If  mailserver.com operates on non-standard port
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
If Mailer.Connect Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

UserName Property
Password Property
ServerName Property

Connect Method


QuotaUsage Property

Gets the size of the occupied space in the mailbox in kilobytes (1024 bytes).

This property is set upon successful call of GetMailboxQuota method. If this method was never called, failed or the IMAP connection is closed, the property returns -1. This can also happen in the server does not support QUOTA capability or if the quota is not set for the given mailbox or account.

GetMailboxQuota method returns the maximum size allocated for the mailbox while this property returns the size of the actually occupied space.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays the quota limit and the used quota (in kilobytes) for the mail account
Dim Mailer, QuotaLimit
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  QuotaLimit = Mailer.GetMailboxQuota("")
  MsgBox Mailer.QuotaUsage & " of " & QuotaLimit & " kilobytes used"
  Mailer.Disconnect
End If

See Also:

RecentCount Property

GetMailboxQuota Method


RecentCount Property

Contains the number of the messages with "Recent" flag in the currently selected mailbox. Recent messages are ones that have not been viewed yet.

The number of recent messages changes each time the messages are read, added to or removed from the mailbox. When it is possible that multiple users access the mailbox at the same time, you may periodically call Ping method to refresh RecentCount value.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample examines "Inbox" mailbox and displays the number of recent messages there

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.ExamineMailbox("Inbox") Then
    MsgBox Mailer.RecentCount & " recent messages in Inbox"
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

MessageCount Property

Ping Method


Selected Property

Indicates whether IMAP4 object has already selected a mailbox on the IMAP4 server.

Many IMAP4 operations require selected mailbox in order to be successfully run.

Use SelectMailbox or ExamineMailbox method to select a mailbox on the IMAP4 server.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Mailer.SelectMailbox("Inbox")
  If Mailer.Selected Then
    MsgBox "Inbox selected"
  End If
  Mailer.Disconnect
End If

See Also:

ExamineMailbox Method
SelectMailbox Method


SendDelay Property

Gets or sets the delay in milliseconds between two successive requests to the IMAP server.

This is advanced property. Use it when working with certain slow IMAP4 servers which cannot handle commands from MailBee as fast as MailBee generates them.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
' Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.IMAP4")
' In ASP use Response.Write instead of MsgBox

' Start logging of all the events. You may try to modify SendDelay value
' and compare times when commands are issued to mail server.
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.SendDelay = 1000
If Mailer.Connect Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

IMAP4 Object


ServerName Property

The name ("mail.server.com") or IP-address ("123.456.789.123") of the IMAP4 server.

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
If Mailer.Connect Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Password Property
UserName Property

Connect Method


ServerResponse Property

Returns the last reply of the IMAP4 server.

This reply is returned as a result of last command sent to the server (the text of this command is available through ClientRequest property value).

Be aware that ServerResponse string can be very large. Usually the only thing needed is server status message (such as "OK Accepted" or "NO Password is incorrect"). To get status message, examine ServerStatusResponse property.

Use this property if you need exact knowledge of what server reply is. For example, if user authentication failed even if UserName and Password were correct and network connection was stable, you may check this property to determine why the IMAP4 server rejected the connection.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
ElseIf Mailer.ErrCode > 300 Then ' IMAP4-specific error, i.e. not connection error
  MsgBox "Server responded: " & Mailer.ServerResponse
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ClientRequest Property
ServerStatusResponse Property


ServerStatusResponse Property

Contains status message which indicates the result of the last operation.

This message is returned by the IMAP4 server. It contains human-readable text such as "BAD Invalid command", "OK logged", "NO Mailbox doesn't exist".

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "Wrong password"
Mailer.Connect
If Not Mailer.IsError Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
ElseIf Mailer.ErrCode > 300 Then ' IMAP4-specific error, i.e. not connection error
  MsgBox Mailer.ServerStatusResponse
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ClientRequest Property
ServerResponse Property


SmartParsing Property

Enables or disables MailBee's ability to better handle incorrect responses from IMAP servers which are not fully standards-compliant.

When SmartParsing property is set to True, MailBee performs some additional checks when parsing data from the server and sends data to the server in blocks of smaller size (in the case of APPEND command). This slightly reduces performance ut allows MailBee to tolerate many not-well written mail servers. Default is False. Setting this property to True can be used for troubleshooting.

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
Mailer.SmartParsing = True ' Make it easier for not well written smail server to accept the message being uploaded
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then

  ' Upload message from mail.eml file keeping defaults for datetime and flags
  If Mailer.AppendMessage("Inbox", "C:\mail.eml", , , 1) Then
    MsgBox "Message uploaded successfully"
  End If

  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Troubleshooting


SSL Property

Specifies the SSL object that will be used for managing secure SSL/TLS connections.

If SSL.Enabled is True, then IMAP4 object will operate in secure mode through SSL/TLS connection.

Note: Many mail servers do not support secure connections.

Value Type: | MailBee.SSL
Parameters: | None

Usage example:

Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over dedicated port
Mailer.SSL.Enabled = True
Mailer.PortNumber = 993

Mailer.ServerName = "mail.server.com"
Mailer.UserName = "username"
Mailer.Pasword = "password"
If Mailer.Connect Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes
    For Each Envelope In Envelopes
      MsgBox Envelope.Subject
    Next
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

SSL Object


TargetName Property

The service principal name (SPN) of the IMAP4 server.

This value can only be used with Kerberos authentication. If an empty string, it's autodetected as "IMAP/<server name>" (which is suitable in most cases).

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "imap.host.com"
Mailer.TargetName = "IMAP4/host.com"
Mailer.AuthMethod = 5 ' Authenticate with Kerberos
Mailer.UserName = "bill"
Mailer.Password = "bill's password"
If Mailer.Connect Then ' Connect to bill@host.com account
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Connect Method

Password Property
ServerName Property


Timeout Property

Specifies timeout value (the maximum amount of time to wait for response from the IMAP4 server before returning an error) in seconds.

Default is 30 sec.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mailserver.com"
Mailer.UserName = "MyName"
Mailer.Password = "MyPassword"
Mailer.Timeout = 5 ' 5 seconds
If Mailer.Connect Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

IMAP4 Object


UIDNext Property

Gets the UID to be assigned to the next message in the currently selected mailbox.

A 32-bit positive value containing the UIDNEXT of the currently selected mailbox, or 0 if it's not available or no mailbox is selected.

This value, if available, allows the application to predict the UID value that will be assigned to a new message in the mailbox.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only.

Usage example:

' This sample writes the UIDVALIDITY value of the 'Inbox' mailbox

Dim Mailer
' Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.IMAP4")
' In ASP use Response.Write instead of MsgBox

' Start logging of all the events
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
   ' Select necessary mailbox first
   If Mailer.SelectMailbox("Inbox") Then
      MsgBox "UIDNEXT = " & Mailer.UIDNext
   Else
      MsgBox "Error."
   End If
   Mailer.Disconnect
Else
   MsgBox "Unable to connect."
End If

See Also:

Selected Property | SelectMailbox Method | IMAP4 Object


UIDPlusResult Property

Gets the APPENDUID or COPYUID value of the last response from the IMAP4 server.

It's a string containing two space-separated values, like "83452345 129" or "345849 91:93" or "942378 5,9,12:16". The first value is the new value of UIDVALIDITY of the destination mailbox. The second value is the UID or a set of UIDs in IMAP4 message set format. The second value denotes the UID or UIDs assigned to the resulting messages in the destination mailbox (uploaded, copied or moved to that mailbox).

This value is only available if the IMAP4 server supports UIDPLUS extension (you can use GetCapabilities method to check this). If it does, the commands like APPEND, COPY and MOVE will set this value if the operation succeeded.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only.

Usage example:

' This sample copies the last message in Inbox into Sent folder (it must exist in the account).
' Then it gets UIDPLUS result and extracts the last value from it which denotes the UID assigned to the copied message in Sent folder.

Dim Mailer, Values, AssignedUID
' Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.IMAP4")
' In ASP use Response.Write instead of MsgBox

' Logging is not necessary but useful for troubleshooting
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
   ' Select the source mailbox first
   If Mailer.SelectMailbox("Inbox") Then
      If Mailer.CopyMessages("Sent", Mailer.MessageCount, Mailer.MessageCount, False) Then
        ' This is how you can extract second (the last) value from UIDPlusResult string.
        Values = Split(IMAP.UIDPlusResult)
        If (UBound(Values) > LBound(Values)) Then
          AssignedUID = Values(UBound(Values))
          MsgBox "Assigned UID=" & AssignedUID
        End If
      End If
   Else
      MsgBox "Error."
   End If
   Mailer.Disconnect
Else
   MsgBox "Unable to connect."
End If

See Also:

AppendMessage Method | CopyMessages Method | MoveMessages Method | IMAP4 Object


UIDValidity Property

Returns UIDVALIDITY value of the currently selected IMAP4 mailbox (see IMAP4 RFC for details).

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only.

Usage example:

' This sample writes the UIDVALIDITY value of the 'Inbox' mailbox

Dim Mailer
' Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.IMAP4")
' In ASP use Response.Write instead of MsgBox

' Start logging of all the events
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
   ' Select necessary mailbox first
   If Mailer.SelectMailbox("Inbox") Then
      MsgBox "UIDVALIDITY = " & Mailer.UIDValidity
   Else
      MsgBox "Error."
   End If
   Mailer.Disconnect
Else
   MsgBox "Unable to connect."
End If

See Also:

Selected Property | SelectMailbox Method | IMAP4 Object


Unseen Property

Gets the ordinal message number (in 1 : MessageCount range) of the first unseen message in the currently selected mailbox.

If you rather need to get the count of unseen messages (not the position of the first such message), either call IMAP.Search(False, "UNSEEN") in the currently selected mailbox or IMAP.GetMailboxStatus(MailboxName) in case if you need this for other mailboxes (not necessarily selected).

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample examines "Inbox" mailbox and displays the ordinal message number of the first unseen message

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.ExamineMailbox("Inbox") Then
    MsgBox Mailer.Unseen & " is the first unread message"
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

RecentCount Property

Search Method


UserDomain Property

The name of the user domain on the IMAP4 server.

This value can only be used with MS-specific authentication methods like NTLM and GSSAPI. The default value is an empty string (which is suitable in most cases).

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "imap.company.com"
Mailer.UserDomain = "company.com"
Mailer.UserName = "bill"
Mailer.Password = "bill's password"
Mailer.AuthMethod = 2 ' Use NTLM
If Mailer.Connect Then ' Connect to bill@company.com account
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Connect Method

Password Property
ServerName Property


UserName Property

The name of the user account on the IMAP4 server.

Usually this is the first part of the email address (e.g. "bill" for "bill@host.com"). Sometimes, however, it can be full email address or something else (it depends on IMAP4 account settings).

This can be left an empty string if you're using Integrated Windows Authentication. See AuthMethod property for details.

Note: This value (if not specified in Connect method parameters) must be set BEFORE calling Connect method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "imap.host.com"
Mailer.UserName = "bill"
Mailer.Password = "bill's password"
If Mailer.Connect Then ' Connect to bill@host.com account
  MsgBox "Connected successfully"
  Mailer.Disconnect
End If

See Also:

Connect Method

Password Property
ServerName Property


UTF7EncodeMailboxNames Property

Tells MailBee whether to automatically encode IMAP mailbox names to UTF-7M when sending requests to the server.

By default, this property is set to True which means mailbox names are encoded automatically when MailBee sends them as part of requests to the server. This property, however, doesn't affect decoding of mailbox names received from the server: Mailbox.Name property always contains decoded name, Mailbox.OriginalName - original name.

Encoding mailbox names makes sense when your application operates with mailboxes having non-latin or special characters in their names. However, some IMAP servers don't support UTF-7M encoding for mailboxes names.

Well designed application sets this property to False; then, it uses decoded names when presenting them to the user and encoded names when sending them to the server. To get encoded name, use Mailbox.OriginalName property. To encode a mailbox name manually (if you're creating a new mailbox and thus no Mailbox.OriginalName value is available), use ToUTF7 method.

In case if you hardcode mailbox names in Visual Basic code (such as VBScript), make sure you saved the code file in ANSI and not UTF-8 encoding. Otherwise, non-English characters may get corrupted when the actual content in the file is UTF-8 while VB runtime thinks it's ANSI. This may also be a problem for other programming environments which are limited in their UTF-8 support.

Value Type: | Boolean
Parameters: | None

Usage example:

' This sample gets all mailboxes list and selects last mailbox in the collection.
' Then, messages count is displayed for this mailbox.

Dim Mailer, Mailboxes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  'Turn off encoding mailbox names
  Mailer.UTF7EncodeMailboxNames = False
  Set Mailboxes = Mailer.RetrieveMailboxes
  If Not Mailboxes Is Nothing Then
    If Mailboxes.Count > 0 Then
      If Mailer.SelectMailbox(Mailboxes(Mailboxes.Count).OriginalName) Then
        MsgBox Mailer.MessageCount & " messages in " & Mailboxes(Mailboxes.Count).Name
      End If
    End If
  End If
  Mailer.Disconnect
End If

See Also:

SelectMailbox Method
RetrieveMailboxes Method

Mailbox.Name Property
Mailbox.OriginalName Property


Abort Method

Aborts currently performed long-run operation and immediately disconnects from the IMAP4 server. If no long-run operation is currently performed, the method does nothing.

Long-run operation is any action which causes data exchange with the IMAP4 server. Connecting to the server, retrieving messages or envelopes, graceful disconnecting, etc. are all long-run operations.

To determine whether long-run operation is currently performing, examine Busy property value.

When long-run operation is aborted, rough disconnection procedure takes place (not graceful one) so "LOGOUT" IMAP4 command is not executed. However, unlike POP3 (where "QUIT" command also expunges messages marked for deletion), IMAP4 "LOGOUT" command just disconnects from the server and does nothing more. To confirm expunging messages from IMAP4 mailbox, issue Expunge or ExpungeAndClose command.

Once the connection is aborted, ErrCode property of IMAP4 object is set to value of 7 (Connection aborted by client side).

Note: Abort method can be called only if IMAP4.EnableEvents=True (Async mode is on). Calling Abort method does not immediately closes the connection, it just notifies IMAP4 object to close it. Closing itself occurs after millisecond or so after calling Abort method. This is a specificity of Async mode operation.

blnResult = ObjectName.Abort
Parameters: | None
Return value As Boolean | True if successful, False if error has occurred (nothing to abort because there is no long-run operation in progress)

Usage example:

Option Explicit
Dim objIMAP4 As Object

Private Sub Command1_Click()
  Dim Envelopes As Object
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"
  objIMAP4.EnableEvents = True ' Enable asynchronous mode
  If objIMAP4.Connect("mailserver.com", 143, "MyName", "MyPassword") Then ' Long-run operation
    If objIMAP4.SelectMailbox("Inbox") Then ' Long-run operation
       Set Envelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False) ' Long-run operation
    End If
    objIMAP4.Disconnect ' Long-run operation
  End If
End Sub

Private Sub Form_Load()
    Set objIMAP4 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
    If objIMAP4 Is Nothing Then Exit Sub
    If objIMAP4.Busy Then objIMAP4.Abort ' Cancel IMAP4 session on exit
End Sub

See Also:

Busy Property
EnableEvents Property
ErrCode Property

Expunge Method
ExpungeAndClose Method


AppendMessage Method

Uploads a message to the specified mailbox on the server.

Messages can be uploaded from files (Options parameter set to 1) or from strings (Options=0). To load message from Message object, use Options=0 and pass Message.RawBody property as a value of Message parameter.

To get the UID value assigned to the message in the destination folder, you can use UIDPlusResult property.

blnResult = ObjectName.AppendMessage(MailboxName, Message, [Date], [Flags], [Options])
Parameters:
MailboxName As String | Name of the mailbox to upload message to
Message | Message source string. If Options=1, filename of the file containing message source.
Date As String (optional) If omitted, current date and time will be used. If specified, sets date of the message. Note that this is the date when the message was received by the server (which corresponds to Envelope.Date value), not the date when the message was created (which corresponds to Date header in the e-mail and Envelope.RFC822Date value).

Use the following format for this value: 01-Jun-2004 15:52:30 -0500
Flags As Variant (optional) Defaults to empty (no flags). Can be either a string like "\Answered \Seen $Starred" (allows for non-standard flags if supported by the server) or a number which is any combination of the following:
  • 1 - Answered
  • 2 - Deleted
  • 4 - Draft
  • 8 - Flagged
  • 16 - Recent
  • 32 - Seen
Options As Long | (optional) Defaults to zero. If Options=1, Message parameter points to filename of the file containing message source.
Return value As Boolean | True if successful, False if error has occurred

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then

  ' Upload message from mail.eml file keeping defaults for datetime and flags
  If Mailer.AppendMessage("Inbox", "C:\mail.eml", , , 1) Then
    MsgBox "Message uploaded successfully"
  End If

  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Message.RawBody Property


ClearLog Method

Clears log file (if logging is on).

Consider calling this method each time your application starts or enters new cycle of processing. Otherwise, log file will increase in size with every IMAP4 session.

blnResult = ObjectName.ClearLog
Parameters: | None
Return value As Boolean | True if successful, False if logging is off or error has occurred (path denoted by LogFilePath property is not accessible, file is locked, etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\my_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

See Also:

EnableLogging Property
LogFilePath Property


Connect Method

Connects to the IMAP4 server and logs in the specified user account.

In order to call this method, make sure LicenseKey property is already set, otherwise, the method will fail.

Also, if you want to call this method without parameters, make sure to previously set the following properties:

  • ServerName
  • UserName
  • Password
If IMAP4 server operates on non-standard port (non-143), use PortNumber property to set appropriate value.

If you're using Integrated Windows Authentication (IWA), you may leave UserName and Password blank but must set AuthMethod property to use IWA-compatible authentication method.

Note: If Connect method is called with parameters, ServerName, PortNumber, UserName, Password, UserDomain, TargetName properties are automatcially updated to reflect specified parameters' values.

blnResult = ObjectName.Connect([ServerName], [PortNumber], [UserName], [Password], [UserDomain], [TargetName])
Parameters: |
ServerName As String | (optional) Server name to connect to. If not specified, current ServerName value will be used
PortNumber As Long | (optional) IMAP4 port number. If not specified, current PortNumber value will be used
UserName As String | (optional) The user account name. If not specified, current UserName value will be used
Password As String | (optional) The user account password. If not specified, current Password value will be used
UserDomain As String | (optional) The user domain name (only used with NTLM and Kerberos). If not specified, current UserDomain value will be used
TargetName As String | (optional) The SPN (only used with Kerberos). If not specified, current TargetName value will be used
Return value As Boolean | True if successful, False if connect procedure failed (mail server is not responding, username and/or password is incorrect, authentication method is not supported, license key is invalid). You can check ErrDesc property or log file to get more detailed error information

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  MsgBox "Connected successfully"
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

ServerName Property
PortNumber Property
UserName Property
Password Property

ErrDesc Property

Disconnect Method


CopyMessages Method

Copies one or more messages from the currently selected mailbox to another mailbox.

To copy a single message, set First and Last parameters to the same message number or UID.

To copy an arbitrary set of messages, specify MessageSet property and pass -1 as First value (Last value is not important when First is -1). AsUID parameter is still honored when IDs are taken from MessageSet property (depending on AsUID value, they will be treated as UIDs or ordinal message numbers).

To copy all messages starting from a particular one, set First to its UID or ordinal message number and Last to -1. This issues a special IMAP request COPY X:* where X is your First value. Alternatively, you can set Last to MessageCount (like in the sample below) but it only works for ordinal message numbers and not UIDs (because you may not know the UID of the last message in the mailbox and requesting it from the server causes the overhead of an extra IMAP query).

To get the UID values assigned to the messages in the destination folder, you can use UIDPlusResult property.

blnResult = ObjectName.CopyMessages(MailboxName, First, Last, AsUID)
Parameters: |
MailboxName As String | Destination mailbox name. Messages will be copied to this mailbox
First As Long | Message number or UID of the first message in the copied range, or -1 to use MessageSet as input.
Last As Long | Message number or UID of the last message in the copied range. -1 means "last message in the mailbox".
AsUID As Boolean | If True, First and Last parameters must be specified as UIDs (unique-IDs). Otherwise, First and Last must be message numbers.
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information.

Usage example:

' This sample copies all messages with message numbers starting at 20 from "Inbox" folder
' into "Archive" folder. Both folders must exist.

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    If Mailer.CopyMessages("Archive", 20, Mailer.MessageCount, False) Then
        MsgBox "Messages copied successfully"
    End If
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

MessageCount Property

SelectMailbox Method


CreateMailbox Method

Creates a mailbox on the IMAP4 server.

If mailbox names you're dealing with may contain non-English characters, please read UTF7EncodeMailboxNames topic to make sure everything's done right.

blnResult = ObjectName.CreateMailbox(MailboxName)
Parameters: |
MailboxName As String | Name of the mailbox to create
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample creates "Archive" mailbox.

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.CreateMailbox("Archive") Then
    MsgBox "Mailbox created successfully"
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

RetrieveMailboxes Method
SelectMailbox Method

DeleteMailbox Method
RenameMailbox Method


DeleteMailbox Method

Deletes existing mailbox from the IMAP4 server.

If mailbox names you're dealing with may contain non-English characters, please read UTF7EncodeMailboxNames topic to make sure everything's done right.

blnResult = ObjectName.DeleteMailbox(MailboxName)
Parameters: |
MailboxName As String | Name of the mailbox to delete
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample deletes "Archive" mailbox.

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.DeleteMailbox("Archive") Then
    MsgBox "Mailbox deleted successfully"
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

RetrieveMailboxes Method
SelectMailbox Method

CreateMailbox Method
RenameMailbox Method


DeleteMessages Method

Marks one or more messages in the currently selected mailbox as "deleted".

This method does not really deletes messages, it just sets "deleted" flag for them. To permanently remove messages marked as "deleted", call Expunge or ExpungeAndClose method.

To delete a single message, set First and Last parameters to the same message number or UID.

To delete an arbitrary set of messages, specify MessageSet property and pass -1 as First value (Last value is not important when First is -1). AsUID parameter is still honored when IDs are taken from MessageSet property (depending on AsUID value, they will be treated as UIDs or ordinal message numbers).

To delete all messages starting from a particular message number (not UID), set First parameter to this number and Last one to MessageCount value. If working with UIDs, you can specify UID of the fist message as First and -1 as Last value (in case if you don't know the UID of the last message).

blnResult = ObjectName.DeleteMessages(First, Last, AsUID)
Parameters: |
First As Long | Message number or UID of the first message in the deleted range, or -1 to use MessageSet as input.
Last As Long | Message number or UID of the last message in the deleted range. -1 means "last message in the mailbox".
AsUID As Boolean | If True, First and Last parameters are treated as UIDs. Otherwise, they are treated as message numbers.
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information.

Usage example:

' This sample deletes the first message from "Inbox" mailbox

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    If Mailer.DeleteMessages(1, 1, False) Then
      MsgBox "Message marked as deleted"
    End If
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

MessageCount Property

Expunge Method
ExpungeAndClose Method
SelectMailbox Method


Disconnect Method

Disconnects from the IMAP4 server.

It is not necessary (though it's recommended) to call this method. The IMAP4 object automatically disconnects from the IMAP4 server when the object is to be freed.

Note: Unlike POP3, IMAP4 disconnection procedure does not expunges messages marked for deletion. To expunge messages, you must explicitly call Expunge or ExpungeAndClose method.

blnResult = ObjectName.Disconnect
Parameters: | None
Return value As Boolean | True if successful, False if disconnect procedure failed (was not connected, mail server is not responding). You can check ErrDesc property or log file to get more detailed error information
Remarks: | If this method fails, the connection will be aborted anyway. This means that Connected property will be always False after calling Disconnect method

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.Disconnect Then
    MsgBox "Connection gracefully closed"
  Else
    MsgBox "Connection aborted"
  End If
End If

See Also:

Connect Method


ExamineMailbox Method

Selects specified mailbox on the IMAP4 server for read-only access.

This method is identical to SelectMailbox method with only exception that no changes of mailbox state are allowed (adding or removing messages, setting flags, etc.).

To get available mailboxes list, use RetrieveMailboxes method.

If mailbox names you're dealing with may contain non-English characters, please read UTF7EncodeMailboxNames topic to make sure everything's done right.

blnResult = ObjectName.ExamineMailbox(MailboxName)
Parameters: |
MailboxName As String | Name of the mailbox to select
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample examines "Inbox" mailbox and displays total number of messages there

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.ExamineMailbox("Inbox") Then
    MsgBox Mailer.MessageCount & " messages in Inbox"
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Selected Property

RetrieveMailboxes Method
SelectMailbox Method


Expunge Method

Permanently removes all messages from the selected mailbox that are marked as "deleted".

blnResult = ObjectName.Expunge
Parameters: | None
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample permanently deletes last 3 messages from "Inbox" mailbox

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    If Mailer.DeleteMessages(Mailer.MessageCount - 2, Mailer.MessageCount, False) Then
      If Mailer.Expunge Then
        MsgBox "Messages expunged successfully"
      End If
    End If
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

DeleteMessages Method
ExpungeAndClose Method
SelectMailbox Method


ExpungeAndClose Method

Permanently removes all messages marked as "deleted" and closes currently selected mailbox.

If this method is not called before disconnecting or selecting another mailbox, messages marked as "deleted" are not removed. However, their "deleted" flag is not discarded.

blnResult = ObjectName.ExpungeAndClose
Parameters: | None
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample permanently deletes all messages from "Inbox" that
' have "deleted" flag set during previous sessions.

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    If Mailer.ExpungeAndClose Then
      MsgBox "Messages expunged successfully. Mailbox closed"
    End If
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

DeleteMessages Method
Expunge Method
SelectMailbox Method


FromUTF7 Method

Decodes the specified UTF-7M string into regular string.

Usually, you do not need to manually decode mailbox names returned by the IMAP server because the decoded name is always available via Mailbox.Name property (undecoded name is also available, see Mailbox.OriginalName property).

Manual decoding of MailBox.OriginalName makes no sense because decoded mailbox name is available in Mailbox.Name property. However, if your application stores MailBox.OriginalName in a database back-end, you should use this method to decode mailbox name (make it readable for users) retrieved from the database. This allows storing only MailBox.OriginalName in the database (no need to also store Mailbox.Name).

str = ObjectName.ToUTF7(SrcUTF7)
Parameters: |
SrcUTF7 As String | Source text string in UTF-7-Modified
Return value As String | Decoded version of the source string

Usage example:

{CodeExample}

See Also:

ToUTF7 method
UTF7EncodeMailboxNames property


GetCapabilities Method

Returns the list of capabilities of the IMAP4 server.

You can additionally specify Capability parameter if you're looking for the particular capability. Capability names are case-insensitive.

This method does not necessarily send CAPABILITY command to the server because the capabilities list may already be available (for instance, you already called this method before or the server itself isssues CAPABILITY response during connecting or authenticating the client).

arrCaps = ObjectName.GetCapabilities([AlwaysSendCommand], [Capability])
Parameters: |
AlwaysSendCommand As Boolean | (optional) If True, MailBee will send CAPABILITY command even if the capabilities list has already been received from the server. The default and recommended value is False
Capability As String | (optional) If non-empty, tells MailBee to return only the specified capability (or return empty array if the specified capability is not supported by the server). If empty string (default), MailBee will return all the capabilities supported by the server
Return value As Variant | Array of Variant/Long, each value is a capability name. If error has occurred, return value is Empty

Usage example:

' This sample checks if the server supports XLIST extension (Sent/Drafts/Trash/Spam flags for IMAP folders,
' Gmail is well-known service which supports this) and uses XLIST to get folders with these flags.
' If XLIST is not supported, folders are retrieved without special folder flags.
Dim Mailer, Caps, Message, UseXList
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
Mailer.SSL.Enabled = True
If Mailer.Connect("imap.gmail.com", 993, "username", "password") Then
  Caps = Mailer.GetCapabilities( , "XLIST")
  If Not IsEmpty(Caps) Then
    UseXList = False
    If UBound(Caps) >= Lbound(Caps) Then UseXList = True
    Set Mailboxes = Mailer.RetrieveMailboxesEx(, , , UseXList)
    Mailer.Disconnect
  End If
End If

See Also:

RetrieveMailboxesEx Method


GetLastReceivedDataChunk Method

Gets the last received data block of the server's response as a string.

Typically, you'll use this method in OnReceiveData event handler to monitor the data being received during the connection. Typically, 5-60KB data portion is returned per call. For instance, if you're downloading 1MB e-mail, OnReceiveData event will fire about 30-200 times as the overall data is split in 30-200 chunks.

The method should be called once per a single triggering of OnReceiveData event.

strData = ObjectName.GetLastReceivedDataChunk()
Parameters: | None
Return value As String | Data portion received with the last read data operation.

Usage example:

Option Explicit
' Early binding and "WithEvents" syntax required for handling MailBee's events
Dim WithEvents objIMAP4 As MailBee.IMAP4

Private Sub Command1_Click()
  Dim Envelopes As MailBee.Envelopes
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"
  objIMAP4.EnableEvents = True ' Enable Async mode
  If objIMAP4.Connect("mailserver.com", 143, "MyName", "MyPassword") Then ' Long-run operation
    If objIMAP4.SelectMailbox("Inbox") Then ' Long-run operation
      Set Envelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False) ' Long-run operation
    End If
    objIMAP4.Disconnect ' Long-run operation
  End If
End Sub

' Respond to MailBee's OnReceiveData event and print the actual data received
Private Sub objIMAP4_OnReceiveData(ByVal BytesReceived As Long, Proceed As Boolean)
  Debug.Print objIMAP.GetLastReceivedDataChunk
End Sub

Private Sub Form_Load()
  Set objIMAP4 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If objIMAP4 Is Nothing Then Exit Sub
  If objIMAP4.Busy Then objIMAP4.Abort ' Cancel IMAP4 session on exit
End Sub

See Also:

OnReceiveData Event


GetMailboxQuota Method

Retrieves the size of the specified mailbox quota in kilobytes.

To get the quota for the entire mail account (including all mailboxes in it), specify empty value for the MailboxName. The method will return -1 if the server does not support QUOTA extension or the folder name is incorrect. Otherwise, the returned value is the quota size in kilobytes (1 kilobyte is 1024 bytes).

Upon calling this method, you can check QuotaUsage property to determine the used space in the account.

If the quota value is very large (such as 2147483647), it usually means the quota size is not limited for the given account (the quota is not set).

lngQuota = ObjectName.GetMailboxQuota(MailboxName)
Parameters: |
MailboxName As String | Name of the mailbox to get the quota for, or an empty string to get the quota for the entire account
Return value As Long | On success, the quota value in kilobytes. On failure, return value is -1
Remarks: | QUOTA extension may not be supported by some IMAP servers.

Usage example:

' This sample displays the quota limit (in kilobytes) for the mail account
Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  MsgBox Mailer.GetMailboxQuota("") & " kilobytes"
  Mailer.Disconnect
End If

See Also:

QuotaUsage Property


GetMailboxStatus Method

Retrieves various stats for the specified mailbox without selecting it.

This method can be used to obtain the folder status information such as total count of messages, recent messages count, unseen messages count, etc without selecting the mailbox.

objStatus = ObjectName.RetrieveSingleMessage(Index, AsUID)
Parameters: |
MailboxName As String | Mailbox name
Return value As MailBee.MailboxStatus | On success, the method returns MailboxStatus object which represents the mailbox stats. On failure, return value is Nothing

Usage example:

' This sample retrieves and displays all the stats of Inbox
Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "MessageCount=" & Stats.MessageCount & " RecentCount=" & Stats.RecentCount & " UnseenCount=" & Stats.UnseenCount
    MsgBox "UIDValidity=" & Stats.UIDValidity & " UIDNext=" & Stats.UIDNext
  End If
  Mailer.Disconnect
End If

See Also:

Message Object


Idle Method

Switches the connection with the server in IDLE mode when the server itself can send notifications to the client about new events.

You can use this method to receive notifications from the server about new messages, changes of message status, and so on without constant polling the mailbox. The server, however, must support IDLE extension.

Prior to calling this method, you should subscribe to OnStatusChange and OnIdle events and set EnableEvents=True. OnStatusChange will raise each time the server sends a notification. OnIdle will raise each 10 milliseconds. Usually, your code will immediately set some flag to False in OnStatusChange event hanlder when a notification arrives from the server. Then, your OnIdle event handler will check this flag and set Proceed argument of the event handler function to False. This will be a signal for Idle method to stop. Then, after you finish processing the mailbox (e.g. download new messages), you can call Idle again.

To avoid disconnecting from the server due to inactivity, it's recommended to re-issue Idle every 10-20 minutes (i.e. set Proceed to False in OnIdle event handler and then call Idle in the main code again). You can remember calculate time elapsed with a timer or rely on the fact that OnIdle event is called every 10 milliseconds (although this is not precise, this is usually not a concern).

This method also updates values of MessageCount and RecentCount properties.

Due to the nature of this method, it can only be used with EnableEvents=True. ASP applications cannot use this too because an ASP page should execute as quickly as possible. Keeping connection for a long time in an ASP application is strongly discouraged.

blnResult = ObjectName.Idle
Parameters: | None
Return value As Boolean | True if successful, False if error has occurred (usually connection failure or IDLE not supported)
Remarks: | IDLE extensions may not be supported by some IMAP servers.

Usage example:

' MailBee.dll must be referenced in Project/References (we need this in order to use events),
' and two buttons must be placed on the form: CommandStart and CommandFinish

' You must declare these variables in the beginning of your VB6 form code
Dim WithEvents IMAP As MailBee.IMAP4
Dim Idling As Boolean
Dim Done As Boolean
Dim GotNews As Boolean
Dim IdleCounter As Long

' Connects to the server and starts idling. Note: nothing will happen until the mailbox
' state changes during idling (such as new messages arrive or old messages change their status).
Private Sub CommandStart_Click()
  Set IMAP = CreateObject("MailBee.IMAP4")
  IMAP.EnableEvents = True

  ' Enable logging for troubleshooting
  IMAP.EnableLogging = True
  IMAP.LogFilePath = "imap4_log.txt"
  IMAP.ClearLog

  Done = False
  GotNews = False
  Idling = False
  IMAP.LicenseKey = "put your license key here"
  If IMAP.Connect("mail.server.com", 143, "jdoe", "password") Then
    If IMAP.SelectMailbox("Inbox") Then
    While Not Done
      Idling = True
      IdleCounter = 0
      If IMAP.Idle Then ' This method call will last for 10 minutes or so unless a notification from the server arrives
        Idling = False
        If GotNews Then
          ' Download new messages or whatever you want (here, we just display the number of recent messages)
          MsgBox IMAP.RecentCount
          GotNews = False
        End If
      Else
        Idling = False
        Done = True
        MsgBox "IDLE failed"
      End If
    Wend
    End If
    IMAP.Disconnect
    MsgBox "Idling finished"
  End If
End Sub

' OnStatusChange fires every time the server sends a notification (regardless if IDLE mode is active or not)
Private Sub IMAP_OnStatusChange(ByVal EventCode As Long, ByVal Message As Long, ByVal Value As Long, Proceed As Boolean)
    If Idling Then ' We check Idling to remember only those notifications which occurred during idling
       GotNews = True
    End If
End Sub

' Stop Idle method if got notification or timeout elapsed (approx. 10 minutes) or user says "Done!"
Private Sub IMAP_OnIdle(Proceed As Boolean)
    If GotNews Or Done Or IdleCounter > 60000 Then Proceed = False
    IdleCounter = IdleCounter + 1
End Sub

' Place a button named Finish to the form. You'll click it to finish idling
Private Sub CommandFinish_Click()
    Done = True
End Sub

' Make sure the application won't hang if the user closes it without clicking Finish button
Private Sub Form_Unload(Cancel As Integer)
  If Not (IMAP Is Nothing) Then IMAP.Abort
End Sub

See Also:

EnableEvents Property
MessageCount Property
RecentCount Property

OnStatusChange Event


MoveMessages Method

Moves one or more messages from the currently selected mailbox to another mailbox.

The IMAP server must support MOVE extension for this method to work! Use GetCapabilities method to check this first.

To move a single message, set First and Last parameters to the same message number or UID.

To move an arbitrary set of messages, specify MessageSet property and pass -1 as First value (Last value is not important when First is -1). AsUID parameter is still honored when IDs are taken from MessageSet property (depending on AsUID value, they will be treated as UIDs or ordinal message numbers).

To move all messages starting from a particular one, set First to its UID or ordinal message number and Last to -1. This issues a special IMAP request MOVE X:* where X is your First value. Alternatively, you can set Last to MessageCount (like in the sample below) but it only works for ordinal message numbers and not UIDs (because you may not know the UID of the last message in the mailbox and requesting it from the server causes the overhead of an extra IMAP query).

To get the UID value assigned to the message in the destination folder, you can use UIDPlusResult property.

blnResult = ObjectName.CopyMessages(MailboxName, First, Last, AsUID)
Parameters: |
MailboxName As String | Destination mailbox name. Messages will be copied to this mailbox
First As Long | Message number or UID of the first message in the moved range, or -1 to use MessageSet as input.
Last As Long | Message number or UID of the last message in the moved range. -1 means "last message in the mailbox".
AsUID As Boolean | If True, First and Last parameters must be specified as UIDs (unique-IDs). Otherwise, First and Last must be message numbers.
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information.

Usage example:

' This sample moves last 3 messages from "Inbox" folder
' into "Archive" folder. Both folders must exist and Inbox must contain 3 messages at least.

Dim Mailer, Caps, MoveSupported
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "user@login", "password") Then
  MoveSupported = False
  Caps = Mailer.GetCapabilities( , "MOVE")
  If Not IsEmpty(Caps) Then
    If UBound(Caps) >= Lbound(Caps) Then MoveSupported = True
  End If

  If MoveSupported Then
    If Mailer.SelectMailbox("Inbox") Then
      If Mailer.MoveMessages("Archive", Mailer.MessageCount - 2, Mailer.MessageCount, False) Then
          MsgBox "Messages moved successfully"
      Else
        If Mailer.ErrCode = 311 Or Mailer.ErrCode = 312 Then
          MsgBox Mailer.ServerStatusResponse
        Else
          MsgBox "Error #" & CStr(Mailer.ErrCode)
        End If
      End If
    End If
  Else
    MsgBox "MOVE not supported :("
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

MessageCount Property

SelectMailbox Method


Ping Method

Sends "NOOP" command to the IMAP4 server.

You can use this method to keep connection with the IMAP4 server alive.

Also, this method updates values of MessageCount and RecentCount properties. These values can accidentally change when another user simultaneously accesses the same mailbox. In such a case IMAP4 object will fire OnStatusChange event (if EnableEvents=True).

blnResult = ObjectName.Ping
Parameters: | None
Return value As Boolean | True if successful, False if error has occurred (usually connection failure)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  ' Start doing some long-lasting job here
  Mailer.Ping ' Call Ping to remind the server about us
  ' Continue long-lasting job
  Mailer.Disconnect
End If

See Also:

EnableEvents Property
MessageCount Property
RecentCount Property

OnStatusChange Event


RenameMailbox Method

Renames existing mailbox on the IMAP4 server.

If mailbox names you're dealing with may contain non-English characters, please read UTF7EncodeMailboxNames topic to make sure everything's done right.

blnResult = ObjectName.RenameMailbox(OldName, NewName)
Parameters: |
OldName As String | Existing mailbox name
NewName As String | New mailbox name
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample renames "Archive" mailbox into "Backup".

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.RenameMailbox("Archive", "Backup") Then
    MsgBox "Mailbox renamed successfully"
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

RetrieveMailboxes Method
SelectMailbox Method

CreateMailbox Method
DeleteMailbox Method


RetrieveEnvelopes Method

Retrieves one or more message envelopes from currently selected IMAP4 mailbox.

Each envelope in returned collection is an Envelope object which represents brief information of the message: size, subject, "From", "To", "Date", etc.

To retrieve single message envelope only, specify the same value for the First and the Last parameters.

To get an arbitrary set of messages, specify MessageSet property and pass -1 as First value (Last value is not important when First is -1). AsUID parameter is still honored when IDs are taken from MessageSet property (depending on AsUID value, they will be treated as UIDs or ordinal message numbers).

To get more detailed synopsis on each message (such as message attachments list or custom headers), use RetrieveEnvelopesEx method.

objEnvelopes = ObjectName.RetrieveEnvelopes(First, Last, AsUID)
Parameters: |
First As Long | Message number or UID of the first message envelope to retrieve, or -1 to use MessageSet as input.
Last As Long | Message number or UID of the last message envelope to retrieve, or -1 to denote the last message in the mailbox.
AsUID As Boolean | If True, First and Last parameters must be specified as UIDs (unique-IDs). Otherwise, First and Last must be message numbers.
Return value As MailBee.Envelopes | On success, Envelopes collection is returned. On failure, return value is Nothing.

Usage example:

' This sample displays Subject for the first 10 messages in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(1, 10, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.Subject
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Envelope Object

Envelopes Collection

RetrieveEnvelopesEx Method
RetrieveSingleMessageHeaders Method


RetrieveEnvelopesEx Method

Retrieves one or more message envelopes (and, optionally, extended information such as body structure and message preview) from currently selected IMAP4 mailbox.

To retrieve single message envelope only, specify the same value for the First and the Last parameters.

To get an arbitrary set of messages, specify MessageSet property and pass -1 as First value (Last value is not important when First is -1). AsUID parameter is still honored when IDs are taken from MessageSet property (depending on AsUID value, they will be treated as UIDs or ordinal message numbers).

If your IMAP server returns broken envelope (which can't be parsed by MailBee) among with good ones and you still want to continue receiving the data in such cases, you may set IgnoreFailures parameter to True to force ignoring broken envelopes. In such case, this method returns all parsed envelopes collection (i.e. not Nothing value), but ErrCode and IsError properties show that an error occurred (connection with the IMAP server will be lost). This allows you to get all envelopes retrieved prior to the error occurred. If IgnoreFailures is False, the method returns Nothing on any failure.

Note: For optimal performance, it's not recommended to retrieve large number (hundreds or thousands) of envelopes with extended information (such as large message preview) at once. Because envelopes are usually used for preview purposes such as building message list, downloading too much data may seriously increase response time of the end system.

objEnvelopes = ObjectName.RetrieveEnvelopesEx(First, Last, AsUID, [AlsoGetBodyStructure], [AlsoGetMessagePreview], [BodyPreviewSize], [IgnoreFailures])
Parameters: |
First As Long | Message number or UID of the first message envelope to retrieve, or -1 to use MessageSet as input.
Last As Long | Message number or UID of the last message envelope to retrieve, or -1 to denote the last message in the mailbox.
AsUID As Boolean | If True, First and Last parameters must be specified as UIDs (unique-IDs). Otherwise, First and Last must be message numbers.
AlsoGetBodyStructure As Boolean | (optional) If True, BodyStructure property of each Envelope object in returned collection contains body structure of the message. If False, BodyStructure is Nothing. Default is False.
AlsoGetMessagePreview As Boolean | (optional) If True, MessagePreview property of each Envelope object in returned collection contains the message preview. If False, MessagePreview is Nothing. Default is False.
BodyPreviewSize As Long | (optional) Specifies the number of bytes of the message body to be returned in addition to message headers for MessagePreview. If AlsoGetMessagePreview=False, BodyPreviewSize makes no sense. If BodyPreviewSize=-1, the entire message gets downloaded but \Seen flag is not set (-2 gets the entire message with \Seen flag set). Default is 0.
IgnoreFailures As Boolean | (optional) If True, forces the method to ignore broken envelopes and parse all other ones which can be parsed. Default is False.
Return value As MailBee.Envelopes | On success, Envelopes collection is returned. On failure, return value is Nothing

Usage example:

' This sample displays preview of body text (taken from first
' 1000 bytes of the body) of every message in Inbox. Broken envelopes
' don't cause the method to fail.
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopesEx _
      (1, -1, False, False, True, 1000, True)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.MessagePreview.BodyText
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Envelope.BodyStructure Property
Envelope.MessagePreview Property
Envelope.UID Property

BodyStructure Object
Envelope Object

Envelopes Collection

RetrieveEnvelopes Method
RetrieveSingleMessageHeaders Method


RetrieveMailboxes Method

Retrieves Mailboxes collection which contains all mailboxes in the IMAP4 account.

RetrieveMailboxesEx method provides additional functionality.

objMailboxes = ObjectName.RetrieveMailboxes([SubscribedOnly])
Parameters: |
SubscribedOnly As Boolean | (optional) If True, only subscribed mailboxes are retrieved. Default is False
Return value As MailBee.Mailboxes | On success, Mailboxes collection is returned. On failure, return value is Nothing

Usage example:

' This sample gets all mailboxes list and selects last mailbox in the collection.
' Then, messages count is displayed for this mailbox.
Dim Mailer, Mailboxes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Set Mailboxes = Mailer.RetrieveMailboxes
  If Not Mailboxes Is Nothing Then
    If Mailboxes.Count > 0 Then
      If Mailer.SelectMailbox(Mailboxes(Mailboxes.Count).Name) Then
        MsgBox Mailer.MessageCount & " messages in " & Mailboxes(Mailboxes.Count).Name
      End If
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Mailbox Object

Mailboxes Collection

ExamineMailbox Method
SelectMailbox Method


RetrieveMailboxesEx Method

This method retrieves Mailboxes collection which contains mailboxes of the IMAP4 account. This collection includes only mailboxes which are passed user defined criteria.

Specail mailbox flags like \Trash or \Drafts are automatically available if the server supports SPECIAL-USE extension. If the server does not support SPECIAL-USE but supports XLIST, see example in GetCapabilities topic on how proceed with XLIST-way. Special mailbox flags will be available together with all other folder flags through Mailbox.Flags property of each Mailbox object in the returned collection.

Note: GMail does support both XLIST and SPECIAL-USE. It does not advertize SPECIAL-USE in its capability list but since SPECIAL-USE extension does not add new commands and all flags become automatically available, you don't need to check for extensions or do anything special to work with extra flags added by SPECIAL-USE.

Two flags ("\HasChildren" and "\HasNoChildren") are added by yet another extension, CHILDREN (supported by Gmail). They are ony useful in case if you work with very large number of mailboxes and don't want to load them all (OneLevelOnly option which gets a particular level of mailboxes without getting their children). These flags let the application understand which mailboxes in the received list have sub-mailboxes (for instance, the app can display '+' button near their names to let the user expand them).

objMailboxes = ObjectName.RetrieveMailboxes(RootMailBoxName, [SubscribedOnly], OneLevelOnly, [GetSpecialFoldersFlags])
Parameters: |
RootMailboxName As String | (optional) If not empty only sub-mailboxes of the specified mailbox will be retrieved, otherwise all mailboxes of the account will be retrieved. Default is False meaning that no mailbox filter is set.
SubscribedOnly As Boolean | (optional) If True the only subscribed mailboxes will be retrieved (the parameter is ignored if GetSpecialFoldersFlags is True). Default is False
OneLevelOnly | (optional) If True only first level sub-folders of the mailbox will be retrieved. Default is False
GetSpecialFoldersFlags As Boolean | (optional) If True, MailBee will also determine special folder flags (Inbox/Drafts/Sent/Spam/Trash/etc) by using XLIST command instead of LIST (the server must support XLIST). Note that for the server which supports SPECIAL-USE extension, no special command needed and this parameter should be left False. XLIST is now considered deprecated. The default is False
Return value As MailBee.Mailboxes | On success, Mailboxes collection is returned. On failure, return value is Nothing

Usage example:

' This sample gets first-level mailboxes list and selects last mailbox in the collection.
' Then, number of messages is displayed for this mailbox.
Dim Mailer, Mailboxes
' Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
' Using ASP to create object
' Set Mailer = Server.CreateObject("MailBee.IMAP4")
' In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
   Set Mailboxes = Mailer.RetrieveMailboxesEx("", False, True)
   If Not Mailboxes Is Nothing Then
      If (Mailboxes.Count > 0) Then
         If Mailer.SelectMailbox(Mailboxes(Mailboxes.Count).Name) Then
            MsgBox Mailer.MessageCount & " messages in " & Mailboxes(Mailboxes.Count).Name
         End If
      End If
   End If
   Mailer.Disconnect
End If

See Also:

RetrieveMailboxes Method | ExamineMailbox Method | SelectMailbox Method | Mailbox Object | Mailboxes Collection


RetrieveMessagesSize Method

Retrieves combined size (in bytes) of one or more messages in the currently selected IMAP4 mailbox.

To get total size of all messages in the currently selected IMAP4 mailbox, call RetrieveTotalSize method.

Message size is also available as the Size property of Envelope object. See RetrieveEnvelopes method description on how to get message envelopes.

To retrieve the size for single message only, specify the same value for the First and the Last parameters.

To get the size of an arbitrary set of messages, specify MessageSet property and pass -1 as First value (Last value is not important when First is -1). AsUID parameter is still honored when IDs are taken from MessageSet property (depending on AsUID value, they will be treated as UIDs or ordinal message numbers).

objEnvelopes = ObjectName.RetrieveMessagesSize(First, Last, AsUID)
Parameters: |
First As Long | Message number or UID of the first message in the range, or -1 to use MessageSet as input.
Last As Long | Message number or UID of the last message in the range, or -1 to denote the last message in the mailbox.
AsUID As Boolean | If True, First and Last parameters must be specified as UIDs (unique-IDs). Otherwise, First and Last must be message numbers.
Return value As Long | On success, combined size of all messages in the range. On failure, return value is 0.

Usage example:

' This sample displays the combined size of the first 10 messages in Inbox
Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    MsgBox Mailer.RetrieveMessagesSize(1, 10, False) & " bytes"
  End If
  Mailer.Disconnect
End If

See Also:

Envelope Object

Envelope.Size Property

RetrieveEnvelopes Method
RetrieveSingleMessageHeaders Method
RetrieveTotalSize Method


RetrieveSingleMessage Method

Retrieves a message from currently selected IMAP4 mailbox.

The message is received completely: including headers, body and any attachments.

If the method succeeds, return value is a Message object which fully represents the message.

To retrieve message headers only, use RetrieveSingleMessageHeaders method. To retrieve headers for multiple messages, use RetrieveEnvelopes or RetrieveEnvelopesEx methods (these methods also let you get more information about messages, such as flags).

objMessage = ObjectName.RetrieveSingleMessage(Index, AsUID)
Parameters: |
Index As Long | Message number or UID of the message to retrieve
AsUID As Boolean | If True, Index parameter must be specified as UIDs (unique-IDs). Otherwise, Index must be a message number
SetSeenFlag As Boolean | (optional) If True, \Seen flag will be set for this message upon downloading; otherwise, it won't. The default is True
Return value As MailBee.Message | On success, the method returns Message object which represents the message. On failure, return value is Nothing

Usage example:

' This sample retrieves last message in Inbox and displays its body
Dim Mailer, Message
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Message = Mailer.RetrieveSingleMessage(Mailer.MessageCount, False)
    If Not Message Is Nothing Then
      MsgBox Message.BodyText
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Message Object

RetrieveEnvelopes Method
RetrieveEnvelopesEx Method
RetrieveSingleMessageHeaders Method


RetrieveSingleMessageHeaders Method

Retrieves a message's headers from currently selected IMAP4 mailbox.

Also, this method is capable of retrieving portion of the message body. This allows client to preview message body.

To retrieve the whole message, use RetrieveSingleMessage method.

Note: It's more effective to get headers for multiple messages at once using RetrieveEnvelopes or RetrieveEnvelopesEx methods. These methods return collections of Envelope objects which are usually more suitable for message preview purposes (such as displaying message lists).

objMessage = ObjectName.RetrieveSingleMessageHeaders(Index, AsUID, [BodyPreviewSize])
Parameters: |
Index As Long | Message number or UID of the message to retrieve
AsUID As Boolean | If True, Index parameter must be specified as UIDs (unique-IDs). Otherwise, Index must be a message number
BodyPreviewSize As Long | (optional) Specifies the number of bytes of the message body to be returned in addition to message headers. If -1 or -2, the entire message is downloaded (-2 also sets \Seen flag). Default is 0
Return value As MailBee.Message | On success, the method returns Message object which represents the message. On failure, return value is Nothing

Usage example:

' This sample retrieves headers and first 500 bytes of the body of
' the last message in Inbox, and displays the retrieved portion of the body
Dim Mailer, Message
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Message = Mailer.RetrieveSingleMessageHeaders(Mailer.MessageCount, False, 500)
    If Not Message Is Nothing Then
      MsgBox Message.BodyText
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Envelope Object
Message Object

RetrieveEnvelopes Method
RetrieveEnvelopesEx Method
RetrieveSingleMessage Method


RetrieveTotalSize Method

Retrieves the total size (in bytes) of all messages in the currently selected IMAP4 mailbox.

lngSize = ObjectName.RetrieveTotalSize
Parameters: | None
Return value As Long | On success, the total size of all messages in the mailbox. On failure, return value is 0

Usage example:

' This sample displays total size of Inbox
Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    MsgBox Mailer.RetrieveTotalSize & " bytes"
  End If
  Mailer.Disconnect
End If

See Also:

MessageCount Property

RetrieveMessagesSize Method


Search Method

Searches the currently selected mailbox for messages which meet specified condition.

This method can also sort the results but the IMAP server must support SORT extension for that. Gmail and Outlook.com still don't support SORT to the moment (Feb 2015). If sorting is not supported by the server, this method will fail. To learn how check for an extension, see MoveMessages method's example. It checks for MOVE extension, checking for SORT can be done the same way.

Message numbers (or UIDs) are returned as array of numbers. Lower bound of the array is 1.

By default, this method just returns message numbers or UIDs for all messages in the mailbox. To search for specific items, specify non-empty search Condition.

Condition is a set of search criteria in IMAP4 format. Some popular search keys are listed below:

  • ALL - all messages
  • ANSWERED - messages with "\Answered" flag set
  • BEFORE <date> - messages whose Date is earlier then specified date
  • BODY <string> - messages that contain specified string in the body
  • DELETED - messages with "\Deleted" flag set
  • DRAFT - messages with "\Draft" flag set
  • FLAGGED - messages with "\Flagged" flag set
  • FROM <string> - messages that contain specified string in "From:"
  • HEADER <header name> <string> - messages that have specified header and specified string is contained in the header value
  • LARGER <number> - messages whose size larger than specified number
  • NEW - messages with "\Recent" flag set and "\Seen" flag not set. Identical to "(RECENT UNSEEN)"
  • NOT <search key> - messages that do not satisfy given search key
  • OLD - messages with "\Recent" flag not set
  • ON <date> - messages whose Date is within specified date
  • OR <search key 1> <search key 2> - messages that match at least key 1 or key 2
  • RECENT - messages with "\Recent" flag set
  • SEEN - messages with "\Sent" flag set
  • SUBJECT <string> - messages that contain specified string in "Subject:"
  • UID <message set> - messages whose UIDs are inside specified UID range
  • UNSEEN - messages with "\Seen" flag not set
Full list of allowed keys is described in RFC 3501 (INTERNET MESSAGE ACCESS PROTOCOL - VERSION 4rev1).

When multiple keys are specified, the result is the intersection (AND function) of all the messages that match those keys. For example, the criteria DELETED FROM "SMITH" SINCE 1-Feb-1994 refers to all deleted messages from Smith that were placed in the mailbox since February 1, 1994. A search key can also be a parenthesized list of one or more search keys (e.g., for use with the OR and NOT keys).

In all search keys that use strings, a message matches the key if the string is a substring of the field. The matching is case-insensitive.

Sorting rule can be "ARRIVAL", "CC", "DATE", "FROM", "SIZE", "SUBJECT", "TO". Sorting is in ascending order. To change order, add "REVERSE" before the key, e.g. "REVERSE ARRIVAL".

Multiple keys are allowed, e.g. "SUBJECT DATE" ("REVERSE" modifier affects only the immediate key after it, subsequent keys are not affected so you may need to specify it multiple times, e.g. "REVERSE SUBJECT REVERSE DATE").

arrIndices = ObjectName.Search(AsUID, [Condition], [Charset])
Parameters: |
AsUID As Boolean | If True, returned array will be array of UIDs (unique-IDs). Otherwise, message numbers will be returned
Condition As String | (optional) Search condition. Default is "ALL" (all messages in the currently selected mailbox returned)
Charset as String | (optional) Charset of the string that appear in search criteria. If not specified, default (US-ASCII) charset is assumed
OrderBy as String | (optional) Sorting rule. If not specified, SEARCH command instead of SORT is used and the messages get returned in their natural order in the mailbox
Return value As Variant | Array of Variant/Long, each value is UID or message number of the message. If error has occurred, return value is Empty

Usage example:

' This sample searches Inbox and retrieves unread messages only
Dim Mailer, SearchResults, Message, I
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    SearchResults = Mailer.Search(False, "UNSEEN") ' Get list of message numbers of unread messages
    If Not IsEmpty(SearchResults) Then
      For I = LBound(SearchResults) To UBound(SearchResults)
        Set Message = Mailer.RetrieveSingleMessage(SearchResults(I), False)
        If Not Message Is Nothing Then
          MsgBox Message.BodyText
        End If
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Envelope.UID Property

RetrieveEnvelopes Method
RetrieveEnvelopesEx Method
RetrieveSingleMessage Method


SelectMailbox Method

Selects the specified mailbox on the IMAP4 server.

Every IMAP4 account has at least "Inbox" mailbox. To get list of available mailboxes, use RetrieveMailboxes or RetrieveMailboxesEx method.

If mailbox names you're dealing with may contain non-English characters, please read UTF7EncodeMailboxNames topic to make sure everything's done right.

blnResult = ObjectName.SelectMailbox(MailboxName)
Parameters: |
MailboxName As String | Name of the mailbox to select
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample selects "Inbox" mailbox and displays total number of messages there

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    MsgBox Mailer.MessageCount & " messages in Inbox"
  End If
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Selected Property

ExamineMailbox Method
RetrieveMailboxes Method


SendCommand Method

Executes user-supplied command on the IMAP4 server.

This method sends the following request to the IMAP4 server:

Autogenerated command tag + User-supplied command + CRLF

E.g. if user-supplied command is LIST "" "", request generated by MailBee looks like:

MBC000002 LIST "" ""CRLF

CRLF is a line delimiter (vbCrLf constant).

To see exact look of the generated request, enable logging on and check the log file.

strServerResponse = ObjectName.SendCommand(Command)
Parameters: |
Command As String | Command text
Return value As String | Response generated by the server in return to user-supplied command

Usage example:

' This sample selects "Inbox" mailbox and displays total number of messages there

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  MsgBox Mailer.SendCommand("LIST """" """"")
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

EnableLogging Property
LogFilePath Property


SetFlagsForMessage Method

Sets the flags for a message in the currently selected mailbox.

To set flags for an arbitrary set of messages, specify MessageSet property and pass -1 as Index value. AsUID parameter is still honored when IDs are taken from MessageSet property (depending on AsUID value, they will be treated as UIDs or ordinal message numbers).

To use non-standard flags (like $Spam if it's supported by your IMAP server), use SetFlagsForMessageAsString method.

blnResult = ObjectName.SetFlagsForMessage(Index, AsUID, Flags, Action)
Parameters:
Index As Long | Message number of Unique-ID of the message to set flags for, or -1 to use MessageSet as input.
AsUID As Boolean | If False, Index is a message number. If True, Index is a Unique-ID.
Flags As Long Flags to be set for the message. Can be zero or any combination of the following:
  • 1 - Answered
  • 2 - Deleted
  • 4 - Draft
  • 8 - Flagged
  • 16 - Recent
  • 32 - Seen
Action As Long Indicates what to do with flags. Can be one of the following:
  • 1 - Set specified flags for the message
  • 2 - Remove specified flags from the message
  • 3 - Replace any existing flags with specified flags
Return value As Boolean | True if successful, False if error has occurred

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then

  If Mailer.SelectMailbox("Inbox") Then

    ' Remove 'Answered' and 'Deleted' flags for the first message
    If Mailer.SetFlagsForMessage(1, False, 1 + 2, 2) Then
      MsgBox "Removed 'Answered' and 'Deleted' flags for message #1"
    End If

  End If

  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

DeleteMessages Method
SetFlagsForMessageAsString Method


SetFlagsForMessageAsString Method

Sets the flags for a message in the currently selected mailbox.

To set flags for an arbitrary set of messages, specify MessageSet property and pass -1 as Index value. AsUID parameter is still honored when IDs are taken from MessageSet property (depending on AsUID value, they will be treated as UIDs or ordinal message numbers).

This method lets you specify the flags as a space-separated string. You can use non-standard flags which are not supported by MailBee. Standard flags starts with "\" while non-standard can be of any kind.

Note that there is no guarantee your server will support such flags. Also, some servers accept non-standard flags but do not save their value on permanent basis (i.e. flag value is not persistent).

blnResult = ObjectName.SetFlagsForMessageAsString(Index, AsUID, Flags, Action)
Parameters:
Index As Long | Message number of Unique-ID of the message to set flags for, or -1 to use MessageSet as input.
AsUID As Boolean | If False, Index is a message number. If True, Index is a Unique-ID.
Flags As String | Flags to be set for the message. A string like "\Answered \Seen $Starred" (allows for non-standard flags if supported by the server).
Action As Long Indicates what to do with flags. Can be one of the following:
  • 1 - Set specified flags for the message
  • 2 - Remove specified flags from the message
  • 3 - Replace any existing flags with specified flags
Return value As Boolean | True if successful, False if error has occurred

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then

  If Mailer.SelectMailbox("Inbox") Then

    ' Mark email as spam
    If Mailer.SetFlagsForMessage(1, False, "$Spam", 1) Then
      MsgBox "Email marked as spam with $Spam flag"
    End If

  End If

  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

DeleteMessages Method
SetFlagsForMessage Method


Subscribe Method

Subscribes specified mailbox.

Many mail programs check subscribed mailboxes only.

To get list of subscribed mailboxes, use call RetrieveMailboxes method with SubscribedOnly parameter set to True.

If mailbox names you're dealing with may contain non-English characters, please read UTF7EncodeMailboxNames topic to make sure everything's done right.

blnResult = ObjectName.Subscribe(MailboxName)
Parameters: |
MailboxName As String | Name of the mailbox to subscribe
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample subscribes "Archive" mailbox. It's assumed this mailbox already exists

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Mailer.Subscribe("Archive")
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

RetrieveMailboxes Method
Unsubscribe Method


ToUTF7 Method

Encodes the specified string into UTF-7M.

Usually, UTF-7M is used to encode mailbox names by IMAP servers. Although by default MailBee encodes mailbox names automatically, you may disable automatic encoding via UTF7EncodeMailboxNames property and perform encoding manually using this method.

Moreover, if you disabled automatic encoding mailbox names, but your IMAP server requires mailbox names to be encoded, you should encode mailbox names before passing them to IMAP server. To reference already existing mailboxes (which were retrieved from the IMAP server), use MailBox.OriginalName property.

strUTF7 = ObjectName.ToUTF7(Src)
Parameters: |
Src As String | Source text string
Return value As String | UTF-7-Modified version of the source string.

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
MsgBox Mailer.ToUTF7("Name with international or special chars")

See Also:

FromUTF7 method
UTF7EncodeMailboxNames property


Unsubscribe Method

Unsubscribes specified mailbox.

Many mail programs check subscribed mailboxes only.

To get list of subscribed mailboxes, use call RetrieveMailboxes method with SubscribedOnly parameter set to True.

If mailbox names you're dealing with may contain non-English characters, please read UTF7EncodeMailboxNames topic to make sure everything's done right.

blnResult = ObjectName.Unsubscribe(MailboxName)
Parameters: |
MailboxName As String | Name of the mailbox to subscribe
Return value As Boolean | True if successful, False if error has occurred. You can check ErrDesc property or log file to get more detailed error information

Usage example:

' This sample unsubscribes "Archive" mailbox. It's assumed this mailbox already exists

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox

Mailer.EnableLogging = True ' Logging helps to discover any problems
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"

Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Mailer.Unsubscribe("Archive")
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

RetrieveMailboxes Method
Unsubscribe Method


OnAlert Event

Fires when there is an [ALERT] message in the IMAP4 server response.

Parameters: |
AlertText As String | Alert message text
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue processing. You can set it to False to immediately abort IMAP4 session and disconnect from IMAP4 server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
' Early binding and "WithEvents" syntax required for handling MailBee's events
Dim WithEvents objIMAP4 As MailBee.IMAP4

Private Sub Command1_Click()
  Dim Envelopes As MailBee.Envelopes
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"
  objIMAP4.EnableEvents = True ' Enable Async mode
  If objIMAP4.Connect("mailserver.com", 143, "MyName", "MyPassword") Then ' Long-run operation
    If objIMAP4.SelectMailbox("Inbox") Then ' Long-run operation
      Set Envelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False) ' Long-run operation
    End If
    objIMAP4.Disconnect ' Long-run operation
  End If
End Sub

' Respond to MailBee's OnAlert event
Private Sub objIMAP4_OnAlert(ByVal AlertText As String, Proceed As Boolean)
  MsgBox AlertText
End Sub

Private Sub Form_Load()
  Set objIMAP4 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If objIMAP4 Is Nothing Then Exit Sub
  If objIMAP4.Busy Then objIMAP4.Abort ' Cancel IMAP4 session on exit
End Sub

See Also:

EnableEvents Property

OnReceiveData Event
OnStatusChange Event


OnEnvelopeDownloaded Event

Fires when IMAP4 object parses an envelope (FETCH response) in the data received from the IMAP server.

This event lets you get e-mail messages with their envelopes not waiting for the entire operation to complete. This only makes sense when you download multiple messages at once.

Parameters: |
DataLength As Long | Received envelope size in bytes
EnvelopeDownloaded As Envelope | Received envelope
MessageNumber As Long | Ordinal number (index) of the downloaded message in the mailbox. The first e-mail in the mailbox has index=1.
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue processing. You can set it to False to immediately abort IMAP4 session and disconnect from IMAP4 server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
' Early binding and "WithEvents" syntax required for handling MailBee's events
Dim WithEvents objIMAP4 As MailBee.IMAP4

Private Sub Command1_Click()
  Dim Envelopes As MailBee.Envelopes
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"
  objIMAP4.EnableEvents = True ' Enable Async mode
  If objIMAP4.Connect("mailserver.com", 143, "MyName", "MyPassword") Then ' Long-run operation
    If objIMAP4.SelectMailbox("Inbox") Then ' Long-run operation
      Set Envelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False) ' Long-run operation
    End If
    objIMAP4.Disconnect ' Long-run operation
  End If
End Sub

' Respond to MailBee's OnEnvelopeDownloaded event and print Subject of the messages being received
Private Sub objIMAP4_OnReceiveData(ByVal DataLength As Long, ByVal EnvelopeDownloaded As MailBee.Envelope, ByVal MessageNumber As Long, Proceed As Boolean)
  Debug.Print EnvelopeDownloaded.Subject
End Sub

Private Sub Form_Load()
  Set objIMAP4 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If objIMAP4 Is Nothing Then Exit Sub
  If objIMAP4.Busy Then objIMAP4.Abort ' Cancel IMAP4 session on exit
End Sub

See Also:

EnableEvents Property

OnReceiveData Event


OnIdle Event

Fires when another 10 millisecond period elapses during idling.

This event can only issued when Idle method is in progress. Because Idle method itself never stops, the correct way to stop it without breaking the connection is to set Proceed value of your OnIdle event handler to False.

Parameters: |
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue idling. You can set it to False to finish idling by issuing DONE command to the server (the IMAP connection will still be opened, so that you can issue other IMAP commands then)
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

The example is available in Idle method topic.

See Also:

Idle Method

OnAlert Event
OnStatusChange Event


OnReceiveData Event

Fires when IMAP4 object receives new chunk of data from the IMAP server.

If you need the actual data being received, not just its length, use GetLastReceivedDataChunk method.

Parameters: |
BytesReceived As Long | Received data chunk size in bytes
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue processing. You can set it to False to immediately abort IMAP4 session and disconnect from IMAP4 server
Remarks: | Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
' Early binding and "WithEvents" syntax required for handling MailBee's events
Dim WithEvents objIMAP4 As MailBee.IMAP4

Private Sub Command1_Click()
  Dim Envelopes As MailBee.Envelopes
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"
  objIMAP4.EnableEvents = True ' Enable Async mode
  If objIMAP4.Connect("mailserver.com", 143, "MyName", "MyPassword") Then ' Long-run operation
    If objIMAP4.SelectMailbox("Inbox") Then ' Long-run operation
      Set Envelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False) ' Long-run operation
    End If
    objIMAP4.Disconnect ' Long-run operation
  End If
End Sub

' Respond to MailBee's OnReceiveData event and print how many data bytes received
Private Sub objIMAP4_OnReceiveData(ByVal BytesReceived As Long, Proceed As Boolean)
  Debug.Print BytesReceived & " bytes received"
End Sub

Private Sub Form_Load()
  Set objIMAP4 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If objIMAP4 Is Nothing Then Exit Sub
  If objIMAP4.Busy Then objIMAP4.Abort ' Cancel IMAP4 session on exit
End Sub

See Also:

EnableEvents Property

OnAlert Event
OnStatusChange Event


OnStatusChange Event

Fires when mailbox status is changed: new message arrives, existing message is deleted, number of existing or recent messages changes, etc.

Often, this event is used during idling (see Idle method for details and code example).

Parameters:
EventCode As Long Type of event:
  • 1 - Expunge. A message was expunged. Message parameter contains the message number
  • 2 - Reserved for future use
  • 3 - Exists. Number of existing messages (MessageCount property) changed. Value parameter contains new number of existing messages
  • 4 - Recent. Number of recent messages (RecentCount property) changed. Value parameter contains new number of recent messages
Message As Long | Message number. Only valid for Expunge event
Value as Long | Number of messages. Only valid for Exists and Recent events
ByRef Proceed As Boolean | Default value is True, which tells MailBee to continue processing. You can set it to False to immediately abort IMAP4 session and disconnect from IMAP4 server
Remarks: Events are turned off by default. To enable them, set EnableEvents to True

Usage example:

Option Explicit
' Early binding and "WithEvents" syntax required for handling MailBee's events
Dim WithEvents objIMAP4 As MailBee.IMAP4

Private Sub Command1_Click()
  Dim Envelopes As MailBee.Envelopes
  Set objIMAP4 = CreateObject("MailBee.IMAP4")
  objIMAP4.LicenseKey = "put your license key here"
  objIMAP4.EnableEvents = True ' Enable Async mode
  If objIMAP4.Connect("mailserver.com", 143, "MyName", "MyPassword") Then ' Long-run operation
    If objIMAP4.SelectMailbox("Inbox") Then ' Long-run operation
      Set Envelopes = objIMAP4.RetrieveEnvelopes(1, objIMAP4.MessageCount, False) ' Long-run operation
    End If
    objIMAP4.Disconnect ' Long-run operation
  End If
End Sub

' Respond to MailBee's OnStatusChange event
Private Sub objIMAP4_OnStatusChange(ByVal EventCode As Long, ByVal Message As Long, ByVal Value As Long, Proceed As Boolean)
  Select Case EventCode
  Case 1:
    Debug.Print "Message #" & Message & " was expunged"
  Case 3:
    Debug.Print Value & " messages in mailbox"
  Case 4:
    Debug.Print Value & " recent messages"
  End Select
End Sub

Private Sub Form_Load()
  Set objIMAP4 = Nothing
End Sub

Private Sub Form_Unload(Cancel As Integer)
  If objIMAP4 Is Nothing Then Exit Sub
  If objIMAP4.Busy Then objIMAP4.Abort ' Cancel IMAP4 session on exit
End Sub

See Also:

EnableEvents Property

OnAlert Event
OnReceiveData Event


SMIME Object

The SMIME object is used for the e-mails securing according to the S/MIME standard. It supports such features as digital signing of the new e-mails, verification of the digital signatures, e-mails encryption and decryption, etc.

Syntax

SMIME.property|method

Properties
AlgorithmEncryption | Gets or sets the name of the message encryption algorithm.
AlgorithmSigning | Gets or sets the name of message signing algorithm.
CSP | Gets or sets the name of Cryptographic Service Provider.
Encrypted | Indicates if the message is encrypted.
Licensed | Indicates if the SMIME object can be used (the valid LicenseKey value has been assigned and the trial period is not yet expired, or the registered version is used).
LicenseKey | Sets the license key for the instance of MailBee.SMIME object.
Message | Gets or sets the Message object which is processed by the SMIME object.
SenderCert | Gets the CertInfo object which contains the information about the certificate of the message sender.
Signed | Indicates if the message has a digital signature.
SignerCert | Gets the CertInfo object which contains the information about the certificate of the message signer.
SMIMEError | Gets the code of the last occurred SMIME error.
SMIMESpecificError | Gets the code of the last occurred SMIME-specific error which was returned by Windows API.
Verified | Indicates if the authenticity of the message signer was verified successfully and the message was not altered during transmission.
Methods
AddRecipientCert | Adds the certificate having the specified parameters to the list of certificates which are used for subsequent encryption of the message.
AddSignerToStore | Extracts the certificate of the entity which signed the message, and then places it into the storage which was specified earlier using the SelectSignerCertStore method.
Decrypt | Decrypts the encrypted message.
DecryptAndVerify | Decrypts the encrypted message and verifies it.
Encrypt | Encrypts the message with the public keys contained in the recipient's certificates which were selected earlier using the AddRecipientCert method.
Reset | Resets the SMIME object to its default state.
SelectSenderCert | Specifies the certificate to be used to sign a new message.
SelectSignerCertStore | Specifies the certificate storage where to save the certificate of the entity which signed the message being currently processed.
Sign | Adds the digital signature to the message.
SignAndEncrypt | Signs the message using the private key contained in the sender's certificate and encrypts this message using the public key contained in the recipient's certificate.
Verify | Verifies the authenticity of the message signer and examines the message integrity.

Remarks

The developer can reuse a single instance of SMIME object to process multiple messages. Just use the Reset method before processing the next message.

NOTE: Windows 2000 Pro may show certificate selection dialog in some scenarios of using private keys. This may cause problems in server environments when no user interaction with the system is expected (such as ASP). Windows 2000 Server, Windows XP, and Windows 2003 server do not have this problem.

[Visual Basic]
Set objMessage = CreateObject("MailBee.SMIME")

[ASP]
Set objMessage = Server.CreateObject("MailBee.SMIME")

Example

The following example demonstrates how the message can be downloaded from file, signed with public recipient's certificate, encrypted with its private certificate (obtained from the system storage) and saved to file. The message could be received from any other source (such as POP3 or IMAP4 object).

[Visual Basic]

Dim objMsg, objSMIME

' Create the new Message object
Set objMsg = CreateObject("MailBee.Message")

' Create the new SMIME object
Set objSMIME = CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further encryption and signing
Set objSMIME.Message = objMsg

' Add the recipient's certificate for the message encryption
objSMIME.AddRecipientCert "AddressBook", 0, "", "", "", objMsg.PureToAddr

' Select the sender's certificate for the message signing
objSMIME.SelectSenderCert "MY", 0, "", "", "", objMsg.PureFromAddr, ""

' Sign and encrypt the message
objSMIME.SignAndEncrypt

' Check if any errors occurred
If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
    ' Display the code of the last occurred error
    MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
      objSMIME.SMIMESpecificError
End If

' Get the signed and encrypted message from the SMIME object
Set objMsg = objSMIME.Message

' Save the message to disk
objMsg.SaveMessage "mail_dst.eml"

[ASP]
<%
Dim objMsg, objSMIME

' Create the new Message object
Set objMsg = Server.CreateObject("MailBee.Message")

' Create the new SMIME object
Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further encryption and signing
Set objSMIME.Message = objMsg

' Add the recipient's certificate for the message encryption
objSMIME.AddRecipientCert "AddressBook", 0, "", "", "", objMsg.PureToAddr

' Select the sender's certificate for the message signing
objSMIME.SelectSenderCert "MY", 0, "", "", "", objMsg.PureFromAddr, ""

' Sign and encrypt the message
objSMIME.SignAndEncrypt

' Check if any errors occurred
If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
    ' Display the code of the last occurred error
    Response.Write "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
      objSMIME.SMIMESpecificError
End If

' Get the signed and encrypted message from the SMIME object
Set objMsg = objSMIME.Message

' Save еру message to disk
objMsg.SaveMessage "mail_dst.eml"
%>

See Also

Message Object, CertInfo Object

Send feedback to AfterLogic


AlgorithmEncryption Property

Gets or sets the name of the message encryption algorithm. RSA algorithm is used by default. Please note your Cryptographic Service Provider must support the specified algorithm.

Value Type: | String
Parameters: | None

Usage example:

' This example displays the name of the default encryption algorithm.

Dim objSMIME

' Using Visual Basic to create the object
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the object
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Display the name of the default encryption algorithm
' In ASP use Response.Write instead of MsgBox
MsgBox objSMIME.AlgorithmEncryption

See Also:

AlgorithmSigning Property, CSP Property


AlgorithmSigning Property

Gets or sets the name of message signing algorithm. SHA1RSA algorithm is used by default. Please note your Cryptographic Service Provider must support the specified algorithm.

Value Type: | String
Parameters: | None

Usage example:

' This example displays the name of the default signing algorithm.

Dim objSMIME

' Using Visual Basic to create the object
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the object
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Display the name of the default signing algoritjm
' In ASP use Response.Write instead of MsgBox
MsgBox objSMIME.AlgorithmSigning

See Also:

AlgorithmEncryption Property, CSP Property


CSP Property

Gets or sets the name of Cryptographic Service Provider. The default value is Microsoft Enhanced Cryptographic Provider v1.0.

Value Type: | String
Parameters: | None

Usage example:

' This example displays the name of Cryptographic Service Provider.

Dim objSMIME

' Using Visual Basic to create the object
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the object
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Display the name of Cryptographic Service Provider
' In ASP use Response.Write instead of MsgBox
MsgBox objSMIME.CSP

See Also:

AlgorithmEncryption Property, AlgorithmSigning Property


Encrypted Property

True if the message is encrypted; otherwise, False.

If the message is encrypted, the developer can use the Decrypt or DecryptAndVerify method to decrypt it.

Also, the developer can use the AlgorithmEncryption property to get the name of algorithm which was used to encrypt this message.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only.

Usage example:

' This example loads the message from file and checks if this message is encrypted.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Check if the message is encrypted
MsgBox objSMIME.Encrypted

See Also:

Signed Property, Verified Property


Licensed Property

True if the SMIME object can be used (the valid LicenseKey value has been assigned and the trial period is not yet expired, or the registered version is used); otherwise, False.

This property is always set to True when the permanent license key is used. In other case, when the trial license key is used, this property contains True until the trial period is not yet expired.

To determine the license status (the registered version is used, the number of days trial version will function yet) the developer should enable logging on and look into the log file.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only.

Usage example:

' This example checks if the SMIME object can be used.

Dim objSMIME

' Using visual basic to the create object
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the object
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Check if the valid license key was specified
If objSMIME.Licensed Then
  ' In ASP use Response.Write instead of MsgBox
  MsgBox "SMIME object is ready for use"
End If

See Also:

LicenseKey Property


LicenseKey Property

Sets the license key for MailBee S/MIME component. This property must contain the correct license key value in order to successfully use the SMIME object.

Value Type: | String
Parameters: | None
Remarks: | To check if the correct license key value was assigned, the developer can use the Licensed property.

Usage example:

' This example checks if the specified license key is valid.

Dim objSMIME

' Using Visual Basic to create the SMIME object
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the SMIME object
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Check if the specified license key is valid
If objSMIME.Licensed Then
  ' In ASP use Response.Write instead of MsgBox
  MsgBox "SMIME object is ready for use"
End If

See Also:

Licensed Property


Message Property

Gets or sets the Message object which is processed by the SMIME object.

Value Type: Message object
Parameters: None
Remarks:

When the developer passes a reference to some Message object to this property, a copy of this Message object is created and assigned to this property.

Thus, all subsequent operations over this object (such as encryption, decryption, signing, etc) alter this copy but not the original Message object.

Usage example:

' This example loads the message from file, encrypts and saves it to disk.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for further processing
Set objSMIME.Message = objMsg

' Add the recipient's certificate which should be used for the message encryption
If objSMIME.AddRecipientCert ("AddressBook", 0, "", "", "", objMsg.PureToAddr) Then
    ' Try to encrypt the message
    If objSMIME.Encrypt Then
        ' Get the encrypted message from SMIME object
        Set objMsg = objSMIME.Message

        ' Save the encrypted message to file
        objMsg.SaveMessage "mail_dst.eml"
    End If
End If

See Also:

Message Object


SenderCert Property

Gets the CertInfo object which contains the information about the message sender's certificate.

Value Type: CertInfo Objec t
Parameters: None
Remarks:

In SMIME, "message sender" is an entity which composes a new message and signs it. On the other hand, "message signer" is an entity which signed a message which was received rather than is being created now.

In other words, the developer should examine the SignerCert property when processing a message which was received from mail server. The only use of SenderCert property is to collect information about the certificate which is to be used to sign a new message (for instance, if the developer wants to find out the details of the certificate set by SelectSenderCert method).

Usage example:

' This example loads the message from file, selects recipient's certificate from the storage and displays to whom this certificate was issued.

Dim objMsg, objSMIME

'Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Select sender's certificate from the personal user's storage
objSMIME.SelectSenderCert "MY", 0, "", "", "", objMsg.PureFromAddr, ""

' Displays to whom this certificate was issued
' In ASP use Response.Write instead of MsgBox
MsgBox (objSMIME.SenderCert.IssuedTo)

See Also:

SignerCert Property, SelectSenderCert Method, CertInfo Object


Signed Property

True if the message has a digital signature; otherwise, False.

If the message is signed, the developer can use the Verify method to make sure the message was written by the known author and it was not altered during the transmission.

Also, the developer can use the AddSignerToStore method to save the certificate of the message sender to the storage for the further use.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only.

Usage example:

' This example loads the message from file, verifies it and shows to whom the sender's certificate was issued.

Dim objMsg, objSMIME

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Check if the message is signed
if objSMIME.Signed Then
    ' Verify the message
    objSMIME.Verify

    ' Display to whom the sender's certificate was issued
    ' In ASP use Response.Write instead of MsgBox
    MsgBox (objSMIME.SenderCert.IssuedTo)
End If

See Also:

Sign Method, Verify Method, AddSignerToStore Method


SignerCert Property

Gets the CertInfo object which contains the information about the certificate of the entity which signed the message assigned to the SMIME object.

Value Type: | CertInfo Object
Parameters: | None
Remarks: | The information about the signer's certificate is available only for the verified messages. The developer can use the Verified property to check if the message is verified and the Verify or DecryptAndVerify method to verify the message.

Usage example:

' This example loads the message from file and if it's signed - shows to whom this certificate was issued.

Dim objMsg, objSMIME

'Using visual basic to create object
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")
'Using ASP to create object
'Set objSMIME = Server.CreateObject("MailBee.SMIME")
'In ASP use Response.Write instead of MsgBox

objSMIME.LicenseKey = "put your license key here"

' Load E-mail message from file
objMsg.ImportFromFile "mail_src.eml"

' Set message for SMIME
Set objSMIME.Message = objMsg

' If message signed, verify message and obtain information about sender certificate
if objSMIME.Signed Then
    objSMIME.Verify

    ' Obtain information about sender
    MsgBox (objSMIME.SignerCert.IssuedTo)
End If

See Also:

SenderCert Property, Verify Method, DecryptAndVerify Method, CertInfo Object


SMIMEError Property

Gets the code of the last occurred SMIME error.

Value Type: Long
Parameters: None
Remarks:

MailBee supports the following error codes:

  • SMIME_OK = 0 - no SMIME errors occurred.
  • SMIME_INVALID_SIGNATURE = 41 - the message has incorrect digital signature
  • SMIME_STORE_NOT_FOUND = 42 - the specified certificate's storage was not found
  • SMIME_ENCRYPTION_FAILED = 43 - the encryption of the message has failed
  • SMIME_DECRYPTION_FAILED = 44 - the decryption of the message has failed
  • SMIME_SIGN_FAILED = 45 - the signing of the message has failed
  • SMIME_WRONG_PASW = 46 - the wrong password was specified to access the PFX certificate's storage OR FromAddr does not match the e-mail address in the certificate (if latter, SMIMESpecificError would be 86)
  • SMIME_CERT_NOT_FOUND = 47 - the digital certificate was not found
  • SMIME_ERR_NOT_LICENSED = 48 - the specified license key is invalid
  • SMIME_ERR_SPECIFIC = 49 - the specific SMIME error has occurred.

The developer can get the code of the last occurred specific SMIME error using the SMIMESpecificError property.

Usage example:

' This example loads the message from file and tries to add the recipient's certificate to the storage.
' If the adding fails, the code of the occurred SMIME error is displayed.

Dim objMsg, objSMIME

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Add the recipient's certificate to the storage
objSMIME.AddRecipientCert "AddressBook", 0, "", "", "", objMsg.PureToAddr

' Display the code of the occurred SMIME error
' In ASP use Response.Write instead of MsgBox
MsgBox objSMIME.SMIMEError

See Also:

SMIMESpecificError Property


SMIMESpecificError Property

Gets the code of the last occurred SMIME-specific error which was returned by Windows API. If no specific error occurred, this property contains 0.

Value Type: | Long
Parameters: | None
Remarks: | The developer can use the SMIMEError property to check if the specific SMIME error occurred. In this case, SMIMEError property contains 49.

Usage example:

' This example loads the message from file and tries to add the recipient's certificate to the storage.
' If the adding fails, the code of the occurred specific error is displayed.

Dim objMsg, objSMIME

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Add the recipient's certificate to the storage
objSMIME.AddRecipientCert "AddressBook", 0, "", "", "", objMsg.PureToAddr

' Check if the specific SMIME error occurred
If objSMIME.SMIMEError = 49 Then
    ' In ASP use Response.Write instead of MsgBox
    ' Display the code of the occurred specific error
    MsgBox objSMIME.SMIMESpecificError
End If

See Also:

SMIMEError Property


Verified Property

True if the authenticity of the message signer was verified suceesfully and the message was not altered during transmission; otherwise, False.

To verify the message the developer can use Verify or DecryptAndVerify method. Only signed messages can be verified.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only.

Usage example:

' This example loads the message from file,

Dim objMsg, objSMIME

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message fro the further processing
Set objSMIME.Message = objMsg

' Check if the message is signed
If objSMIME.Signed Then
' Verify the message
    objSMIME.Verify

    ' Check if the message was verified successfully
    If objSMIME.Verified Then
        ' Display to whom was the sender's certificate issued
        ' In ASP use Response.Write instead of MsgBox
        MsgBox (objSMIME.SenderCert.IssuedTo)
    End If
End If

See Also:

Signed Property, Verify Method, DecryptAndVerify Method


AddRecipientCert Method

Adds the certificate having the specified parameters to the list of certificates which are used for subsequent encryption of the message.

To encrypt a message, the developer must specify at least one public certificate of the recipient. The method performs search over the the specified certificate storage accordingly the specified search criteria and picks the first matching certificate. If the message has multiple recipients, this method must be called for each recipient.

When the message gets delivered to the recipients, they will be able to decrypt it using their private certificates assuming you encrypted it using their public certificates.

[Visual Basic]

blnResult = ObjectName.AddRecipientCert(Store, StoreType, IssuedTo, IssuedBy, FriendlyName, Email)

Parameters:
Store As String

The name of the digital certificate's storage. The following names are supported for the system storage (REGISTRY_STORE):

  • "MY" - the personal user's certificates storage
  • "AddressBook" - other people certificates storage
  • "CA" - Intermediate Certification Authorities
  • "Root" - Trusted Root Certification Authorities

If empty, Mailbee uses "AddressBook" value.
StoreType As Long

The type of the digital certificate's storage. MailBee supports the next types of the certificate's storages:

  • REGISTRY_STORE = 0 - standard system storage which belongs to the current user
  • FILE_STORE = 1 - file storage
  • PFX_STORE = 2 - PFX file
IssuedTo As String | The name of a person or organization to whom the certificate was issued. If empty, will not perform certificate search by this field.
IssuedBy As String | The name of a person or organization by whom the certificate was issued. If empty, will not perform certificate search by this field.
FriendlyName As String | The friendly name of a person to whom the certificate was issued. If empty, will not perform certificate search by this field.
Email As String | The e-mail address associated with the certificate. If empty, will not perform certificate search by this field.
PfxPassword As String | The PFX file password, in case of a PFX_STORE.
Return value As Boolean | True if successful, False if error has occurred or no certificate matching the specified search criteria has been found.

Usage example:

' This example loads the message from file, encrypts it and saves it to disk. It's assumed the message has only a single recipient.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Add the recipient's certificate for the message encryption from the system storage
If objSMIME.AddRecipientCert("AddressBook", 0, "", "", "", objMsg.PureToAddr) Then
  ' Encrypt the message
  objSMIME.Encrypt
End If

' Check if any errors occurred
If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
    ' Display the code of the last occurred error
    ' In ASP use Response.Write instead of MsgBox
    MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
      objSMIME.SMIMESpecificError
End If

' Get the encrypted message
Set objMsg = objSMIME.Message

' Save the message to disk
objMsg.SaveMessage "mail_dst.eml"

See Also:

SelectSenderCert Method, AddSignerToStore Method


AddSignerToStore Method

Extracts the certificate of the entity which signed the message, and then places it into the storage which was specified earlier using the SelectSignerCertStore method.

[Visual Basic]

blnResult = ObjectName.AddSignerToStore

Parameters: | None
Return value As Boolean | True if successful, False if error has occurred.
Remarks: | In the future (if the certificate of this sender is already available in the certificates storage), the authenticity of the sender which signed the message can be easily verified using the Verify method.

Usage example:

' This example loads the signed message from file and adds the signer's certificate to the personal storage of the current user

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Check if the message is signed and select the personal storage of the current user
If objSMIME.Signed And (objSMIME.SelectSignerCertStore ("MY", REGISTRY_STORE)) Then
    ' Add the signer's certificate to the selected storage
    objSMIME.AddSignerToStore
End If

' Check if any errors occurred
If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
    ' Display the code of the last occurred error
    ' In ASP use Response.Write instead of MsgBox
    MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
      objSMIME.SMIMESpecificError
End If

See Also:

SelectSignerCertStore Method, Verify Method, AddRecipientCert Method


Decrypt Method

Decrypts the encrypted message.

You can optionally specify the certificate store where to find the certificate suitable for decryption.

[Visual Basic]

blnResult = ObjectName.Decrypt([Store], [StoreType], [PfxPassword])
Parameters:
Store As String

(optional) The name of the certificate's storage. The following names are supported for the system storage (REGISTRY_STORE):

  • MY - the personal user's certificates storage
  • AddressBook - other people certificates storage
  • CA - Intermediate Certification Authorities
  • Root - Trusted Root Certification Authorities

When using a file storage (FILE_STORE or FILE_PFX_STORE) this parameter should contain the name of this file storage.

The default value is "MY".
StoreType As Long

(optional) The type of the certificate's storage. MailBee supports the following types of certificate's storages:

  • REGISTRY_STORE = 0 - the standard system storage which belongs to the current user (not applicable for web applications which are usually run under the special system user, not the interactive user)
  • FILE_STORE = 1 - file storage
  • FILE_PFX_STORE = 2 - password-protected PFX file storage

The default value is 0.
PfxPassword As String | (optional) The password which should be used to access the certificates storage if it's a PFX file. The default value is an empty string.
Return value As Boolean | True if successful, False if error has occurred and the message was not decrypted.
Remarks:

To decrypt the message, private key for the certificate which was used to encrypt this message must be available in the certificate storage.

If the message is not encrypted nothing happens. To check if the message is encrypted the developer can use the Encrypted property.

Usage example:

' This example loads the encrypted message from file and decrypts it
Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Check if the message is encrypted
If objSMIME.Encrypted Then
    ' Decrypt the message
    objSMIME.Decrypt

    ' Check if any errors occurred
    If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
        ' Display the code of the last occurred error
        ' In ASP use Response.Write instead of MsgBox
        MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
          objSMIME.SMIMESpecificError
    End If
End If

See Also:

DecryptAndVerify Method, Encrypted Property


DecryptAndVerify Method

Decrypts the encrypted message and verifies its signature if it's present in the message.

You can optionally specify the certificate store where to find the certificate suitable for decryption.

[Visual Basic]

blnResult = ObjectName.DecryptAndVerify([Store], [StoreType], [PfxPassword])
Parameters:
Store As String

(optional) The name of the certificate's storage. The following names are supported for the system storage (REGISTRY_STORE):

  • MY - the personal user's certificates storage
  • AddressBook - other people certificates storage
  • CA - Intermediate Certification Authorities
  • Root - Trusted Root Certification Authorities

When using a file storage (FILE_STORE or FILE_PFX_STORE) this parameter should contain the name of this file storage.

The default value is "MY".
StoreType As Long

(optional) The type of the certificate's storage. MailBee supports the following types of certificate's storages:

  • REGISTRY_STORE = 0 - the standard system storage which belongs to the current user (not applicable for web applications which are usually run under the special system user, not the interactive user)
  • FILE_STORE = 1 - file storage
  • FILE_PFX_STORE = 2 - password-protected PFX file storage

The default value is 0.
PfxPassword As String | (optional) The password which should be used to access the certificates storage if it's a PFX file. The default value is an empty string.
Return value As Boolean | True if successful, False if error has occurred.
Remarks:

Only signed messages can be decrypted and verified. If the message is not encrypted nothing happens.

To check if the message was encrypted or verified the developer can use the Encrypted or Verified properties.

Usage example:

' This example loads the encrypted message from file, decrypts and verifies this message.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Check if the message is encrypted
If objSMIME.Encrypted Then
    ' Decrypt and verify the message
    objSMIME.DecryptAndVerify

    ' Check if any errors occurred
    If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
        ' Display the code of the last occurred error
        ' In ASP use Response.Write instead of MsgBox
        MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
          objSMIME.SMIMESpecificError
    End If
End If

See Also:

Decrypt Method, Verify Method


Encrypt Method

Encrypts the message with the public keys contained in the recipient's certificates which were selected earlier using the AddRecipientCert method.

[Visual Basic]

blnResult = ObjectName.Encrypt

Parameters: | None
Return value As Boolean | True if successful, False if error has occurred.
Remarks: | The recipients can decrypt the encrypted message using their private keys. The developer can use the Encrypted property to check if the message is encrypted.

Usage example:

' This example loads the message from file and encrypts it with recipient's certificate. It also shows the code of the error if it occurred.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")
' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the  message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Add recipient's certificate to certificate's list
If objSMIME.AddRecipientCert ("AddressBook", 0, "", "", "", objMsg.PureToAddr) Then
    ' Encrypt the message
    objSMIME.Encrypt
End If

' Check if any errors occurred
If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
    ' Display the code of the last occurred error
    ' In ASP use Response.Write instead of MsgBox
    MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
      objSMIME.SMIMESpecificError
End If

See Also:

SignAndEncrypt Method


Reset Method

Resets the SMIME object to its default state. This method can be used to process multiple messages.

[Visual Basic]

blnResult = ObjectName.Reset

Parameters: | None
Return value As Boolean | True if successful, False if error has occurred.
Remarks: | After using the Reset method the SMIME object should be re-initialized before using it again.

Usage example:

' This example loads 5 messages from files, encrypts and saves them to disk. Only one instance of the SMIME object is used.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Iterate through the messages
For i = 1 To 5
    ' Load the message from file
    objMsg.ImportFromFile "mail_src" & i & ".eml"

    ' Specify the message for the further processing
    Set objSMIME.Message = objMsg

    ' Add the recipient's certificate for the message encryption
    If objSMIME.AddRecipientCert ("AddressBook", 0, "", "", "", objMsg.PureToAddr) Then
        ' Encrypt the message
        objSMIME.Encrypt
    End If

    ' Check if any errors occurred
    If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
        ' Display the code of the last occurred error
        ' In ASP use Response.Write instead of MsgBox
        MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
          objSMIME.SMIMESpecificError
    End If

    ' Get the encrypted message from the SMIME object
    Set objMsg = objSMIME.Message

    ' Save the encrypted message to disk
    objMsg.SaveMessage "mail_dst" & i &".eml"

    ' Reset the SMIME object
    objSMIME.Reset
Next

See Also:

SMIME Object


SelectSenderCert Method

Specifies the certificate to be used to sign a new message.

To sign a new message, the developer must first specify a certificate with this method. The method performs search over the the specified certificate storage accordingly the specified search criteria and picks the first matching certificate. Once the certificate is selected, you can actually call the Sign method.

For this method to work, you must select the certificate which has the same associated email address as the one you specified with FromAddr Property of the mail message to be signed.

[Visual Basic]

blnResult = ObjectName.SelectSenderCert(Path, StoreType, IssuedTo, IssuedBy, FriendlyName, Email, PfxPassword)
Parameters:
Path As String

The name of the certificate's storage. The following names are supported for the system storage (REGISTRY_STORE):

  • MY - the personal user's certificates storage
  • AddressBook - other people certificates storage
  • CA - Intermediate Certification Authorities
  • Root - Trusted Root Certification Authorities

When using a file storage (FILE_STORE or FILE_PFX_STORE) this parameter should contain the name of this file storage.

If empty , MailBee uses "MY" value.
StoreType As Long

The type of the certificate's storage. MailBee supports the following types of certificate's storages:

  • REGISTRY_STORE = 0 - the standard system storage which belongs to the current user (not applicable for web applications which are usually run under the special system user, not the interactive user)
  • FILE_STORE = 1 - file storage
  • FILE_PFX_STORE = 2 - password-protected PFX file storage
IssuedTo As String | The name of a person or organization to whom the certificate was issued. If empty, will not perform certificate search by this field.
IssuedBy As String | The name of a person or organization by whom the certificate was issued. If empty, will not perform certificate search by this field.
FriendlyName As String | The friendly name of a person to whom the certificate was issued. If empty, will not perform certificate search by this field.
Email As String | The e-mail address associated with the certificate. If empty, will not perform certificate search by this field.
PfxPassword As String | The password which should be used to access the certificates storage if it's a PFX file. If the password is not used, leave it an empty string.
Return value As Boolean | True if successful, False if error has occurred or no certificate matching the specified search criteria has been found.

Usage example:

' This example loads 5 messages from files, signs them and saves them to disk using the same instance of SMIME class.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Iterate through the messages
For i = 1 To 5
    ' Load the message from file
    objMsg.ImportFromFile "mail_src" & i & ".eml"

    ' Specify the message for the further processing
    Set objSMIME.Message = objMsg

    ' Select the sender's certificate from the system storage of the current user
    ' It's assumed all messages do have valid From and objMsg.PureFromAddr is not empty for them
    If objSMIME.SelectSenderCert ("MY", 0, "", "", "", objMsg.PureFromAddr, "") Then
        ' Sign the message
        objSMIME.Sign
    End If

    ' Check if any errors occurred
    If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
        ' Display the code of the last occurred error
        ' In ASP use Response.Write instead of MsgBox
        MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
          objSMIME.SMIMESpecificError
    End If

    ' Get the signed message from SMIME object
    Set objMsg = objSMIME.Message

    ' Save the signed message to disk
    objMsg.SaveMessage "mail_dst" & i & ".eml"

    ' Reset the SMIME object
    objSMIME.Reset
Next

See Also:

AddRecipientCert Method, Sign Method


SelectSignerCertStore Method

Specifies the certificate storage where to save the certificate of the entity which signed the message being currently processed.

To add a signer's certificate to the store, set the store with SelectSignerCertStore method, and then call AddSignerToStore method.

For instance, the user (message recipient) had received the message which was signed and encrypted by another user (the original sender and signer of this message). If the recipients would like to be able to send the reply-messages encrypted with the original sender's certificates, they should add the original sender's certificate to the certificates storage (using the SelectSignerCertStore and AddSignerToStore methods).

Note that SelectSignerCertStore, when used with AddSignerToStore to save the certicate into a file, can only produce .p7b (not .cer) files.

Once the certificate was successfully added to the storage, user can encrypt the reply-message with the public key contained in this certificate (using AddRecipientCert and Encrypt methods).

[Visual Basic]

blnResult = ObjectName.SelectSignerCertStore([Path], [StoreType])
Parameters:
Path As String

(optional) The name of the certificate's storage. The following names are supported for the system storage (REGISTRY_STORE):

  • MY - the personal user's certificates storage
  • AddressBook - other people certificates storage
  • CA - Intermediate Certification Authorities
  • Root - Trusted Root Certification Authorities

When using the file storage (FILE_STORE or FILE_PFX_STORE) this parameter should contain the name of this file storage.

By default, this parameter is set to "AddressBook" value.
StoreType As Long

(optional) The type of the certificate's storage. MailBee supports the following types of certificate's storages:

  • REGISTRY_STORE = 0 - standart system storage which belongs to the current user
  • FILE_STORE = 1 - file storage
  • FILE_PFX_STORE = 2 - file PFX storage (special file type)

By default, this parameter is set to REGISTRY_STORE value.
Return value As Boolean True if successful, False if error has occurred.

Usage example:

' This example loads the message from file and adds the recipient's certificate to the system storage of the current user.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Check if the message is signed and select the system storage of the current user
If objSMIME.Signed And (objSMIME.SelectSignerCertStore ("MY", REGISTRY_STORE)) Then
    ' Add the signer's certificate to the system storage of the current user
    objSMIME.AddSignerToStore

    ' Check if any errors occurred
    If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
        ' Display the code of the last occurred error
        ' In ASP use Response.Write instead of MsgBox
        MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
          objSMIME.SMIMESpecificError
    End If
End If

See Also:

AddSignerToStore Method, AddRecipientCert Method, Encrypt Method


Sign Method

Adds the digital signature to the message.

Signing a message with digital signature allows recipients (who have their own public keys) to confirm the authenticity of the message sender and verify its integrity (that the message was not altered during transmission).

To add the digital signature to a message, the developer must select the digital certificate containing the public key of message recipient using the SelectSenderCert method.

Then, the developer should add the digital signature using the Sign method. If the message was already signed, nothing happens. The developer can check if the message is signed using the Signed property.

Nowadays, it's recommended to use SHA-256 as signature algorithm. It's more secure than the default one (usually SHA-1). Some mail clients like Mozilla Thunderbird may consider SHA-1 signatures not trusted at all.

[Visual Basic]

blnResult = ObjectName.Sign

Parameters: | None
Return value As Boolean | True if successful, False if error has occurred.

Usage example:

' This example loads the message from file and signs it.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' These lines are needed if we want to use SHA-256 signature (required by Thunderbird)
objSMIME.CSP = "Microsoft Strong Cryptographic Provider"
objSMIME.AlgorithmSigning = "2.16.840.1.101.3.4.2.1"

' Select the sender's certificate form the system storage of the current user
If objSMIME.SelectSenderCert ("MY", 0, "", "", "", objMsg.PureFromAddr, "") Then
    ' Sign the message with selected certificate
    objSMIME.Sign

    ' Check if any errors occurred
    If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
        ' Display the code of the last occurred error
        ' In ASP use Response.Write instead of MsgBox
        MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
          objSMIME.SMIMESpecificError
    End If
End If

See Also:

SelectSenderCert Method, SignAndEncrypt Method, Signed Property


SignAndEncrypt Method

Signs the message using the private key contained in the sender's certificate and encrypts this message using the public key contained in the recipient's certificate.

The digital signature allows recipients to confirm the authenticity of the message sender and verify message integrity.

[Visual Basic]

blnResult = ObjectName.SignAndEncrypt

Parameters: | None
Return value As Boolean | True if successful, False if error has occurred.
Remarks: | Before using this method, the sender's and the recipient's certificates should be selected using SelectSenderCert and AddRecipientCert methods.

Usage example:

' This example loads the message from file, signs and encrypts this message.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' These lines are needed if we want to use SHA-256 signature (required by Thunderbird)
objSMIME.CSP = "Microsoft Strong Cryptographic Provider"
objSMIME.AlgorithmSigning = "2.16.840.1.101.3.4.2.1"

' Select the sender's certificate form the system storage and the recipient's certificate from address book
If (objSMIME.SelectSenderCert ("MY", 0, "","", "", objMsg.PureFromAddr, "")) And _
    (objSMIME.AddRecipientCert ("AddressBook", 0, "", "", "", objMsg.PureToAddr)) Then
    ' Sign and encrypt the message
    objSMIME.SignAndEncrypt

    ' Check if any errors occurred
    If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
        ' Display the code of the occurred error
        ' In ASP use Response.Write instead of MsgBox
        MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
          objSMIME.SMIMESpecificError
    End If
End If

See Also:

SelectSenderCert Method, AddRecipientCert Method , Sign Method, Encrypt Method


Verify Method

Verifies the signature of the message.

The method checks that the message has not been tampered and its sender is not faked.

[Visual Basic]

blnResult = ObjectName.Verify

Parameters: | None
Return value As Boolean | True if successful, False if error has occurred.
Remarks: | This method allows the developer to assure the message was written by the known author and was not altered during the transmission. The developer can also use the Verified property to check if the message was verified successfully.

Usage example:

' This example loads the message from file and verifies it.

Dim objSMIME, objMsg

' Using Visual Basic to create the objects
Set objMsg = CreateObject("MailBee.Message")
Set objSMIME = CreateObject("MailBee.SMIME")

' Using ASP to create the objects
'Set objMsg = Server.CreateObject("MailBee.Message")
'Set objSMIME = Server.CreateObject("MailBee.SMIME")

' Specify MailBee license key
objSMIME.LicenseKey = "put your license key here"

' Load the message from file
objMsg.ImportFromFile "mail_src.eml"

' Specify the message for the further processing
Set objSMIME.Message = objMsg

' Verify the message
objSMIME.Verify

' Check if any errors occurred
If (objSMIME.SMIMEError <> SMIME_OK) Or (objSMIME.SMIMESpecificError <> SMIME_OK) Then
    ' Display the code of the last occured
    ' In ASP use Response.Write instead of MsgBox
    MsgBox "SMIMEError = " & objSMIME.SMIMEError & "   SMIMESpecificError = " & _
      objSMIME.SMIMESpecificError
End If

' Check if the message was verified successfully
If objSMIME.Verified Then
    MsgBox "This message is verified."
End If

See Also:

Verified Property


SSL Object

The SSL object enables the SMTP, POP3 and IMAP4 mailer objects to communicate to email servers over secure SSL and TLS connections. The TLS, as the most secure protocol in comparison to SSL, is used by default.

The SSL object is never used on its own. You always access it via SSL property of SMTP, POP3 and IMAP4 mailer objects. To enable secure connection mode, you must set Enabled=True and also set UseStartTLS=True of SSL object (for STARTTLS connections) or PortNumber of mailer object (for dedicated SSL port connections). See details below.

Syntax

SSL.property|method

Properties
AutosetPortAndSSL | Enables automatic setting of SSL mode accordingly the server name and port.
ClientCert | Contains details on the currently selected client certificate.
Enabled | Enables secure connections.
Protocol | Specifies the security protocol to be used (e.g. TLS 1.0, TLS 1.2).
ServerCert | Contains details on the mail server certificate.
SSLError | Returns completion status of the last security-related operation.
SSLSpecificError | Contains security-related error code returned by Windows API functions.
UseStartTLS | Specifies whether secure connections must use regular port instead of dedicated port.
VerifyServerCert | Specifies whether to abort the connection if the mail server does not have a trusted certificate.
Methods
SelectClientCert | Selects client certificate from the specified registry or file store.
SelectServerCertStore | Selects the registry or file store against which the mail server certificate will be validated.

Remarks

Secure communications take advantage of client and server certificates to authenticate clients and servers. The SSL object supports both types of the certificates including anonymous (i.e. missing) client certificates. You can verify server certificates, search and select client certificates, display information regarding server and client certificates.

Note: The SSL object supports secure connections over dedicated port and over regular port. Some mail servers support both types of the connections, others - only one of these types or even do not support secure connections at all. Consult your mail server administration or documentation to determine which type of the secure connection is supported by your server.

Secure connection over dedicated port uses a port specially reserved for secure connections. The following ports are usually used:
Protocol | Dedicated port number
SMTP | 465
POP3 | 995
IMAP4 | 993
To change port number, set PortNumber property of the SMTP, POP3 or IMAP4 object. By default, MailBee can automatically set the appropriate SSL mode based on the port number you specified (see AutosetPortAndSSL topic for details). However, it's always recommended not to rely on the automatic setting and set everything manually (this means setting Enabled and UseStartTLS properties).

Secure connection over regular port uses the same port as simple insecure connection does. The connection starts in non-secure mode and then switches into secure mode using STARTTLS command (or STLS command for the POP3 protocol). Regular ports are:
Protocol | Regular port number
SMTP | 25
POP3 | 110
IMAP4 | 143
Because regular port numbers are set by default, you do not need to change PortNumber property value. To enable STARTTLS connections, set UseStartTLS property of the SSL object to True.

Note: The default SSL protocol in Windows is TLS 1.0. This version of TLS protocol is now considered weak so it's recommended to specify TLS 1.2 (it, however, must be supported by your mail server). See Protocol property for details).

Example

The following example sends an e-mail through secure channel. The secure connection is created through default port for regular SMTP connections. To enter secure mode, STARTTLS command is used (UseStartTLS is set to True).
Dim objSMTP

' Using Visual Basic to create object
Set objSMTP = CreateObject("MailBee.SMTP")

' Using ASP to create object
' Set objSMTP = Server.CreateObject("MailBee.SMTP")
'
' In ASP, use Response.Write instead of MsgBox

' Unlock SMTP mailer
objSMTP.LicenseKey = "SMTP license key"

' Enable secure connection over regular port
objSMTP.SSL.Enabled = True
objSMTP.SSL.UseStartTLS = True

' Set SMTP server name
objSMTP.ServerName = "mail.server.com"

' Set message properties
objSMTP.Message.ToAddr = "bill@yoursite.com"
objSMTP.Message.FromAddr = "joe@mysite.com"
objSMTP.Message.Subject = "Subject"
objSMTP.Message.BodyText = "Body"

' Send message
If objSMTP.Send Then
  ' Succeeded!!
  MsgBox "Sent successfully"
Else
  ' Failed...
  MsgBox "Error #" & objSMTP.ErrCode & _
    ", Last server reply:" & objSMTP.ServerResponse
End If

' Close the connection
objSMTP.Disconnect

See Also

SMTP.SSL Property, POP3.SSL Property, IMAP4.SSL Property

Send feedback to AfterLogic


AutosetPortAndSSL Property

Tells MailBee whether to automatically enable secure connection mode based on the current port and server name settings.

The default value is True.

You may consider setting it to False only if your server expects regular non-SSL connection on a port which is normally SSL. See SSL object topic for the list of well-known SSL ports. In all cases, setting this property to False won't have any effect.

This property, when True, also checks if the server name contains ".gmail.com". If yes, MailBee will automatically connect to SSL ports because Gmail is known to be SSL-only service.

Note: it's still recommended to manually set the port (e.g. PortNumber for POP3) and SSL properties like Enabled and UseStartTls and do not rely on automatic selection of port number and SSL mode because it can work only in limited number of well-known cases.

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command and ignore automatic SSL setting
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True
Mailer.SSL.AutosetPortAndSSL = False

Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "Body"
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

SSL.Enabled Property


ClientCert Property

Contains information regarding active client certificate.

Active client certificate is used to authenticate the client once connection occurs.

By default there is no any certificate selected (i.e. anonymous certificate is active). Many but not all mail servers accept anonymous certificates. However, you can always select non-anonymous client certificate from the store using SelectClientCert method.

Value Type: | MailBee.CertInfo
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

' It's assumed "MY" system store includes certificate with friendly name "Administrator"
Mailer.SSL.SelectClientCert("MY", 0, "", "", "Administrator") ' select active certificate

' display name of the authority which issued the certificate to the client
MsgBox Mailer.SSL.ClientCert.IssuedBy

See Also:

CertInfo Object

SelectClientCert Method


Enabled Property

Tells MailBee whether to use secure connection.

You may also consider setting UseStartTls property because there are two kinds of secure connections - over a dedicated port and over a regular port.

Note: not all mail servers support secure connections.

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "Body"
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

SMTP.PortNumber Property
POP3.PortNumber Property
IMAP4.PortNumber Property


Protocol Property

Specifies security protocol to be used.

By default, the most secure available protocol is used (currently TLS). However, the default setting does not specify the TLS version so that it's up to the OS. The modern Windows 10 versions tend to use TLS 1.2 in this case. To force using TLS 1.2, you need to specify this property manually. However, it won't work if the mail server doesn't support TLS 1.2 (such servers still exist). Allowed values:

  • 0 - (default) Let the underlying interface select the SSL protocol (usually TLS 1.2 with downgrade to TLS 1.0 if TLS 1.2 is not supported by the server but this logic can be different for older Windows versions)
  • 1 - PCT 1.0
  • 2 - SSL 2.0
  • 3 - SSL 3.0
  • 4 - TLS 1.0
  • 5 - TLS 1.1
  • 6 - TLS 1.2

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.SSL.Protocol = 6 ' Force TLS 1.2

Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "Body"
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  If Mailer.ErrCode = 12 Then
    MsgBox "SSL Error #" & Mailer.SSL.SSLError
  Else
    MsgBox Mailer.ErrDesc
  End If
End If

See Also:

SSL Object


ServerCert Property

Contains information regarding the mail server's certificate.

This property contains valid information only if the connection is already established.

When SSL-enabled object (SMTP, POP3 or IMAP4) connects to the mail server, it receives the server's certificate and places its information in ServerCert property. Also, if VerifyServerCert=True, MailBee verifies whether the server's certificate is trusted. If it is, connection procedure normally continues. If it is not, the connection is aborted.

Value Type: | MailBee.CertInfo
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  ' display name of the authority which issued the certificate to the server
  MsgBox Mailer.SSL.ServerCert.IssuedBy
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

CertInfo Object

VerifyServerCert Property

SelectServerCertStore Method


SSLError Property

Returns completion status of the last SSL-related operation.

This property is useful in two cases:

  • To get detailed error code if ErrCode property of root mailer object (SMTP, POP3 or IMAP4) returned code 12 (SSL Init failed)
  • To get completion status of any methods of SSL object (such as SelectClientCert)

Possible values are:
  • 0 - No Error
  • 8 - SSL operation failed due socket error
  • 21 - Certificate store not found
  • 22 - Certificate not found in the store
  • 23 - Adding certificate to the store failed
  • 24 - Other certificate error
  • 25 - PFX Password is incorrect
  • 31 - Specific SSL error code from Windows API is available in SSLSpecificError property

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "Body"
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  If Mailer.ErrCode = 12 Then
    MsgBox "SSL Error #" & Mailer.SSL.SSLError
  Else
    MsgBox Mailer.ErrDesc
  End If
End If

See Also:

SSLSpecificError Property

SMTP.ErrCode Property
POP3.ErrCode Property
IMAP4.ErrCode Property


SSLSpecificError Property

Contains SSL error code from Windows API.

This property is set if SSLError returned code 31 (Specific error).

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "Body"
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  If Mailer.ErrCode = 12 Then
    MsgBox "SSL Error #" & Mailer.SSL.SSLError
    If Mailer.SSL.SSLError = 31 Then
      MsgBox "WinAPI Error code: " & Mailer.SSL.SSLSpecificError
    End If
  Else
    MsgBox Mailer.ErrDesc
  End If
End If

See Also:

SSLError Property


UseStartTLS Property

Tells MailBee whether to use dedicated port connection or STARTTLS connection.

Dedicated port connection uses specially provided SSL port number: usually 465 for SMTP, 995 for POP3, 993 for IMAP4.

STARTTLS connection uses regular ports (25 for SMTP, 110 for POP3, 143 for IMAP4) but uses special command STARTTLS to switch connection to SSL mode.

If UseStartTLS=False, you must explicitly set dedicated port number for SMTP, POP3 or IMAP4 object. For example:

Mailer.PortNumber = 995 ' Set dedicated SSL port for POP3 object

Note that in case of SMTP MailBee will issue STARTTLS command only if it's supported by the server. If the server does not support it, the connection will not be encrypted. You may consider to use dedicated SSL port connection if your server supports SSL but not STARTTLS. To check if your SMTP server supports STARTTLS, use SMTP.SupportsStartTLS property.

Refer to your mail server documentation or configuration to determine what type of connection your server supports: some servers support both types, others - only one of the types, but many servers do not support SSL/TLS at all.

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "Body"
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

SMTP.PortNumber Property
POP3.PortNumber Property
IMAP4.PortNumber Property


VerifyServerCert Property

If True, SSL object will verify server certificate each time SSL-enabled object (such as SMTP, POP3 or IMAP4) connects to the mail server.

By default is False, i.e. SSL object will accept any server certificate regardless whether it is trusted or not.

The server certificate is considered "trusted" if it was issued by trusted authority (from Windows's point of view). In Windows, list of trusted authorities can be viewed or managed using "Control panel/Internet options/Content/Certificates/Trusted Root Certification Authorities".

However, you can select your own trusted certificates list instead of system default one using SelectServerCertStore method.

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

' Only trusted server cerificates will be accepted
Mailer.SSL.VerifyServerCert = True

Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.BodyText = "Body"
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

SelectServerCertStore Method


SelectClientCert Method

Reads a certificate from the specified store and makes it active certificate that MailBee will use to represent the client to the mail server.

Most (but not all) mail servers do not require any client certificate (anonymous certificate is accepted). So, you do not need to call this method unless your mail server requires client certificate.

As a minimum, only certificate store name and type required for this method. First certificate in the store will be automatically selected. However, you can specify particular certificate in the store by using optional parameters of the method.

To deselect any client certificate (if you want to revert to anonymous certificate), just call this method with empty Path argument.

Selected certificate information will be accessible through ClientCert property.

Note: This method will make effect only if it called BEFORE connecting to the mail server.

blnResult = ObjectName.SelectClientCert(Path, StoreType, [IssuedTo], [IssuedBy], [FriendlyName], [PrivateKey])
Parameters:
Path As String Filename or system registry name of the store. Allowed system registry names are:
  • "MY" - Personal certificates of the user. This is common store of clients certificates
  • "CA" - Intermediate authorities. This is common store of server certificates' issuers
  • "ROOT" - Trusted list of Internet certification authorities. Well-known servers usually have certificates signed by authorities from the "ROOT"
StoreType As Long Type of the certificate store to select certificate from. Allowed values are:
  • 0 - System registry. Path must be one of the strings "MY", "CA", "ROOT"
  • 1 - File store. Path must be the valid filename of certificate store
  • 2 - PFX File store (only supported on Windows 2000 or higher). Path must be the valid filename of the certificate with embedded private key
IssuedTo As String | (optional) If specified, only certificates with given Issued To name will be considered during search
IssuedBy As String | (optional) If specified, only certificates with given Issued By name will be considered during search
FriendlyName As String | (optional) If specified, only certificates with given Friendly Name will be considered during search
PrivateKey As String | (optional) Private key of PFX file. This parameter is valid for PFX file stores only
Return value As Boolean | True if successful, False if no corresponding certificate was found

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.UseStartTLS = True
Mailer.SSL.Enabled = True

' It's assumed "C:\admin.cer" is a valid certificate
Mailer.SSL.SelectClientCert("C:\admin.cer", 1) ' select active certificate

MsgBox Mailer.SSL.ClientCert.IssuedBy ' display info on who issued the certificate to the client

See Also:

ClientCert Property


SelectServerCertStore Method

Selects the store where to search server certificate.

This method is used for testing validity of server certificates. However, this method is required only if you're implementing your own certificate stores.

By default (VerifyServerCert=False), MailBee does not check server certificates. However, if VerifyServerCert=True, MailBee will determine whether the server certificate is trusted during connecting to the server. If the certificate is not trusted, the connection is refused.

MailBee concludes the certificate is trusted if it is signed by well-known authority. Default store of well-known authorities is "ROOT" system store. You can access this store through "Control panel/Internet options/Content/Certificates/Trusted Root Certification Authorities" panel. However, you can always select your own trusted store using SelectServerCertStore method.

Note: This method will make effect only if it called BEFORE connecting to the mail server. Also VerifyServerCert must be True.

blnResult = ObjectName.SelectServerCertStore(Path, StoreType, [Options])
Parameters:
Path As String Filename or system registry name of the store. Allowed system registry names are:
  • "MY" - Personal certificates of the user. This is common store of clients certificates but not usually applicable for server certificates
  • "CA" - Intermediate authorities. This is common store of server certificates' issuers
  • "ROOT" - Trusted list of Internet certification authorities. Well-known servers usually have certificates signed by authorities from the "ROOT"
StoreType As Long Type of the certificate store to select certificate from. Allowed values are:
  • 0 - System registry. Path must be one of the strings "MY", "CA", "ROOT"
  • 1 - File store. Path must be the valid filename of certificate store
Options As Long (optional) By default, server certificate is considered "trusted" by the store if certificate issuer name is found in the store. However, you may override this behavior. If Options is specified, can be any combination of the following values:
  • 1 - Search by certificate name
  • 2 - Search by certificate issuer name. This is default behavior commonly used in secure communications
  • 128 - Server certificate if not found in the store will be automatically added to the store. Thus, any server becomes trusted for this store
Return value As Boolean Always True

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

' Select system's TRUSTED ROOT as a source of trusted authorities
Mailer.SSL.SelectServerCertStore("ROOT", 0) ' select active certificate

Mailer.SSL.VerifyServerCert = True

Mailer.Connect "mail.server.com", 465
MsgBox Mailer.SSL.ServerCert.IssuedTo ' display info on the certificate owner

See Also:

ServerCert Property


Message Object

The Message object represents a single e-mail message. You can use methods and properties of the Message object to examine or set message attributes and content.

When retrieving a message with the POP3 or IMAP4 object, downloaded message is parsed and stored in the Message object's property values.

When creating a message to be sent by the SMTP object, the Message object's property values are encoded and assembled to produce e-mail message data.

Thus, many properties of the Message object can be both read (when downloading and displaying messages) and set (when composing and sending messages).

Syntax

Message.property|method

Collections
Attachments | The collection of attachments to the message.
Properties
AddressDelimiter | Specifies the delimiter to be used to separate individual items when returning e-mail addresses' or friendly names' strings.
AltBodyEncoding | Specifies which encoding method to use for the message alternative body.
AutoEncodeHeaders | Sets or gets if MailBee should automatically encode headers and attachment filenames with international characters.
AltBodyText | Contains alternative plain-text body of the message if the primary body is HTML-formatted.
BCCAddr | The e-mail addresses of the blind-carbon-copy recipients.
BodyEncoding | Specifies which encoding method to use for the message primary body.
BodyFormat | Indicates the primary body format: Plain-Text, HTML, etc.
BodyText | The primary body text.
CCAddr | The e-mail addresses of the carbon-copy recipients.
CCFriendlyName | The friendly names of the carbon-copy recipients.
Charset | Specifies the charset of the message body.
ContentType | The "Content-Type:" message header value.
Date | The date and time when the message was composed.
Enable8bitEncoding | Indicates whether 8bit characters are permitted in the message body.
FromAddr | The e-mail address of the sender.
FromFriendlyName | The friendly name of the sender.
HasAttachments | Indicates whether the message has any attachments.
MessageID | The "Message-ID:" message header value.
MinimalRebuild | Restricts possible modifications of the message to operations with its headers.
PureCCAddr | The e-mail addresses (with friendly names removed) of the carbon-copy recipients.
PureFromAddr | The e-mail address (with friendly name removed) of the sender.
PureToAddr | The e-mail addresses (with friendly names removed) of the primary recipients.
RawBody | The entire message source including the headers, all the bodies and attachments.
RawHeader | Returns the entire message header block.
Received | The "Received:" message header value.
ReplyToAddr | The e-mail address of the entity specified to receive all replies to the message.
ReturnPath | The e-mail address from which the message was actually sent.
Size | The size of the entire message in bytes.
SpecialBodyContentType | Contains the value of Content-Type header of the non-standard text body part of the message.
SpecialBodyHeaders | Specifies additional headers to be put into the header section of the non-standard text body part of the message.
SpecialBodyText | Contains the non-standard body of the message.
Subject | The subject of the message.
ToAddr | The e-mail addresses of the primary recipients.
ToFriendlyName | The friendly names of the primary recipients.
XMailer | The "X-Mailer:" message header value.
Methods
AddAttachment | Attaches a file to the message.
AddHeader | Adds custom header to the message.
AddMemoryAttachment | Attaches a data from memory as file to the message.
AddStringAttachment | Attaches a data from string as file to the message.
ConvertCharset | Converts the supplied string encoded in the given charset into another charset.
DecodeMstnef | Extracts attachments from MS-TNEF (winmail.dat) attachment if any, removes MS-TNEF attachments from Attachments collection, and returns the number of extracted files.
EncodeHeaderText | Encodes a string using the specified charset encoding.
EscapeIdnDomain | Encodes specified text string (e-mail address) to allow using international characters in domain name.
GetBodyWithEmbeddedObjects | Saves embedded pictures (and other objects referenced in the message HTML body) to temporary files and returns modified HTML body text where paths to the embedded objects are replaced with paths to the the temporary files.
GetBodyWithEmbeddedObjectsEx | In addition to GetBodyWithEmbeddedObjects method functionality, provides more options and allows using virtual paths and dynamic URLs to reference embedded objects in the HTML body.
GetCodepageFromCharset | Returns codepage number for the specified charset.
GetDateFromString | Converts the specified date and time string into Date type.
GetFileAsArray | Returns the contents of the specified file as Byte Array. In ASP, you can use this method to download files to the clients.
GetFriendlyName | Extracts and returns the friendly name from the specified full e-mail address
GetHeader | Returns the value of the specified message header.
GetHtmlFromPlain | Returns the specified plain-text adapted for display in HTML browser.
GetMD5Digest | Returns the MD5 Digest value of the specified string.
GetMD5DigestOfArray | Returns the MD5 Digest value of the specified byte array.
GetMessageDirectoryPath | Returns path to the directory where the embedded objects were saved during GetBodyWithEmbeddedObjects or GetBodyWithEmbeddedObjectsEx method call.
GetPlainFromHtml | Converts the specified HTML text into plain-text.
GetPureAddr | Extracts and returns the pure e-mail address from the specified full e-mail address
ImportAltBodyText | Loads the specified file contents into the message alternative body.
ImportBodyText | Loads the specified file contents into the message primary body and, optionally, scans the loaded HTML body for embedded objects and appends them as attachments.
ImportFromFile | Loads entire message from the specified file.
ImportFromMemory | Loads entire message from the specified byte array.
MakeAltBody | Creates the alternative plain-text body from the current value of the HTML body.
MessageDirectoryExists | Indicates whether the directory for the embedded objects storage exists.
RemoveCharsetFromBody | Removes the meta tag containing the charset declaration of the document from the HTML body, and returns the charset removed.
RemoveHeader | Removes custom header from the message.
RemoveMessageDirectory | Deletes the directory for the embedded objects storage.
SaveMessage | Saves the entire message to disk in .EML format.
ToUTF8 | Returns the specified string converted in UTF-8 charset.
UnescapeIdnDomain | Decodes the e-mail address string with Punycode-encoded domain part (IDN) into human-readable form.
ValidateEmailAddress | Tests whether the specified e-mail address is correct.
WriteStringToFile | Writes the specified string into the specified file.

Remarks

To retrieve a message (and the Message object) from the POP3 server, you can use RetrieveSingleMessage or RetrieveSingleMessageHeaders methods of the POP3 object. RetrieveSingleMessageHeaders method returns a message with only headers set so you can use it for message preview purposes.

The IMAP4 object does also include RetrieveSingleMessage and RetrieveSingleMessageHeaders methods.

The POP3 object can also return multiple messages at once within the Messages collection of Message objects. Refer to RetrieveMessages and RetrieveHeaders methods documentation for details. With the IMAP4 object, however, it is more efficient to preview multiple messages as the Envelopes collection of Envelope objects.

When composing a new message, you can get a reference to the Message object from SMTP.Message property.

Finally, you can create the Message object directly in the code:

[Visual Basic]
Set objMessage = CreateObject("MailBee.Message")

[ASP]
Set objMessage = Server.CreateObject("MailBee.Message")

This is useful when using stand-alone methods of the Message object (such as GetFileAsArray), or when you want to extract a message from another message (e.g. to obtain forwarded message from the attachment).

Example

The following example retrieves a message from the POP3 server and displays it. The sample is presented separately in Visual Basic version and ASP version since they differ quite enough.

[Visual Basic]
Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Download first message in the mailbox
Set objMsg = objPOP3.RetrieveSingleMessage(1)

If objPOP3.IsError Then
  ' Display error information
  MsgBox "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
Else
  ' Display the message
  MsgBox _
    "From: " & objMsg.FromAddr & vbCrLf & _
    "To: " & objMsg.ToAddr & vbCrLf & _
    "Subject: " & objMsg.Subject & vbCrLf & _
    "Date: " & objMsg.GetDateFromString(objMsg.Date) & vbCrLf & vbCrLf & _
    objMsg.BodyText
End If

' Close the connection
objPOP3.Disconnect

[ASP]
<%
Dim objPOP3, objMsg

' Create POP3 object
Set objPOP3 = Server.CreateObject("MailBee.POP3")

' Unlock POP3 object
objPOP3.LicenseKey = "put your license key here"

' Set POP3 server name
objPOP3.ServerName = "mail.server.com"

' Set user credentials
objPOP3.UserName = "username"
objPOP3.Password = "password"

' Download first message in the mailbox
Set objMsg = objPOP3.RetrieveSingleMessage(1)

If objPOP3.IsError Then
  ' Display error information
  Response.Write "Error #" & objPOP3.ErrCode & ", " & objPOP3.ErrDesc
Else
  ' Display the message.
  ' We use Server.HTMLEncode to convert '<' and '>'
  ' characters which can disturb the output if they
  ' are contained in the message headers.
  Response.Write _
    "From: " & Server.HTMLEncode(objMsg.FromAddr) & "<br>" & _
    "To: " & Server.HTMLEncode(objMsg.ToAddr) & "<br>" & _
    "Subject: " & Server.HTMLEncode(objMsg.Subject) & "<br>" & _
    "Date: " & objMsg.GetDateFromString(objMsg.Date) & "<br><br>" & _
    objMsg.BodyText
End If

' Close the connection
objPOP3.Disconnect
%>

See Also

SMTP Object, POP3 Object, IMAP4 Object

Send feedback to AfterLogic


Attachments Property

Holds collection of the message attachments.

See Attachments collection description for details

Value Type: | Attachments
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Number of attachments = " & Msg.Attachments.Count
   End If
   Mailer.Disconnect
End If

See Also:

Message Object
Attachments Collection
AddAttachment Method


AddressDelimiter Property

Specifies the delimiter of addresses which will be used when returning values of FromAddr, ToAddr, PureCCAddr, ToFriendlyName and other similar properties. The default value is ", " (comma followed by space).

This property is useful if you have "," chars in the values of e-mail addresses or display names and you need to split the entire string to get individual addresses. You can assign it to a somewhat like "{|}" (which is highly unlikely to appear in addresses) and split by this value.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg, ToRecipients, SingleTo
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        Msg.AddressDelimiter = "{|}"
        ToRecipients = Split(Msg.ToAddr, "{|}")
        For Each SingleTo In ToRecipients
          MsgBox SingleTo
        Next
      End If
   End If
   Mailer.Disconnect
End If

See Also:

Message Object


AltBodyEncoding Property

Specifies method to be used to encode alternative body of the message.

You need to set value of this property only during message composing (i.e. for using with MailBee.SMTP object). If the message is created by MailBee.POP3 object, its alternative body (if present) will be automatically decoded, so you do not need to care about AltBodyEncoding.

The following encoding settings are allowed:

  • 0 - No encoding. No encoding is performed, Content-Transfer-Encoding header is not set at all
  • 1 - 7bit or 8bit encoding. Nearly equivalent of "No encoding", but Content-Transfer-Encoding header is explicitly set to "7 bit" or "8 bit" depending on value of Enable8bitEncoding property
  • 2 - (default) Quoted-printable encoding. Efficient if the body contains mostly 7bit characters (ASCII symbols with codes 0 - 127)
  • 3 - Base64. Efficient if the body contains many 8bit characters (ASCII symbols with codes 128 - 255)

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Message.MakeAltBody
  Mailer.Message.AltBodyEncoding = 3 ' Base64
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

ImportAltBodyText Method
MakeAltBody Method
Enable8bitEncoding Property
BodyEncoding Property


AltBodyText Property

Contains alternative message body (if BodyText contains HTML-formatted body).

If the message is not HTML-formatted (i.e. BodyText contains plain text), AltBodyText is empty. If the message provides both bodies (HTML and plain), AltBodyText contains plain body taken from the message. If the message provides only HTML body, AltBodyText is generated by MailBee using GetPlainFromHtml method.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Plain Body = " & Msg.AltBodyText
   End If
   Mailer.Disconnect
End If

See Also:

Message Object
BodyText Property
GetPlainFromHtml Method
ImportAltBodyText Method


AutoEncodeHeaders Property

This property controls whether MailBee should automatically encode headers and attachment filenames containing international characters.

The default value is True.

For advanced purposes, you can set it to False and encode headers manually with EncodeHeaderText method.

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "I want to encode headers manually"
  Mailer.AutoEncodeHeaders = False
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

EncodeHeaderText method


BCCAddr Property

Value of "BCC" header (blind-carbon-copy recipients).

If composing the message, at least one of recipient specifiers (ToAddr, CCAddr, BCCAddr) must be set. Otherwise, SMTP server will reject the message. You can specify several email addresses, separating with commas (",").

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses. This only makes sense for reading an existing message, not for composing a new one (when sending a message, recipients must be separated with comma).

If the message was created by MailBee.POP3, this header is empty, because BCC does not appear in messages (the message is sent to BCC recipients, but they are not displayed in message headers).

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.BCCAddr = "Jeff Jones<jeff@hissite.com>, Margo Witch<margo.witch@herssite.com>"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

ToAddr Property
CCAddr Property
FromAddr Property


BodyEncoding Property

Specifies method to be used to encode main body of the message.

You need to set value of this property only during message composing (i.e. for using with MailBee.SMTP object). If the message is created by MailBee.POP3 object, its main body will be automatically decoded, so you do not need to care about BodyEncoding.

The following encoding settings are allowed:

  • 0 - No encoding. No encoding is performed, Content-Transfer-Encoding header is not set at all
  • 1 - 7bit or 8bit encoding. Nearly equivalent of "No encoding", but Content-Transfer-Encoding header is explicitly set to "7 bit" or "8 bit" depending on value of Enable8bitEncoding property
  • 2 - (default) Quoted-printable encoding. Efficient if the body contains mostly 7bit characters (ASCII symbols with codes 0 - 127)
  • 3 - Base64. Efficient if the body contains many 8bit characters (ASCII symbols with codes 128 - 255)
Note: Besides handling high ASCII characters, quoted-printable and base64 encoding also preserve original text formatting. This might be important for plain-text (not HTML) bodies with lines more than 76 symbols length. If you want to disable line-wrapping for these lines, use quoted-printable or base64 encoding.

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Message.BodyEncoding = 3 ' Base64 encoding
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

Enable8bitEncoding Property
AltBodyEncoding Property


BodyFormat Property

Indicates format of main body of the message.

MailBee.POP3 can produce Message objects of the following body formats:

  • 0 - Plain text (default value)
  • 1 - HTML
  • 2 - RTF
  • 3 - XML
  • 7 - Unknown format
When creating the message to be sent using MailBee.SMTP object, the following subset of defined formats can be used:
  • 0 - Plain text (default value)
  • 1 - HTML
  • 2 - RTF
  • 3 - XML

Value Type: | Long
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        Select Case Msg.BodyFormat
        Case 0
          MsgBox "Plain text"
        Case 1
          MsgBox "HTML text"
        Case Else
          MsgBox "Other text"
        End Select
      End If
   End If
   Mailer.Disconnect
End If

See Also:

Message Object
BodyText Property


BodyText Property

Contains the message's body.

If the message is multipart (i.e. constists of several parts, like attachments, alternative body presentation and so on), BodyText property includes richest text body. If the message includes HTML-formatted body, BodyText contains HTML body (plain version is still available through AltBodyText property). If only plain text body is available, BodyText contains plain body. Other parts of the message are available through Message.Attachments collection.

When composing the message (for using with SMTP object), consider using ImportBodyText method to import the body from a file, or ToUTF8 method to export Unicode content.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Body = " & Msg.BodyText
   End If
   Mailer.Disconnect
End If

See Also:

"Displaying HTML-formatted messages in Visual Basic" Tutorial
"Displaying HTML-formatted messages in ASP" Tutorial
"Creating and sending HTML-formatted messages" Tutorial

Message Object
AltBodyText Property
ImportBodyText Method
ToUTF8 Method
GetBodyWithEmbeddedObjects Method
GetBodyWithEmbeddedObjectsEx Method


CCAddr Property

Value of "CC" header (carbon-copy recipients).

If composing the message, at least one of recipient specifiers (ToAddr, CCAddr, BCCAddr) must be set. Otherwise, SMTP server will reject the message. You can specify several email addresses, separating with commas (",").

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses. This only makes sense for reading an existing message, not for composing a new one (when sending a message, recipients must be separated with comma).

To deal with e-mail addresses with international domain names (IDN), use EscapeIdnDomain method to encode an e-mail address to IDN form (when sending out e-mails) or UnescapeIdnDomain method to decode an e-mail address into human-readable form (when receiving e-mails).

If the message was received using MailBee.POP3 object, the property is value of "CC" header or empty string if this header is missing.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.CCAddr = "Jeff Jones<jeff@hissite.com> (ABC Company), margo.witch@herssite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

PureCCAddr Property
CCFriendlyName Property
ToAddr Property
BCCAddr Property
FromAddr Property


CCFriendlyName Property

Returns comma-separated friendly names of CC recipients. If particular friendly name is not available, corresponding email address is returned instead.

For example, if CCAddr is as following: "Mr. X, Y Company"<mr.x@y.com> (y.com), nofriendlyname@localhost, someone@host.net (Only comment)

then CCFriendlyName will return: Mr. X, Y Company, nofriendlyname@localhost, Only comment

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses. This only makes sense for reading an existing message, not for composing a new one (when sending a message, recipients must be separated with comma).

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "CCFriendlyName(s) = " & Msg.CCFriendlyName
   End If
   Mailer.Disconnect
End If

See Also:

CCAddr Property
PureCCAddr Property
ToFriendlyName Property
FromFriendlyName Property


Charset Property

Specifies the character set of the message.

This property mostly makes sense only when you create the message yourself. If the message was created by MailBee (such as returned by MailBee.POP3 object), the message is already decoded to Unicode, so this property value will be informational only.

The default value for new messages is "utf-8".

Note that if you receive HTML e-mail and plan to display it in the browser, you will usually need to remove META tag containing charset declaration from the HTML body. This is because MailBee uses the charset declaration from the e-mail headers to decode the HTML body into Unicode, and the charset META charset becomes no longer relevant (because HTML body is now Unicode). From now on, if you display the HMTL contents in a browser, META charset declaration must not be there (otherwise, the browser will use it and set the charset of the page incorrectly).

You can use RemoveCharsetFromBody method to remove this charset declaration from the HTML body.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.FromAddr = "Natasha <nata@server.com>"
  Mailer.Subject = "Non-english text in the subject and in the body"
  Mailer.Charset = "koi8-r"
  Mailer.ImportBodyText "C:\docs\letter_koi8.htm", True
  Mailer.MakeAltBody
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

BodyText Property
AltBodyText Property
BodyEncoding Property
AltBodyEncoding Property


ContentType Property

Value of "Content-Type" header (or empty string if this header is missing).

Common example is: text/plain; charset="us-ascii"

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "ContentType: " & Msg.ContentType
   End If
   Mailer.Disconnect
End If

See Also:

GetHeader Method


Date Property

When the message is returned by MailBee.POP3 object, contains value of "Date" header (or empty string if this header is missing).

Typical example is: Mon, 20 Oct 2003 11:46:07 -0800

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        MsgBox "Date as it appears in the header: " & Msg.Date
        MsgBox _
          "Local date (relative to the current locale and timezone):" & _
          Msg.GetDateFromString(Msg.Date)
      End If
   End If
   Mailer.Disconnect
End If

See Also:

Message Object
GetDateFromString Method


Enable8bitEncoding Property

This property makes sense only for message composing (i.e. for using with MailBee.SMTP object). It covers international issues regarding non-US characters in message body.

You should set this property to True if you wish to use 8bit characters without encoding (BodyEncoding=AltBodyEncoding=0). By default, MIME messages are not allowed to have characters with ASCII codes above 127 in their bodies. However, most modern SMTP servers provide 8bit support.

8 bit characters may appear in body text only if body encoding is not used (i.e BodyEncoding=0). If you apply quoted-printable (BodyEncoding=2) or base64 (BodyEncoding=3) encoding to all document bodies, characters of encoded bodies will be within 7bit range, so Enable8bitEncoding property doesn't matter.

Default value is False.

Note: Enable8bitEncoding property controls whole message body. If all chararcters of BodyText are within 7bit range, but AltBodyText or any of message headers includes 8 bit characters, set Enable8bitEncoding=True or apply encoding to the message parts containing 8 bit characters.

Value Type: | Boolean
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Enable8bitEncoding = True
  Mailer.ImportBodyText "C:\docs\letter_with_extended_symbols.txt", False
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

BodyText Property
AltBodyText Property
BodyEncoding Property
AltBodyEncoding Property


FromAddr Property

Value of "From" header (message sender).

To deal with e-mail addresses with international domain names (IDN), use EscapeIdnDomain method to encode an e-mail address to IDN form (when sending out e-mails) or UnescapeIdnDomain method to decode an e-mail address into human-readable form (when receiving e-mails).

If the message was received using MailBee.POP3 object, the property is value of "From" header or empty string if this header is missing.

If composing the message (for usage with MailBee.SMTP object), FromAddr must be set to the moment of calling Send method. Otherwise, SMTP server will reject the message.

Value Type: | String
Parameters: | None

Usage example:

' Example 1: Using with POP3 object
Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "From: " & Msg.FromAddr
   End If
   Mailer.Disconnect
End If

' Example 2: Using with SMTP object
' (Connect method will authenticate using 'HELO mysite.com' taken from FromAddr).
Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

' Example 3: Using with SMTP object
' (Connect method will authenticate using 'HELO localhost' if it's hostname of your machine).
Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"

' FromAddr is empty at this time, the machine's hostname is used
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

PureFromAddr Property
FromFriendlyName Property
ToAddr Property
CCAddr Property
BCCAddr Property
SMTP.Domain Property
SMTP.Connect Method


FromFriendlyName Property

Returns comma-separated friendly names of From recipients (however, usually only one recipient is present). If friendly name is not available, email address is returned instead.

For example, if FromAddr is like: "Mr. X, Y Company"<mr.x@y.com> (y.com)

then FromFriendlyName will return: Mr. X, Y Company

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "FromFriendlyName = " & Msg.FromFriendlyName
   End If
   Mailer.Disconnect
End If

See Also:

FromAddr Property
PureFromAddr Property
ToFriendlyName Property


HasAttachments Property

True if the message has attachments.

This property can be determined from the message headers, so it is set even if only headers are available (RetrieveSingleMessageHeaders or RetrieveHeaders method was used).

Note: Some odd messages may have incorrect Content-Type header setting, so HasAttachments property should be used with care, for preview purposes only. The only 100%-reliable way to determine whether attachments are present or not is to receive the message completely (using RetrieveSingleMessage or RetrieveMessages method). If the message is received completely, HasAttachments is determined from the size of Attachments collection (so it will be correct in 100% cases).

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        If Msg.HasAttachments Then
          MsgBox "It seems the message has attachments"
        Else
          MsgBox "The message does not seem to have attachments"
        End If
      End If
   End If
   Mailer.Disconnect
End If

See Also:

Message Object
Attachments.Count Property
POP3.RetrieveSingleMessage Method
POP3.RetrieveSingleMessageHeaders Method
POP3.RetrieveMessages Method
POP3.RetrieveHeaders Method


MessageId Property

When the message is returned by MailBee.POP3 object, contains value of "Message-ID" header (or empty string if this header is missing).

Typical example: <000601c3971c$754572f0$6801a8c0@SMEANSPC>

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Message-ID: " & Msg.MessageId
   End If
   Mailer.Disconnect
End If

See Also:

Message Object


MinimalRebuild Property

MinimalRebuild property restricts possible modifications of the message to operations with its headers.

Setting this property to True ensures that the structure and values of the header fields of the message (for example, "Message-ID") and its content will keep their original values. The only allowed modifications of the message are changing, removing or adding of the headers.

Set this property to True during forwarding of the message or when you send the message which is imported from the file.

Default value is False.

Value Type: | Boolean
Parameters: | None

Usage example:

' This sample retrieves first message in the account, sets 'MinimalRebuild' property to True and adds a header.
' Then, it sends the modified message back to the server. The message has kept its original structure and the new header was
' the only change.
Dim MailerPOP, MailerSMTP, Msg
' Using visual basic to create object
Set MailerPOP = CreateObject("MailBee.POP3")
Set MailerSMTP = CreateObject("MailBee.SMTP")
' Using ASP to create object
' Set MailerPOP = Server.CreateObject("MailBee.POP3")
' Set MailerSMTP = Server.CreateObject("MailBee.SMTP")
' In ASP use Response.Write instead of MsgBox
MailerPOP.LicenseKey = "put your license key"
MailerSMTP.LicenseKey = "put your license key"
MailerSMTP.ServerName = "mailserver.com"
If MailerPOP.Connect("mailserver.com", 110, "MyName", "MyPassword") Then
   If MailerPOP.MessageCount > 0 Then
      Set Msg = MailerPOP.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
         Msg.MinimalRebuild = True
         Msg.AddHeader "Organization", "AfterLogic Corp"
         Set MailerSMTP.Message = Msg

         ' Send modified message back to the server
         If Not MailerSMTP.Send Then
            MsgBox "Error #" & MailerSMTP.ErrCode & ", " & MailerSMTP.ErrDesc
         Else
            MailerSMTP.Disconnect
         End If
      End If
   Else
      MsgBox "Your mailbox is empty."
   End If
   MailerPOP.Disconnect
End If

See Also:

Message Object | POP3 Object | SMTP Object


PureCCAddr Property

Returns comma-separated email addresses of CC recipients.

For example, if CCAddr is like: "Mr. X, Y Company"<mr.x@y.com> (y.com), nofriendlyname@localhost, someone@host.net (Only comment)

then PureCCAddr will return: mr.x@y.com, nofriendlyname@localhost, someone@host.net

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses. This only makes sense for reading an existing message, not for composing a new one (when sending a message, recipients must be separated with comma).

To deal with e-mail addresses with international domain names (IDN), use UnescapeIdnDomain method to decode an e-mail address into human-readable form.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Pure CC Addr(s) = " & Msg.PureCCAddr
   End If
   Mailer.Disconnect
End If

See Also:

CCAddr Property
CCFriendlyName Property
PureToAddr Property
PureFromAddr Property


PureFromAddr Property

Returns email address of the sender.

For example, if FromAddr is like: "Mr. X, Y Company"<mr.x@y.com> (y.com)

then PureCCAddr will return: mr.x@y.com

To deal with e-mail addresses with international domain names (IDN), use UnescapeIdnDomain method to decode an e-mail address into human-readable form.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Pure From Addr = " & Msg.PureFromAddr
   End If
   Mailer.Disconnect
End If

See Also:

FromAddr Property
FromFriendlyName Property
PureToAddr Property
PureCCAddr Property


PureToAddr Property

Returns comma-separated email addresses of "To:" recipients.

For example, if ToAddr is like: "Mr. X, Y Company"<mr.x@y.com> (y.com), nofriendlyname@localhost, someone@host.net (Only comment)

then PureToAddr will return: mr.x@y.com, nofriendlyname@localhost, someone@host.net

To deal with e-mail addresses with international domain names (IDN), use UnescapeIdnDomain method to decode an e-mail address into human-readable form.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Pure 'To' Addr(s) = " & Msg.PureToAddr
   End If
   Mailer.Disconnect
End If

See Also:

ToAddr Property
ToFriendlyName Property
PureCCAddr Property
PureFromAddr Property


RawBody Property

Contains whole message (including bodies, attachments, headers) as MIME-formatted text.

If the message was returned by MailBee.POP3 or MailBee.IMAP4 object, RawBody holds message source as it came from the mail server.

If the message is created (not received by MailBee.POP3), RawBody will be generated by MailBee by converting values of all properties into MIME format.

Also, you can assign value of RawBody manually. However, make sure you pass correct MIME message in the value.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "RawBody = " & Msg.RawBody
   End If
   Mailer.Disconnect
End If

See Also:

Message Object


RawHeader Property

Returns the entire message header block.

Message header block is the first part of the entire message data. To access the entire message data, use RawBody property.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox Msg.RawHeader
   End If
   Mailer.Disconnect
End If

See Also:

RawBody Property


Received Property

Value of "Received" header (or empty string if this header is missing).

Messages often contain several "Received" headers. If so, they will be separated with CRLF sequence (vbCrLf constant in VB) in this property's value.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Received = " & Msg.Received
   End If
   Mailer.Disconnect
End If

See Also:

Message Object


ReplyToAddr Property

Value of "Reply-To" header (an address the message sender wants to get replies to).

If composing the message, you can leave this address blank (it is not required by SMTP servers).

To deal with e-mail addresses with international domain names (IDN), use EscapeIdnDomain method to encode an e-mail address to IDN form (when sending out e-mails) or UnescapeIdnDomain method to decode an e-mail address into human-readable form (when receiving e-mails).

If the message was received using MailBee.POP3 object, the property is value of "Reply-To" header or empty string if this header is missing.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Reply-To: " & Msg.ReplyToAddr
   End If
   Mailer.Disconnect
End If

See Also:

FromAddr Property
ToAddr Property
CCAddr Property
BCCAddr Property


ReturnPath Property

Value of "Return-Path" header (the path back to the message's originator).

If composing the message, you commonly leave this address blank (SMTP servers generate it themselves).

If the message was received using MailBee.POP3 object, the property is value of "Return-Path" header or empty string if this header is missing.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Return-Path: " & Msg.ReturnPath
   End If
   Mailer.Disconnect
End If

See Also:

FromAddr Property
ReplyToAddr Property


Size Property

Returns the message size (in bytes).

This property is always set to right value even if only message headers are received (i.e. if RetrieveSingleMessageHeaders or RetrieveHeaders method was used). So, Size property might be not equal to Len(RawBody) if only headers are received.

Note: To get message size, it's not even required to download message headers. POP3 object gets messages sizes during connection stage. Once Connect method finished, you may get particular message size using POP3.Size(Index) property.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Message size = " & Msg.Size & " bytes"
   End If
   Mailer.Disconnect
End If

See Also:

Message Object


SpecialBodyContentType Property

Contains the value of Content-Type header of the non-standard text body part of the message.

The example of this value is text/calendar; method=REQUEST; name="meeting.ics". If the message doesn't have such kind of body, this value is an empty string.

To get or set the contents of such body, use SpecialBodyText property.

To get or set other headers of such body, use SpecialBodyHeaders property. However, you do not need to set Content-Transfer-Encoding header. MailBee adds it automatically if required.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Special body type = " & Msg.SpecialBodyContentType
   End If
   Mailer.Disconnect
End If

See Also:

SpecialBodyText Property
SpecialBodyHeaders Property


SpecialBodyHeaders Property

Specifies additional headers to be put into the header section of the non-standard text body part of the message.

Use this property to add specific headers to the non-standard text body part (such as vCal item) of the message being composed.

For received messages (messages being parsed rather than created), this property is set to an empty string. This is also the default value of this property.

To get or set the contents of the non-standard body, use SpecialBodyText property. To get or set Content-Type of such body, use SpecialBodyContentType property.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Meeting request"
  Mailer.Message.SpecialBodyContentType = "text/calendar; method=REQUEST; name=""meeting.ics"""
  Mailer.Message.SpecialBodyHeaders = "Content-Class: urn:content-classes:calendarmessage" & vbCrLf
  Mailer.Message.SpecialBodyText = "BEGIN:VCALENDAR" & vbCrLf & "METHOD:REQUEST" & vbCrLf & "etc..."
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

SpecialBodyText Property
SpecialBodyContentType Property


SpecialBodyText Property

Contains the non-standard body of the message.

Usually e-mail messages contain plain-text and/or HTML bodies. However, they may also contain text bodies of non-standard types such as text/calendar (vCal items). You can use this property to get or set the body of such kind.

To get the type of such body, use SpecialBodyContentType property.

If the message does not have such body, this value is an empty string.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Special body = " & Msg.SpecialBodyText
   End If
   Mailer.Disconnect
End If

See Also:

SpecialBodyContentType Property
SpecialBodyHeaders Property


Subject Property

When the message is returned by MailBee.POP3 object, contains value of "Subject" header (or empty string if this header is missing).

When composing the message, use this property to specify message's subject.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "Subject: " & Msg.Subject
   End If
   Mailer.Disconnect
End If

See Also:

Message Object


ToAddr Property

Value of "To" header (primary recipients).

If composing the message, at least one of recipient specifiers (ToAddr, CCAddr, BCCAddr) must be set. Otherwise, SMTP server will reject the message. You can specify several email addresses, separating with commas (",").

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses. This only makes sense for reading an existing message, not for composing a new one (when sending a message, recipients must be separated with comma).

To deal with e-mail addresses with international domain names (IDN), use EscapeIdnDomain method to encode an e-mail address to IDN form (when sending out e-mails) or UnescapeIdnDomain method to decode an e-mail address into human-readable form (when receiving e-mails).

If the message was received using MailBee.POP3 object, the property is value of "To" header or empty string if this header is missing.

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com, joe (Skywalker) <jj@host.com>"
  Mailer.Message.CCAddr = "Jeff Jones<jeff@hissite.com> (ABC Company), margo.witch@herssite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

PureToAddr Property
ToFriendlyName Property
CCAddr Property
BCCAddr Property
FromAddr Property


ToFriendlyName Property

Returns comma-separated friendly names of "To:" (primary) recipients. If particular friendly name is not available, corresponding email address is returned instead.

For example, if ToAddr is like: "Mr. X, Y Company"<mr.x@y.com> (y.com), nofriendlyname@localhost, someone@host.net (Only comment)

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses. This only makes sense for reading an existing message, not for composing a new one (when sending a message, recipients must be separated with comma).

then ToFriendlyName will return: Mr. X, Y Company, nofriendlyname@localhost, Only comment

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "ToFriendlyName(s) = " & Msg.ToFriendlyName
   End If
   Mailer.Disconnect
End If

See Also:

ToAddr Property
PureToAddr Property
CCFriendlyName Property
FromFriendlyName Property


XMailer Property

When the message is returned by MailBee.POP3 object, contains value of "X-Mailer" header (or empty string if this header is missing).

When composing the message, you may set this property's value to the title of your program of mail delivery system. Default value is "MailBee".

Value Type: | String
Parameters: | None

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
Mailer.Message.XMailer = "Bob's mail program version 1.0"
Mailer.Message.ToAddr = "bill@yoursite.com"
Mailer.Message.FromAddr = "joe@mysite.com"
Mailer.Message.Subject = "Hello"
Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
If Mailer.Connect Then
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

Message Object


AddAttachment Method

Attaches a file to the message.

Attached files are automatically base64-encoded to comply with MIME requirements. This method can also handle inline objects (such as images) related in message body. However, you can use ImportBodyText method to let MailBee handle all inline objects itself.

blnResult = ObjectName.AddAttachment(FilePath, [ContentType], [ContentID], [FilenameInMessage])
Parameters: |
FilePath As String | The path to the file being attached
ContentType As String | (optional) If you already know Content-Type of the file, you may specify it. If this parameter is omitted, Content-Type is taken from filename extension
ContentID As String | (optional) Non-empty value denotes that the file is related in message body with specified Content-ID (i.e. inline object). Omitted or empty value denotes ordinary attachment (not inline object). Inline objects are usually not displayed by email clients in attachment lists.
FilenameInMessage As String | (optional) If the value is non-empty, it will be used in the message as attachment filename. For example, you have disk file "C:\Data\abc.tmp" and want to add it to the message as file "graph.gif". To do this, specify FilenameInMessage="graph.gif". If FilenameInMessage is missing or empty, filename extracted from FilePath parameter will be used. If FilenameInMessage="<none>" (angle brackets are important), no filename will be assigned at all (useful when forwarding e-mail messages as attachment).
Return value As Boolean | True if successful, False if error has occurred

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Message.AddAttachment "C:\docs\archive.zip"
  Mailer.Message.AddAttachment "C:\docs\picture.tmp", "image/gif","hello.gif", "hello.gif"
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

ImportBodyText Method
EncodeHeaderText Method
AddMemoryAttachment Method
BodyText Property
AltBodyText Property


AddHeader Method

Adds custom header to the message.

If you want to add header different from "To", "CC", "From", "Subject", "Date", "Message-ID", "Content-Type", "Content-Transfer-Encoding", "MIME-Version", "X-Mailer", "Return-Path", "Reply-To", use this method.

If specified header is already in the message, it will be overwritten.

blnResult = ObjectName.AddHeader(Name, Value)

Parameters: |
Name As String | Custom header name (like "X-Priority", "Organization", etc.)
Value As String | Custom header value
Return value As Boolean | True if successful. False if header name is empty or predefined (such as "From", "Date", etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.AddHeader "Organization", "AfterLogic Corp"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

GetHeader Method


AddMemoryAttachment Method

Creates an attachment from binary block of memory and attaches it to the message.

Attached files are automatically base64-encoded to comply with MIME requirements. This method can also handle inline objects (such as images) related in message body.

[Visual Basic]

blnResult = ObjectName.AddMemoryAttachment(Data, FilenameInMessage, [ContentType], [ContentID])

Parameters: |
Data As Variant | Attachment binary data represented as Byte Array.
FilenameInMessage As String | It will be used in the message as attachment filename. For instance, the developer has a disk file C:\Data\abc.tmp and he is going to add this file to the message as a graph.gif file . To do this, he should set FilenameInMessage="graph.gif". If FilenameInMessage="<none>" (angle brackets are important), no filename will be assigned at all (useful when forwarding e-mail messages as attachment).
ContentType As String | (optional) If you already know Content-Type of the file, you may specify it. If this parameter is omitted, Content-Type is taken from the filename extension.
ContentID As String | (optional) Non-empty value denotes that the file is related in message body with specified Content-ID (i.e. inline object). Omitted or empty value denotes ordinary attachment (not inline object). Inline objects are usually not displayed by email clients in attachment lists.
Return value As Boolean | True if successful, False if error has occurred.

Usage example:

<%
'  This is ASP-only sample which attaches last uploaded file to the message without creating any temporary files

Dim Mailer, Uploader, File

' Create new objects
Set Mailer = Server.CreateObject("MailBee.SMTP")
Set Uploader = Server.CreateObject("MailBee.Uploader")

' Specify MailBee license key
Mailer.LicenseKey = "put your license key here"

' Specify the name of the mail server
Mailer.ServerName = "mail.server.com"

' Try to connect to the specified mail server
If Mailer.Connect Then

  ' Specify the e-mail address of the message recipient
  Mailer.Message.ToAddr = "bill@yoursite.com"

  ' Specify the e-mail address of the message sender
  Mailer.Message.FromAddr = "joe@mysite.com"

  ' Specify the subject of the message
  Mailer.Message.Subject = "Hello"

  ' Import the text of the message body from file
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True

  ' Get the server's response as a binary array
  Uploader.ParseRequest(Request.BinaryRead(Request.TotalBytes))

  ' Check if the form contains any files
  If (Uploader.FormFiles.Count <> 0) Then
       ' Select the last file related to the form
       Set File = Uploader.FormFiles(Uploader.FormFiles.Count)

       ' Add attachment under the name of selected file
       Mailer.Message.AddMemoryAttachment File.ValueAsArray, File.FileName
  End If

  ' Send the message
  Mailer.Send

  ' Disconnect from the mail server
  Mailer.Disconnect
End If
%>

See Also:

AddAttachment Method, Uploader Object


AddStringAttachment Method

Creates an attachment from text string by converting data string to bytes and attaches it to the message.

After that, attached files are automatically encoded to base64 encoding to comply with MIME requirements. This method can also handle inline objects (such as images) related to the message body.

Because attachments are binary files (series of 8-bit bytes) while strings are series of 16-bit wide chars, MailBee needs to know how to convert wide chars of the source string into bytes of the attachment data. AsUTF8 parameter controls this.

Nevertheless, base64 encoding is still applied after string-to-bytes conversion, no matter what value AsUTF8 is.

blnResult = ObjectName.AddStringAttachment(Data, AsUTF8, FilenameInMessage, [ContentType], [ContentID])
Parameters: |
Data As String | Attachment text data represented as String.
AsUTF8 As Boolean | If True, will convert the source string into UTF-8 bytes. Otherwise, will use the default system encoding for conversion.
FilenameInMessage As String | Specifies the file name of the attachment in message. For example, if you have file "C:\Data\abc.tmp" and want to add it to the message as file "graph.gif", you just need to specify FilenameInMessage as "graph.gif". If FilenameInMessage="<none>" (angle brackets are important), no filename will be assigned at all (useful when forwarding e-mail messages as attachment).
ContentType As String | (optional) Specifies the Content-Type of file if it's already known. If this parameter is empty or ommited, Content-Type is taken from filename extension.
ContentID As String | (optional) Non-empty value denotes that the file is related tomessage body with specified Content-ID (i.e. inline object). Omitted or empty value denotes ordinary attachment (not inline object). Inline objects are usually not displayed by email clients in attachment lists.
Return value As Boolean | True if successful, False if error has occurred

Usage example:

<%
' This sample attaches text string as text file to the message without creating any temporary files

Dim Mailer, Uploader, File

' Using ASP to create the object
Set Mailer = Server.CreateObject("MailBee.SMTP")

' Using Visual Basic to create the object
'Set Mailer = CreateObject("MailBee.SMTP")

' Specify MailBee license key
Mailer.LicenseKey = "put your license key here"

' Specify the name of the mail server
Mailer.ServerName = "mail.server.com"

' Connect to the specified mail server
If Mailer.Connect Then
    ' Load the message from file
    Mailer.Message.ImportFromFile("C:\Temp\msg.eml")

    ' Add the attachment from string
    Mailer.Message.AddStringAttachment "This is attachment body", False, "sample.txt", "text/plain"

    ' Send the message
    Mailer.Send

    ' Disconnect from the mail server
    Mailer.Disconnect
End If
%>

See Also:

AddAttachment Method, Uploader Object


ConvertCharset Method

Converts the supplied string encoded in the given charset into another charset.

If you simply need to output certain string in UTF-8 encoding, use ToUTF8 method. The sample code in this topic emulates the effect of ToUTF8 via calling ConvertCharset method.

strConverted = ObjectName.ConvertCharset(Src, SrcCharset, DestCharset)

Parameters: |
Src As String | The source string encoded in SrcCharset.
SrcCharset As String | The charset encoding of the source string. If an empty string, it's assumed that Src is not encoded (i.e. it's Unicode).
DestCharset As String | The charset encoding of the output string. If an empty string, it's assumed that the output should be Unicode (i.e. it's not encoded).
Return value As String | The converted string, or the same string if both SrcCharset and DestCharset are empty strings.

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "International message"
  'Inform mail readers that the body contains UTF-8 data
  Mailer.Message.Charset = "utf-8"
  'Produce UTF-8 body
  Mailer.Message.BodyText = Mailer.Message.ConvertCharset("text with int. chars", "", "utf-8")
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

Charset Property


DecodeMstnef Method

Extracts attachments from MS-TNEF (winmail.dat) attachment if any, removes MS-TNEF attachments from Attachments collection, and returns the number of extracted files.

MS-TNEF is a proprietary e-mail format designed by Microsoft. In some cases, MS Outlook encapsulates files attached to e-mail message into a single MS-TNEF attachment. You should use this method to extract attachments from such e-mail messages.

lngCount = ObjectName.DecodeMstnef
Parameters: | None
Return value As Long | Number of extracted files if succeeded, 0 if no MS-TNEF was found in the attachments collection, -1 if there was error during extraction.

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    MsgBox "Extracted " & Msg.DecodeMstnef & " files from winmail.dat"
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "Content: " & Attach.Content
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Attachments Property


EncodeHeaderText Method

Encodes specified text string to allow using international characters (Japan, Korean, Russian, etc.) and very long header lines.

By default, MailBee encodes all headers with international names (Message.AutoEncodeHeaders=True). You need this method only for advanced purposes, when automatic encoding is not an option.

A standard header string may not contain international characters. Header encoding eliminates the problem, and also splits headers to multiple lines to avoid very long lines.

This method does not change message headers. It just returns encoded string you may assign to the message header value.

This method can also be used to encode attachment filenames (allows using international characters in attachment filenames).

Note: Some headers ("From", "To", "CC") contain e-mail address (it MUST NOT be encoded). So you must always properly set HeaderName so MailBee will use special encoding for address-containing headers.

strEncodedString = ObjectName.EncodeHeaderText(HeaderName, HeaderText, Charset, Encoding)
Parameters:
HeaderName As String | Case-insensitive name of the header to encode (like "Subject", "From", "To", "name"). Can be empty. Use empty value when encoding attachment filenames (if the value is empty, wrapping at 76-th character will no occur).
HeaderText As String | Text to encode (header value)
Charset As String | Charset used for composing HeaderText (for example, "windows-1251" if HeaderText is written in Russian)
Encoding As Long Specifies encoding to use. Only two encoding schemes are applicable for header encoding:
- Encoding = 2 - Quoted-Printable encoding
- Encoding = 3 - Base64 encoding
Return value As Boolean | On success, encoded value of HeaderText. On error, empty string.
Remarks: You can also use this method to encode attachment filenames containing international characters. An example below shows this.

Usage example:

Dim Mailer, strFilename
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = Mailer.EncodeHeaderText("From", "Алекс <alex@server.ru>", "windows-1251", 3)
  Mailer.Message.Subject = "Hello, There is word 'Alex' written in Russian in 'From' field"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  strFilename = Mailer.Message.EncodeHeaderText("name", "long or international filename to encode.htm", "us-english", 2)
  Mailer.Message.AddAttachment "C:\docs\long or international filename to encode.htm",,, strFilename
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

AddAttachment Method
BodyText Property
AltBodyText Property


EscapeIdnDomain Method

Encodes specified text string (e-mail address) to allow using international characters in domain name.

Use this method to convert domain part of e-mail address into Punycode. If the e-mail address does not have international characters, it will be left intact. Can be used for From, To, CC, etc.

As an e-mail address can also contain friendly name, be sure to apply this method only to the e-mail address itself. You can append friendly name later (like it's done in the sample code below).

strEscapedAddress = ObjectName.EscapeIdnDomain(EmailAddress)
Parameters: |
EmailAddress As String | E-mail address whose domain part to encode (like "user@domain").
Return value As String | E-mail address with Punycode-encoded domain part, or the source string if such encoding is not needed.
Remarks: | If you need to encode multiple addresses, you need to encode each address separately and concatenate the results then.

Usage example:

Dim Mailer, strFilename
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "Alex <" & Mailer.Message.EscapeIdnDomain("alex@почта.рф") & ">"
  Mailer.Message.Subject = "Hello, There is word 'pochta.rf' written in Russian in 'From' domain part"
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

UnescapeIdnDomain Method
FromAddr Property
ToAddr Property


GetBodyWithEmbeddedObjectsEx Method

Visual Basic Tutorial available! (3 pages)

ASP Tutorial available! (4 pages)

Prepares HTML-formatted messages for displaying, also saving embedded objects of the message into default or user-specified temporary location.

GetBodyWithEmbeddedObjectsEx method processes the message body (taken from BodyText property) replacing CIDs (Content-IDs) with corresponding attachments filenames and saving attachments required for displaying the message body (i.e. embedded objects) in specified directory. If the message body has non-HTML format, this stage is skipped.

This method by default also removes META charset information from the HTML message body. See RemoveCharsetFromBody method documentation on why this is useful.

The method returns prepared message body text. Original value of BodyText property is not affected.

strPreparedBody = ObjectName.GetBodyWithEmbeddedObjectsEx([TempDirectoryPath], [VirtualPath], [MessageDirectoryName], [PathBuildingMode], [Options], [Filter])
Parameters:
TempDirectoryPath As String | (optional) Path to the temporary directory where MailBee will create message directory for storing temporary files. If not specified, the current user's temporary directory will be used
VirtualPath As String | (optional) Virtual path to the physical location of TempDirectoryPath, or downloader URL (see PathBuildingMode parameter). If not specified, defaults to TempDirectoryPath
MessageDirectoryName As String | (optional) The name of the message directory to be created within TempDirectoryPath where temporary files of the current message will be placed. If not specified, the name will be generated by MailBee as MD5 digest of Message-ID
PathBuildingMode As Long (optional) Specifies the method of creating and translating physical file paths of the attachments into URLs that substitute CIDs in HTML tags. Options supported:
  • 0 - REAL mode (default value). Physical file paths will be used in SRC attributes of the tags. VirtualPath must be equal to TempDirectoryPath (or omitted). In this mode files can get overwritten if there are inline attachments with the same filename.
  • 1 - DIRECT mode. VirtualPath must denote virtual path (e.g. "http://www.server.com/path_to_data") to the physical location of TempDirectoryPath (e.g. "c:\inetpub\wwwroot\data"). Files are stored under real filenames.
  • 2 - INDEX mode. VirtualPath requirements as for DIRECT mode, but files are saved under temporary filenames ("1.jpg", "2.js", etc).
  • 3 - SCRIPT mode. VirtualPath must point to downloader URL (e.g. "http://www.server.com/download.asp?"). Files are saved under temporary filenames (as for INDEX mode). TempDirectoryPath may (and, for better security, should) point to the path unreachable from the web.
  • 4 - DIRECT and INDEX hybrid mode. To the real filename, [digit] index is appended. Ensures that files are not get overwritten even if their filenames are the same but still filenames resemble their original values. This mode produces more accurate results than REAL mode.
Options As Long | (optional) If 0, META chatset information will be removed from HTML source. If 1, this tag will be left intact. The default is 0 (remove META charset).
Filter as Object | (optional) Reserved for future use. Must be set to Nothing.
Return value As String | If successful, the result is a prepared body text. Otherwise, zero-length string is returned

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      MsgBox Msg.GetBodyWithEmbeddedObjectsEx(, , , 4, , ) ' Hybrid PathBuildingMode
   End If
   Mailer.Disconnect
End If

See Also:

"Displaying HTML-formatted messages in Visual Basic" Tutorial
"Displaying HTML-formatted messages in ASP" Tutorial

GetBodyWithEmbeddedObjects Method
RemoveMessageDirectory Method
GetMessageDirectoryPath Method


GetBodyWithEmbeddedObjects Method

Visual Basic Tutorial available! (3 pages)

Prepares HTML-formatted messages for displaying them locally, also saving embedded objects of the message into default or user-specified temporary location.

Note: It's recommended to use GetBodyWithEmbeddedObjectsEx method instead. It's more flexible and accurate.

GetBodyWithEmbeddedObjects method processes the message body (taken from BodyText property) replacing CIDs (Content-IDs) with corresponding attachments filenames and saving attachments required for displaying the message body (i.e. embedded objects) in specified directory. If the message body has non-HTML format, this stage is skipped.

The method returns prepared message body text. Original value of BodyText property is not affected.

As soon as message viewing is finished, call RemoveMessageDirectory method without parameters to remove temporary folder created by MailBee for displaying the message.

strPreparedBody = ObjectName.GetBodyWithEmbeddedObjects([TempDirectoryPath], [MessageDirectoryName], [Filter])
Parameters: |
TempDirectoryPath As String | (optional) Path to the temporary directory where MailBee will create message directory for storing temporary files. If not specified, the current user's temporary directory will be used
MessageDirectoryName As String | (optional) The name of the message directory to be created within TempDirectoryPath where temporary files of the current message will be placed. If not specified, the name will be generated by MailBee as MD5 digest of Message-ID
Filter as Object | (optional) reserved for future use. Leave it Nothing
Return value As String | If successful, the result is a prepared body text. Otherwise, zero-length string is returned

Usage example:

' VB-only sample (see ASP Tutorial for ASP samples)
Dim Mailer, Msg
Set Mailer = CreateObject("MailBee.POP3")
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      MsgBox Msg.GetBodyWithEmbeddedObjects(, , )
   End If
   Mailer.Disconnect
End If

See Also:

"Displaying HTML-formatted messages in Visual Basic" Tutorial
"Displaying HTML-formatted messages in ASP" Tutorial

GetBodyWithEmbeddedObjectsEx Method
RemoveMessageDirectory Method
GetMessageDirectoryPath Method


GetCodepageFromCharset Method

Returns codepage number for the specified charset.

strPlain = ObjectName.GetCodepageFromCharset(charset)
Parameters: |
Charset As String | The charset name
Return value As Long | The codepage number

Usage example:

Dim Msg, lngCodepage
'Using visual basic to create object
Set Msg = CreateObject("MailBee.Message")
'Using ASP to create object
'Set Msg = Server.CreateObject("MailBee.Message")
'In ASP use Response.Write instead of MsgBox
lngCodepage = Msg.GetCodepageFromCharset("utf-8")
MsgBox lngCodepage 'Displays "65001"

See Also:

Message Object


GetDateFromString Method

Converts specified datetime string (which must have format of "Date" message header) into Date type.

You can use this method to parse Date property of the Message object or any other date specified in this format.

date = ObjectName.GetDateFromString(DateStr, [ToLocalTime])
Parameters: |
DateStr As String | String containing date (for example, Date property value)
ToLocalTime | (optional) True by default, which means returned datetime is corrected to local timezone. If False, the datetime is returned in GMT (UTC) timezone
Return value As Date | Converted datetime value

Usage example:

Dim Msg, dDateTime
'Using visual basic to create object
Set Msg = CreateObject("MailBee.Message")
'Using ASP to create object
'Set Msg = Server.CreateObject("MailBee.Message")
'In ASP use Response.Write instead of MsgBox
dDateTime = Msg.GetDateFromString("Sat, 1 Nov 2003 11:32:37 -0500", False) ' Get specified date in UTC
MsgBox dDateTime ' Prints "11/01/2003 16:32:37" (if locale settings are in mm/dd/yyyy format)

See Also:

Message Object
Date Property


GetFileAsArray Method

On success, returns content of specified file as byte array. On error, returns Empty.

In ASP environment, this method is especially useful for downloading text or binary files such as pictures, ZIP files, documents, etc. to client machines. Common example of such files is message's attachments previously saved to disk. To save attachments to disk, you can use SaveFile method of Attachment object.

Note: Message's attachments can be downloaded directly from memory by using ContentAsArray property of Attachment object. This is useful if you do not want to save attachments to disk.

arrFile = ObjectName.GetFileAsArray([FilePath])
Parameters: |
FilePath As String | Path to the file, e.g. "C:\Data\picture01.gif"
Return value As Variant | Byte array of the file's data. If an error occurs, return value is Empty

Usage example:

' This ASP-only sample downloads specified file to the client
Dim Msg, Arr
Set Msg = Server.CreateObject("MailBee.Message")
Arr = Msg.GetFileAsArray("D:\Docs\file.zip")
If Not IsEmpty(Arr) Then
  Response.BinaryWrite Arr
Else
  Response.Write "File not found"
End If

See Also:

Attachment.SaveFile Method
Attachment.ContentAsArray Property


GetFriendlyName Method

Extracts and returns the friendly name (e.g. John Doe) from the specified full e-mail address (e.g. John Doe <jdoe@domain.com>). If multiple e-mail addresses specified, they must be delimited with commas.

For example, if FullAddr parameter is as following: "Mr. X, Y Company"<mr.x@y.com> (y.com), nofriendlyname@localhost, someone@host.net (Only comment)

then GetFriendlyName will return: Mr. X, Y Company, nofriendlyname@localhost, Only comment

strFriendlyName = ObjectName.GetFriendlyName(FullAddr)

Parameters: |
FullAddr As String | Full e-mail address or addresses to extract friendly name(s) for
Return value As String | Friendly name part of the specified full e-mail address

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        MsgBox "Reply-To person: " & Msg.GetFriendlyName(Msg.ReplyToAddr)
      End If ' If the message does not have Reply-To, empty string will be displayed
   End If
   Mailer.Disconnect
End If

See Also:

GetPureAddr Method


GetHeader Method

Returns value of specified message header (or empty string if there is no such header in the message).

strHeaderValue = ObjectName.GetHeader(HeaderName)

Parameters: |
HeaderName As String | name of message header (case is not significant, i.e. "X-Mailer" and "x-mailer" are equal)
Return value As String | String containing value of specified message header (or zero-length string if the header is not found)
Remarks: | You may use this method to get values for some rarely used headers not accessible through standard properties of Message object (standard properties are Subject, FromAddr, Date, ReplyTo, Received, and some others).

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        MsgBox "X-Mailer: " & Msg.GetHeader("X-Mailer")
      End If ' If the message does not have this header, empty string will be displayed
   End If
   Mailer.Disconnect
End If

See Also:

Message Object


GetHtmlFromPlain Method

Returns html version of specified plain text string by wrapping plain text with html tags (such as <html><head>, <title>, <body>, <pre>) and replacing some special characters with their html equivalents.

You can use this method for creating html body if only plain-text body is available.

If you want to insert the result of this method into another html, you can specify option "generate only body content" (InnerBodyOnly=True). In this case no <html><head><title><body> tags would be generated.

strHtml = ObjectName.GetHtmlFromPlain(PlainText, [Title], [InnerBodyOnly])
Parameters: |
PlainText As String | Source plain text string
Title As String | (optional) If specified (and InnerBodyOnly=False), <title> tag containing the title is added into <head> section
InnerBodyOnly As Boolean | (optional) If True, only section between <body> and </body> tags is returned (<body> and </body> themselves are not returned). Default is False
Return value As String | Html version of the source

Usage example:

' Example 1
Dim Msg, strHtml
'Using visual basic to create object
Set Msg = CreateObject("MailBee.Message")
'Using ASP to create object
'Set Msg = Server.CreateObject("MailBee.Message")
'In ASP use Response.Write instead of MsgBox
strHtml = Msg.GetHtmlFromPlain("first line" & vbCrLf & "second line", , True)
MsgBox strHtml

' Example 2
Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportAltBodyText "C:\docs\letter.txt"
  Mailer.Message.BodyText = _
    Mailer.Message.GetHtmlFromPlain(Mailer.Message.AltBodyText, _
    "Important message to you")
  Mailer.Message.BodyFormat = 1 ' Mark body as html body
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

Message Object
AltBodyText Property
ImportAltBodyText Method
GetPlainFromHtml Method


GetMD5Digest Method

Returns MD5 irreversible digest for the specified text.

Source text can be any string (including null or zero-length string). The method converts the string into bytes and then calculates the digest. The returned digest is guaranteed to be 32 characters length alphanumeric sequence (such as "706138b31d04788a2be339c4ede89f2f"). Each pair of characters ("70", "61", "38", "b3", "1d", etc.) indicates hexadecimal presentation of a byte.

You may use this digest for any purpose (such as encoding passwords). MailBee itself uses MD5 digests to generate name for the message directory created by GetBodyWithEmbeddedObjects and GetBodyWithEmbeddedObjectsEx methods. Corresponding message-id (Message.MessageID property) is used as a source text to calculate digest for.

The message directory path = Temporary directory path + "\" + GetMD5Digest(Message-ID).

The sample code below shows how MailBee creates name for the message directory.

strDigest = ObjectName.GetMD5Digest(Text, [Codepage])
Parameters: |
Text As String | String to get MD5 digest for
Codepage As Long | (optional) The codepage to use to convert text to bytes. The default value is 65001 (corresponds to UTF-8 charset).
Return value As String | MD5 digest of the specified string

Usage example:

' VB-only sample (see ASP tutorial for ASP samples)

Dim Mailer, Msg

Set Mailer = CreateObject("MailBee.POP3")
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)

    ' The next two lines are equivalents: they cause the same message directory to be created
    Msg.GetBodyWithEmbeddedObjects
    Msg.GetBodyWithEmbeddedObjects , Msg.GetMD5Digest(Msg.MessageID)

    MsgBox Msg.GetMessageDirectoryPath
    Msg.RemoveMessageDirectory
  End If
  Mailer.Disconnect
End If

See Also:

GetMD5DigestOfArray Method
GetBodyWithEmbeddedObjects Method
GetBodyWithEmbeddedObjectsEx Method
RemoveMessageDirectory Method
GetMessageDirectoryPath Method


GetMD5DigestOfArray Method

Returns MD5 irreversible digest for the specified byte array.

The example in this topic calculates MD5 digest of attachment (it's assumed the message has at least one attachment).

strDigest = ObjectName.GetMD5DigestOfArray(Data)
Parameters: |
Data As Variant | The byte array to get MD5 digest for
Return value As String | MD5 digest of the specified byte array

Usage example:

Dim Mailer, Msg

Set Mailer = CreateObject("MailBee.POP3")
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 110, "MyName", "MyPassword") Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Msg.Attachments.Count > 0 Then
      MsgBox Msg.GetMD5Digest(Msg.Attachments(1).ContentAsArray)
    End If
  End If
  Mailer.Disconnect
End If

See Also:

GetMD5Digest Method


GetMessageDirectoryPath Method

Visual Basic Tutorial available! (3 pages)

ASP Tutorial available! (4 pages)

Returns the path to the message directory previously created by GetBodyWithEmbeddedObjectsEx or GetBodyWithEmbeddedObjects method call.

This method is useful if the Message object is destroyed before its corresponding message directory becomes removed (this behavior is common in web environment where all objects are removed as soon as the page has been processed).

The value returned by this method should be stored somewhere (for example, in the Session for ASP or global variable for Visual Basic). Then (when the message directory becomes no longer needed) pass it to RemoveMessageDirectory method as a value of MessageDirectoryPath parameter.

Note: The message directory path may be empty string even if GetBodyWithEmbeddedObjectsEx or GetBodyWithEmbeddedObjects method has been already called. This just means the message had no embedded objects and there was no need to save any files and create the message directory.

strPath = ObjectName.GetMessageDirectoryPath
Parameters: | None
Return value As String | The path to the message directory

Usage example:

' VB-only sample (see ASP tutorial for ASP samples)
Dim MsgDirPath

Sub Form_Load()
  Dim Mailer, Msg

  Set Mailer = CreateObject("MailBee.POP3")
  Mailer.LicenseKey = "put your license key here"
  Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
  If Mailer.Connected Then
    If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      MsgBox Msg.GetBodyWithEmbeddedObjects(, , )
      MsgDirPath = Msg.GetMessageDirectoryPath
    End If
    Mailer.Disconnect
  End If
End Sub

Sub Form_Unload(Cancel As Integer)
  Dim Msg

  Set Msg = CreateObject("MailBee.Message")
  Msg.RemoveMessageDirectory MsgDirPath
End Sub

See Also:

"Displaying HTML-formatted messages in Visual Basic" Tutorial
"Displaying HTML-formatted messages in ASP" Tutorial

GetBodyWithEmbeddedObjects Method
GetBodyWithEmbeddedObjectsEx Method
RemoveMessageDirectory Method


GetPlainFromHtml Method

Returns plain-text version of specified HTML string by transforming <br>, <p> and some other tags into their text equivalents and removing all other tags (including <head>...</head> section).

If you need to get plain version of HTML message body, you can obtain it through Message.AltBodyText property.

strPlain = ObjectName.GetPlainFromHtml(Html)
Parameters: |
Html | Source HTML string
Return value As String | Plain-text version of the source

Usage example:

Dim Msg, strPlain
'Using visual basic to create object
Set Msg = CreateObject("MailBee.Message")
'Using ASP to create object
'Set Msg = Server.CreateObject("MailBee.Message")
'In ASP use Response.Write instead of MsgBox
strPlain = Msg.GetPlainFromHtml("<html>first line<br>second line</html>")
MsgBox strPlain

See Also:

Message Object
AltBodyText Property
GetHtmlFromPlain Method


GetPureAddr Method

Extracts and returns the pure e-mail address (e.g. jdoe@domain.com) from the specified full e-mail address (e.g. John Doe <jdoe@domain.com>). If multiple e-mail addresses specified, they must be delimited with commas.

For example, if FullAddr parameter is as following: "Mr. X, Y Company"<mr.x@y.com> (y.com), nofriendlyname@localhost, someone@host.net (Only comment)

then GetPureAddr will return: mr.x@y.com, nofriendlyname@localhost, someone@host.net

strPureAddr = ObjectName.GetPureAddr(FullAddr)

Parameters: |
FullAddr As String | Full e-mail address or addresses to extract friendly name(s) for
Return value As String | Pure e-mail address part of the specified full e-mail address

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        MsgBox "Reply-To e-mail: " & Msg.GetPureAddr(Msg.ReplyToAddr)
      End If ' If the message does not have Reply-To, empty string will be displayed
   End If
   Mailer.Disconnect
End If

See Also:

GetFriendlyName Method


ImportAltBodyText Method

Sets value of AltBodyText property by importing contents of specified file.

This method is useful if alternative (plain-text) presentation for html-formatted body is available in a file.

blnResult = ObjectName.ImportAltBodyText(FilePath, [AppendMode])
Parameters: |
FilePath As String | The path to the file containing alternative plain-text body
AppendMode As Boolean | (optional) If True, AltBodyText value is not overwritten by this method, but extended with value generated by ImportAltBodyText method. Default is False
Charset As String | (optional) The charset of the file being imported. If not specified, MailBee will assume the system default encoding to determine the charset of the file.
Return value As Boolean | True if successful. False if error has occurred (file not found, i/o error, etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportAltBodyText "C:\docs\letter.txt", True
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

ImportBodyText Method
AltBodyText Property


ImportBodyText Method

Sets value of BodyText property by importing contents of specified file. HTML import option is also available.

In HTML Import mode the following considerations are used while scanning tags of specified html file:

  • If the tag contains SRC or BACKGROUND attributes, corresponding files are added to attachments collection
  • If the tag is IMG or INPUT, LOWSRC attribute additionally used to get attachment sources
  • If the tag is LINK, HREF attribute additionally used to get attachment sources
  • File paths for embedded objects are considered to be relative to the directory, where specified html file resides. I.e. if you are importing html file "C:\Docs\file.html", and there is line <IMG SRC='images/pic.gif'>, MailBee will search for the file "C:\Docs\images\pic.gif"
  • If the file denoted by file path for embedded object is found, file is added to attachments collection (as inline object, so Attachment.IsInline=True), corresponding ContentID is generated for the attachment and the tag where embedded object is used is modified (for example, IMG tag will look like <IMG SRC="cid:9094130553-1">)
  • If the file denoted by file path for embedded object is NOT found, the tag will not be changed
Also, if HTML Import mode is active, the method sets BodyFormat=1 (HTML Format).

The method also offers some options to determine the charset of the file being imported.

blnResult = ObjectName.ImportBodyText(FilePath, [HTMLImport], [AppendMode])
Parameters:
FilePath As String | The path to the file containing body text
HTMLImport As Boolean | (optional) If True, HTML import mode is active. In this mode MailBee scans specified file for embedded objects, images, etc. and adds them as inline attachments to the message. If False, plain text import is assumed. Default value is False
AppendMode As Boolean | (optional) If True, BodyText value is not overwritten by this method, but extended with value generated by ImportBodyText method. Default is False
Charset As String | (optional) The charset of the file being imported. If not specified, MailBee will assume the system default encoding to set the charset. In case of HTML import, however, MailBee by default detects the charset from the META charset tag specified in the HTML source itself.
CharsetOptions As Long

(optional) A set of flags (some of which can be combined together) which affect how the charset of the HTML file being imported will be determined:
1 - Leave META charset tag in the HTML if it's there (cannot be combined with flag value 4). If this flag is not set, META charset tag is always removed from the imported HTML source.
2 - Set the determined charset for the entire message (Message.Charset property). Lets you automatically set the charset for the message based on the charset in the HTML file being imported. You'll usually combine this with flag 1, i.e. 1 + 2 = 3.
4 - Ignore META charset tag value contained in the HTML file if the charset was explicitly specified in Charset parameter.

The default value is 0 which means the following:

- META charset tag is removed from the HTML source
- If META charset tag was present in the HTML source, it will be used to determine the charset of the HTML
- If META charset tag was NOT present in the HTML, MailBee will use Charset parameter to determine the charset
- If both META charset and Charset parameters are not available, MailBee will assume the default system encoding to determine the charset
- The charset of the e-mail message itself (Message.Charset property) will be left intact. By default, it's "utf-8".

Return value As Boolean | True if successful. False if error has occurred (file not found, i/o error, etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

ImportAltBodyText Method
BodyText Property
BodyFormat Property


ImportFromFile Method

Loads and parses an e-mail message from a disk file.

The file must contain RFC822-compliant message (such files usually have ".eml" extension). SaveMessage method of the Message object saves files in this format.

Note: To "blind-forward" (resend without modifications) previously saved message it's better to use RelayMessage method of the SMTP object.

blnResult = ObjectName.ImportFromFile(FilePath)
Parameters: |
FilePath As String | The path to the file to load
Return value As Boolean | True if successful. False if error has occurred (file not found, i/o error, etc.)

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ImportFromFile "C:\docs\letter.eml"

  ' Add some modifications to the message (otherwise RelayMessage would be enough)
  Mailer.Subject = "FW:" & Mailer.Subject

  Mailer.Send
  Mailer.Disconnect
End If

See Also:

SMTP.Send Method
SMTP.RelayMessage Method


ImportFromMemory Method

Loads the message from binary block of memory (the data must be in MIME format).

[Visual Basic]

blnResult = ObjectName.ImportFromMemory(Data)

Parameters: |
Data As Variant | Message MIME data represented as Byte Array.
Return value As Boolean | True if successful, False if error has occurred.

Usage example:

<%
'  This is ASP-only sample which the message from last uploaded file (it must be in MIME/EML format) without creating any temporary files

Dim Mailer, Uploader, File

' Create new objects
Set Mailer = Server.CreateObject("MailBee.SMTP")
Set Uploader = Server.CreateObject("MailBee.Uploader")

' Specify MailBee license key
Mailer.LicenseKey = "put your license key here"

' Specify the name of the mail server
Mailer.ServerName = "mail.server.com"

' Try to connect to the specified mail server
If Mailer.Connect Then
  ' Get the server's response as a binary array
  Uploader.ParseRequest(Request.BinaryRead(Request.TotalBytes))

  ' Check if the form contains any files
  If (Uploader.FormFiles.Count <> 0) Then
       ' Select the last file related to the form
       Set File = Uploader.FormFiles(Uploader.FormFiles.Count)

       ' Load the email to be sent from the selected file
       Mailer.Message.ImportFromMemory File.ValueAsArray
  End If

  ' Send the message
  Mailer.Send

  ' Disconnect from the mail server
  Mailer.Disconnect
End If
%>

See Also:

AddMemoryAttachment Method, Uploader Object


MakeAltBody Method

Produces plain-text version of HTML-formatted BodyText and assigns it to AltBodyText property.

If BodyText does not contain HTML-formatted body (i.e. BodyFormat<>1), this method does nothing.

You may use this method to create alternative plain-text version of existing html-formatted body.

blnResult = ObjectName.MakeAltBody
Parameters: | None
Return value As Boolean | True if successful, False otherwise

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\letter.htm", True
  Mailer.MakeAltBody
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

ImportAltBodyText Method
AltBodyText Property
BodyText Property
BodyFormat Property


MessageDirectoryExists Method

Visual Basic Tutorial available! (3 pages)

ASP Tutorial available! (4 pages)

Returns whether the message directory was really created by GetBodyWithEmbeddedObjectsEx or GetBodyWithEmbeddedObjects method call.

GetBodyWithEmbeddedObjects and GetBodyWithEmbeddedObjectsEx methods will not create the message directory if it is not needed. Only if the message contains any embedded objects, the message directory is created.

Another reason of the message directory not been created is when the required path could not be created (for example, there is already file under the given name).

MessageDirectoryPath parameter may be omitted if GetBodyWithEmbeddedObjects or GetBodyWithEmbeddedObjectsEx method has been already called for the same instance of the Message object.

Also, you may use this method for testing any paths for their existence and being directory.

blnResult = ObjectName.MessageDirectoryExists([MessageDirectoryPath])
Parameters: |
MessageDirectoryPath As String | (optional) The path to the message directory created by MailBee for the message. If omitted, the path is taken from internal variable that is set by GetBodyWithEmbeddedObjects and GetBodyWithEmbeddedObjectsEx methods
Return value As Boolean | True if the message directory exists and it is a directory (not a file), False otherwise

Usage example:

' VB-only sample (see ASP Tutorial for ASP samples)
Dim Mailer, Msg
Set Mailer = CreateObject("MailBee.POP3")
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      MsgBox Msg.GetBodyWithEmbeddedObjects(, , )
      MsgBox "Message dir exists? - " & Msg.MessageDirectoryExists
      Msg.RemoveMessageDirectory
   End If
   Mailer.Disconnect
End If

See Also:

"Displaying HTML-formatted messages in Visual Basic" Tutorial
"Displaying HTML-formatted messages in ASP" Tutorial

GetBodyWithEmbeddedObjects Method
GetBodyWithEmbeddedObjectsEx Method
RemoveMessageDirectory Method
GetMessageDirectoryPath Method


RemoveCharsetFromBody Method

Removes the meta tag containing the charset declaration of the document from the HTML body, and returns the charset removed.

This method scans the contents of BodyText property for <meta ... Content="... charset=..."> declaration and removes this tag from the BodyText value, returning the charset removed. This is useful when you convert the charset of the HTML so that the charset setting in the HTML no longer matches the actual charset of the document.

Note that ImportBodyText method used in the sample below can also remove META charset tag via optional parameters setting. On other hand, if you received an existing message rather than composed a new one, you can use GetBodyWithEmbeddedObjectsEx method to prepare HTML body and strip META charset tag. Therefore, in most cases you'll not need to call RemoveCharsetFromBody method directly.

strCharset = ObjectName.RemoveCharsetFromBody
Parameters: | None
Return value As String | The charset of the message as extracted from meta tag.

Usage example:

Dim Mailer, strCharset
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  Mailer.Message.Subject = "Hello"
  Mailer.Message.ImportBodyText "C:\docs\e-mail.htm", True
  strCharset = Mailer.Message.RemoveCharsetFromBody
  Mailer.Message.ConvertCharset Mailer.Message.BodyText, strCharset, "UTF-8"
  Mailer.Message.Charset = "UTF-8"
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

Message Object
Charset Property
ConvertCharset Method


RemoveHeader Method

This method removes custom header from the message.

blnResult = ObjectName.RemoveHeader(HeaderName)

Parameters: |
HeaderName As String | Custom header name (like "X-Priority", "Organization", etc.)
Return value As Boolean | True if successful. False if header name is empty, predefined (such as "From", "Date", etc.) or there is no such a header in this message.

Usage example:

' This sample retrieves first message in the account and in case if "X-Priority" header presents in the message removes it.
' Then, sends modified message back to the server.
Dim MailerPOP, MailerSMTP, Msg
' Using visual basic to create object
Set MailerPOP = CreateObject("MailBee.POP3")
Set MailerSMTP = CreateObject("MailBee.SMTP")
' Using ASP to create object
' Set MailerPOP = Server.CreateObject("MailBee.POP3")
' Set MailerSMTP = Server.CreateObject("MailBee.SMTP")
' In ASP use Response.Write instead of MsgBox
MailerPOP.LicenseKey = "put your license key"
MailerSMTP.LicenseKey = "put your license key"
MailerSMTP.ServerName = "mailserver.com"
If MailerPOP.Connect("mailserver.com", 110, "MyName", "MyPassword") Then
   If MailerPOP.MessageCount > 0 Then
      Set Msg = MailerPOP.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
         ' Check if specified header presents in a message
         If Msg.GetHeader("X-Priority") <> "" Then
            If Msg.RemoveHeader("X-Priority") Then
               MsgBox "Header successfully removed"
            Else
               MsgBox "Failed to remove header"
            End If
         End If
         Set MailerSMTP.Message = Msg

         ' Send modified message back to the server
         If Not MailerSMTP.Send Then
            MsgBox "Error #" & MailerSMTP.ErrCode & ", " & MailerSMTP.ErrDesc
         Else
            MailerSMTP.Disconnect
         End If
      End If
   Else
      MsgBox "Your mailbox is empty."
   End If
   MailerPOP.Disconnect
End If

See Also:

AddHeader Method | GetHeader Method | Message Object | POP3 Object | SMTP Object


RemoveMessageDirectory Method

Visual Basic Tutorial available! (3 pages)

ASP Tutorial available! (4 pages)

Destroys the message temporary directory (with all its contents) previously created by GetBodyWithEmbeddedObjectsEx or GetBodyWithEmbeddedObjects method call.

Message object internally stores the path to the message directory created by GetBodyWithEmbeddedObjects or GetBodyWithEmbeddedObjectsEx methods. However, when the Message object is freed, this information is lost.

If you're going to destroy the message temporary directory during lifetime of the Message object, you may call RemoveMessageDirectory method without parameters.

Another approach (useful for web environments where objects are created and destroyed each time the user makes request to the server) is to obtain the message directory path through the call of GetMessageDirectoryPath method and save returned value for later use. You must call GetMessageDirectoryPath method AFTER calling GetBodyWithEmbeddedObjects or GetBodyWithEmbeddedObjectsEx methods. When the time to clean up comes, call RemoveMessageDirectory method using previously stored value as MessageDirectoryPath parameter.

If MessageDirectoryPath parameter is omitted, the method will destroy the temporary message directory ONLY IF GetBodyWithEmbeddedObjectsEx or GetBodyWithEmbeddedObjects method has been already called for the same instance of the Message object.

blnResult = ObjectName.RemoveMessageDirectory([MessageDirectoryPath], [DeleteContentOnly])
Parameters: |
MessageDirectoryPath As String | (optional) The path to the temporary message directory created by MailBee for the message. If omitted, the path is taken from internal variable that is set by GetBodyWithEmbeddedObjects or GetBodyWithEmbeddedObjectsEx methods
DeleteContentOnly As Boolean | (optional) If True, the method will remove all files from the message directory, but the directory itself will NOT be deleted. Default is False
Return value As Boolean | True if successful, False if error occurred (the path doesn't exist, some files are locked, etc.)

Usage example:

' VB-only sample (see ASP Tutorial for ASP samples)
Dim Mailer, Msg
Set Mailer = CreateObject("MailBee.POP3")
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      MsgBox Msg.GetBodyWithEmbeddedObjects(, , )
      ' Clean up once the user has finished viewing the message
      Msg.RemoveMessageDirectory
   End If
   Mailer.Disconnect
End If

See Also:

"Displaying HTML-formatted messages in Visual Basic" Tutorial
"Displaying HTML-formatted messages in ASP" Tutorial

GetBodyWithEmbeddedObjects Method
GetBodyWithEmbeddedObjectsEx Method
GetMessageDirectoryPath Method


SaveMessage Method

Saves content of RawBody property into the file.

The file will contain RFC822 formatted message, so you can, for example, pass this file to SMTP.RelayMessage method.

blnResult = ObjectName.SaveMessage(FilePath)
Parameters: |
FilePath As String | Absolute or relative path where to save file containing message source
Return value As Boolean | True if successful, False if error has occurred

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then
        Msg.SaveMessage "C:\Docs\msg.eml"
      End If
   End If
   Mailer.Disconnect
End If

See Also:

Message Object
RawBody Property
SMTP.RelayMessage Method


ToUTF8 Method

Returns source string converted in UTF-8 format.

UTF-8 format is used to represent international characters in e-mail. It is especially useful when a e-mail is written in several languages.

Note that in most cases you won't need to use this method directly as MailBee by default encodes e-mails being composed in UTF-8. The typical case of using this method is when you need to output the data you received from an existing e-mail onto web page in UTF-8 format.

strUTF8 = ObjectName.ToUTF8(Src, [SrcCharset])
Parameters: |
Src As String | Source text string (if SrcCharset parameter is omitted, this string must be in Unicode format)
SrcCharset As String | (optional) Charset (such as "us-ascii", "iso-8859-1", "gb2312", etc.) used to compose Src. If omitted, default ANSI codepage of the machine is assumed
Return value As String | UTF-8 version of the source

Usage example:

Dim Mailer, strUTF8, strUnicodeSubject, strUnicodeBody

' Assume strUnicodeSubject and strUnicodeBody already contain some unicode text
strUnicodeSubject = "some unicode chars here"
strUnicodeBody = "some unicode chars here"

'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  Mailer.Message.ToAddr = "bill@yoursite.com"
  Mailer.Message.FromAddr = "joe@mysite.com"
  strUTF8 = Mailer.Message.ToUTF8(strUnicodeSubject)
  Mailer.Message.Subject = Mailer.Message.EncodeHeaderText("Subject", strUTF8, "utf-8", 3)
  Mailer.Message.BodyText = Mailer.Message.ToUTF8(strUnicodeBody)
  Mailer.Message.Charset = "utf-8"
  Mailer.Send
  Mailer.Disconnect
End If

See Also:

Message Object
Charset Property
EncodeHeaderText Method


UnescapeIdnDomain Method

Decodes the e-mail address string with Punycode-encoded domain part (IDN) into human-readable form.

Use this method to convert domain part of e-mail address back from Punycode. If the e-mail address does not have international characters, it will be left intact. Can be used for From, To, CC, etc.

As an e-mail address can also contain friendly name, be sure to apply this method to the e-mail address itself ("pure" address). You can use a property like PureFromAddr for that. Also, if you have several addresses (e.g. To or CC field), you need to feed only a single address to this method at once (see Remarks below).

strEscapedAddress = ObjectName.EscapeIdnDomain(EmailAddress)
Parameters: |
EmailAddress As String | E-mail address whose domain part to encode (like "user@domain".
Return value As String | E-mail address with Punycode-encoded domain part, or the source string if such encoding is not needed.
Remarks: | If you need to decode multiple addresses (such as when decoding PureToAddr property value), you need to split the returned string by "," and decode each address separately. After that, you can concatenate the results back (if you need to).

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
   If Mailer.MessageCount > 0 Then
      Set Msg = Mailer.RetrieveSingleMessage(1)
      If Not Msg Is Nothing Then MsgBox "From e-mail(s) = " & Msg.UnescapeIdnDomain(Msg.PureFromAddr)
   End If
   Mailer.Disconnect
End If

See Also:

EscapeIdnDomain Method
PureFromAddr Property
PureToAddr Property


ValidateEmailAddress Method

Tests whether specified email address is correct.

This address must be "pure", i.e. without friendly names or comments. To get pure email address of the sender use PureFromAddr property.

The method checks email address syntax and optionally performs simple DNS query to check whether email address domain (the part after "@" symbol) is a valid email domain.

Note: It's strongly recommended that you explicitly specify DNS server name in DNSServer parameter. Although this parameter can be autodetected from Windows, the Windows API functions used for this can produce memory or resource leaks in certain installations.

blnResult = ObjectName.ValidateEmailAddress(EmailAddress, [Options])
Parameters:
EmailAddress As String | Email address to check. E.g. "user@server.com" or "info@[127.0.0.1]".
Options As Long (optional) Specifies email address validation level. Higher level requires more time to execute. Options supported:
  • 0 - Perform syntax check only (default value)
  • 1 - Perform syntax check and simple DNS query to validate email address domain
DNSServer As String | (optional) Specifies DNS server name to be used for resolving host names into IP addresses.
Return value As Boolean | True if email address seems to be correct. False if email address is invalid or can not be validated (DNS server failed, etc.)
Remarks: There is no 100% guarantee that email address is correct even if its syntax is OK and the domain exists. The only reliable way to validate email address is to send email to this address and then check whether bounce mail returned for this address

Usage example:

Dim Msg, dDateTime
'Using visual basic to create object
Set Msg = CreateObject("MailBee.Message")
'Using ASP to create object
'Set Msg = Server.CreateObject("MailBee.Message")
'In ASP use Response.Write instead of MsgBox
If Msg.ValidateEmailAddress("abc@pbox.server.com", 1) Then
  MsgBox "Email address seems to be valid"
Else
  MsgBox "Email address is invalid or cannot be checked"
End If

See Also:

PureFromAddr Property
PureToAddr Property
PureCCAddr Property


WriteStringToFile Method

Writes the specified string into the specified file.

The method lets you specify the codepage to use when saving the string (which is a sequence of 16-bit Unicode characters) into the file (which is a sequence of 8-bit bytes). If you know only the charset name but not the codepage, you can get the codepage number with GetCodepageFromCharset method.

This is a helper method you can use for writing any strings to files. For instance, you can use it to write your own entries into MailBee log files.

blnResult = ObjectName.WriteStringToFile(Filename, Data, [Overwrite], [Codepage])
Parameters: |
Filename As String | The file path to the file.
Data As String | The string to write to file.
Overwrite As Boolean | (optional) If True, MailBee will overwite the file. If False (the default value), MailBee will append to the file. Anyway, the file will be created if it does not exist.
Codepage As Long | (optional) The codepage of the encoding to use when writing the string into the file. By default, the system's default codepage 0 is used.
Return value As Boolean | True on success, False on error.

Usage example:

Dim Msg, dDateTime
'Using visual basic to create object
Set Msg = CreateObject("MailBee.Message")
'Using ASP to create object
'Set Msg = Server.CreateObject("MailBee.Message")
'In ASP use Response.Write instead of MsgBox
If Msg.WriteStringToFile("C:\Temp\logfile.txt", "log file entry" & vbCrLf) Then
  MsgBox "OK"
Else
  MsgBox "Error"
End If

See Also:

GetCodepageFromCharset Method


Messages Collection

The Messages collection contains Message objects used to examine properties of the downloaded messages and the messages headers.

To obtain the Messages collection, either call RetrieveMessages or RetrieveHeaders methods of the POP3 object. The IMAP4 object utilizes the Envelopes collection instead of the Messages collection.

Syntax

Messages.property

Properties
Count | Returns the number of Message objects in the collection.
Item | Returns a reference to Message object in the collection.

Remarks

Item is the default property of the collection, so Messages.Item(index) and Messages(index) are equivalents.

To iterate through the collection, you can use either For .. Each statement or any common loop statement such as For .. To.

Example

The following examples use different syntax to display "Subject:" field of all messages in the POP3 mailbox. It's assumed the Messages collection has been already obtained with RetrieveHeaders method call and stored in objMessages variable.

For .. Each syntax
For Each objMessage In objMessages
  MsgBox objMessage.Subject
  ' In ASP, use Response.Write instead of MsgBox
Next

For .. To syntax
For I = 1 To objMessages.Count
  MsgBox objMessages(I).Subject
  ' In ASP, use Response.Write instead of MsgBox
Next

See Also

Message Object, POP3 Object

Send feedback to AfterLogic


Count Property

Number of the messages in the Messages collection. If the collection is empty, the value is zero.

If the collection was created using RetrieveMessages or RetrieveHeaders methods of MailBee.POP3 object, the following expression is True:

Messages.Count = POP3.MessageCount

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msgs
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  Set Msgs = Mailer.RetrieveHeaders
  MsgBox "Headers received for " & Msgs.Count & " messages"
  Mailer.Disconnect
End If

See Also:

Item Property
Message Object
POP3.MessageCount Property
POP3.RetrieveMessages Method
POP3.RetrieveHeaders Method


Item Property

Returns message with the specified Index from the collection. If Index is out of range, automation error occurs.

This is default property of the Messages collection. The following two statements (assuming Msgs has MailBee.Messages type) are equivalent:

Set Msg = Msgs(1)

and

Set Msg = Msgs.Item(1)

Value Type: | MailBee.Message
Parameters: |
Index As Long | Index of the message to return. Allowed range is: 1 <= Index <= Messages.Count
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msgs
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  Set Msgs = Mailer.RetrieveHeaders
  If Msgs.Count > 0 Then
    MsgBox "Subject of the first message: " & Msgs(1).Subject
  End If
  Mailer.Disconnect
End If

See Also:

Count Property
Message Object
Messages Collection
POP3.RetrieveHeaders Method


Attachment Object

The Attachment object provides access to properties of a single attachment to a message and includes methods to save the attachment to a disk file.

Syntax

Attachment.property|method

Properties
Content | Binary content of the attachment as String.
ContentAsArray | Binary content of the attachment as Byte Array.
ContentID | The Content-ID value taken from the attachment header.
ContentLocation | The Content-Location value taken from the attachment header.
Content-Type | The Content-Type value taken from the attachment header.
Filename | The filename of the attachment, or an autogenerated name if the attachment has no name.
FilenameAsIs | The filename of the attachment, or an empty string if the attachment has no name.
IsInline | Indicates whether the attachment is an inline object (such as embedded picture).
IsMessage | Indicates whether the attachment contains another e-mail message (such as forwarded message).
Size | The size of the attachment's binary content in bytes.
Methods
SaveFile | Saves the attachment to disk.

Example

The following example retrieves a message from the server and saves all of the attachments found in the message into a disk folder.
Dim objPOP3, objMsg, objAttach

' Using Visual Basic to create object
Set objPOP3 = CreateObject("MailBee.POP3")

' Using ASP to create object
' Set objPOP3 = Server.CreateObject("MailBee.POP3")
'
' In ASP, use Response.Write instead of MsgBox

objPOP3.LicenseKey = "put your license key here"

' Connect to the server
If objPOP3.Connect("mail.server.com", 110, "jdoe", "secret") Then

  ' Retrieve first message
  Set objMsg = objPOP3.RetrieveSingleMessage(1)

  If objPOP3.IsError Then
    ' Check for errors
    MsgBox "Error #" & objPOP3.ErrCode
  Else
    ' Iterate through all of the attachments
    For Each objAttach In objMsg.Attachments
      ' Save each attachment to disk
      If Not objAttach.SaveFile("C:\Attachments") Then
        MsgBox "Could not save a file"
      End If
    Next
  End If

  ' Disconnect when finished
  objPOP3.Disconnect
End If

See Also

Attachments Collection

Send feedback to AfterLogic


Content Property

Contains the binary content of the attachment as a string.

If the attachment is, for example, a GIF file, Content property contains binary string of image bytes; if the attachment is a text file, Content property contains the text.

To get the attachment's content as an array use ContentAsArray property. This is useful for downloading files with ASP's BinaryWrite method.

In the case when the attachment was previously saved to disk, you can use GetFileAsArray method of the Message object to get file's content as array.

To save the attachment's content to disk, use SaveFile method.

Note: To determine the size of the attachment, it's more efficient to use Size property instead of Len(Attachment.Content).

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "Content: " & Attach.Content
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

ContentAsArray Property
Filename Property
Size Property
SaveFile Method
IsInline Property

Message.GetFileAsArray Method


ContentAsArray Property

Contains binary content of the attachment as a byte array.

This property contains the same data as Content property does, but this data is in the form of an array rather than a string. In ASP, this is useful for downloading files via Response.BinaryWrite method.

In the case where the attachment was previously saved to disk, you can use GetFileAsArray method of the Message object to get file's content as array.

Value Type: | Variant of type Byte Array
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This ASP-only sample downloads the attachment to the client
Dim Mailer, Msg
Set Mailer = Server.CreateObject("MailBee.POP3")
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 110, "MyName", "MyPassword") Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      If Msg.Attachments.Count > 0 Then
        Response.BinaryWrite Msg.Attachments(1).ContentAsArray
      End If
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Content Property

Message.GetFileAsArray Method


ContentID Property

Value of "Content-ID" header of the attachment (usually it is non-empty for embedded images and other documents related in the message body as CIDs). Such documents are called inline objects (and their IsInline property is set to True).

Note: ContentID property is often enclosed in "<>" symbols. To get the pure value of Content-ID, use PureContentID property instead.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "ContentID: " & Attach.ContentID
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

PureContentID Property
IsInline Property


ContentLocation Property

Value of "Content-Location" header of the attachment (often, it's an alternative to Content-ID).

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "Content-Location: " & Attach.ContentLocation
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

ContentID Property


ContentType Property

Value of "Content-Type" header of the attachment (or empty string if the header is missing). For example, JPEG files usually have "image/jpeg" Content-Type.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "ContentType: " & Attach.ContentType
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Filename Property
PureContentID Property
IsInline Property


Count Property

Number of attachments in the Attachments collection of the message. If the collection is empty, the value is zero.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    MsgBox "The message has " & Msg.Attachments.Count & " attachments"
  End If
  Mailer.Disconnect
End If

See Also:

Item Property
Attachment Object
Attachments Collection
Message Object


Filename Property

Value of "filename" field of the attachment headers. If "filename" field is not available, "name" field is returned. If both "filename" and "name" are missing, the property value is autogenerated (ATT<some-number>.<extension>). Extension is determined from the content-type.

To get the filename without autogeneration (so that empty name remains empty), use FilenameAsIs property.

Note: Filename (and FilenameAsIs) property always truncates path from original filename. E.g. if the attachment headers are: Content-Type: image/gif; name="_city_cat/030821xx.gif"

then Filename property will return "030821xx.gif".

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "Filename: " & Attach.Filename
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

ContentType Property
SaveFile Method
IsInline Property


FilenameAsIs Property

Value of "filename" field of the attachment headers. If "filename" field is not available, "name" field is returned. If both "filename" and "name" are missing, the property is an empty string.

Note: FilenameAsIs property always truncates path from original filename. E.g. if the attachment headers are: Content-Type: image/gif; name="_city_cat/030821xx.gif"

then FilenameAsIs property will return "030821xx.gif".

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "Filename (can be empty): " & Attach.FilenameAsIs
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

ContentType Property
SaveFile Method
IsInline Property


IsInline Property

True, if the attachment is an inline object (such as image related in html-formatted body), and False if the attachment was explicitly attached to the message (such as attached zip file).

Inline objects are used to correctly display message body (images, sounds, style-sheets, javascripts, etc.), while non-inline objects usually correspond to documents, archives, programs (n.b.: all files considered to be attachments from user's point of view).

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        If Attach.IsInline Then
          MsgBox "Inline Attachment (related in the message body)"
        Else
          MsgBox "Ordinary Attachment (attached by the user)"
        End If
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Filename Property
PureContentID Property
SaveFile Method


IsMessage Property

True, if the attachment holds RFC822-formatted message inside (for example, if the message was forwarded as attachment of another, containing message), False otherwise.

If True, you can create new Message object manually and pass value of Attachment.Content to Message.RawBody to load the message from the attachment.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach, AttachedMsg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        If Attach.IsMessage Then
          ' For ASP: Set AttachedMsg = Server.CreateObject("MailBee.Message")
          Set AttachedMsg = CreateObject("MailBee.Message")
          AttachedMsg.RawBody = Attach.Content
          MsgBox "Subject of attached message: " & AttachedMsg.Subject
        End If
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Content Property
Message Object


Item Property

Returns attachment with the specified Index from the Attachments collection of the message. If Index is out of range, automation error occurs.

This is default property of the Attachments collection. The following two statements (assuming Attachs has MailBee.Attachments type) are equivalent:

Set Attach = Attachs(1)

and

Set Attach = Attachs.Item(1)

Value Type: | MailBee.Attachment
Parameters: |
Index As Long | Index of the attachment to return. Allowed range is: 1 <= Index <= Attachments.Count
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Msg.Attachments.Count > 0 Then
      MsgBox "Filename of the first attachment: " & Msg.Attachments(1).Filename
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Count Property
Attachment Object
Attachments Collection
Message Object


PureContentID Property

Returns undecorated value of "Content-ID" header (trimming quotes and "<>" symbols). ContentIDs are referred to in message body as CIDs.

Suppose one of the message's attachments has ContentID property = "<122234@43500-2c04>" and the following tag is present somewhere in the message body:

<IMG SRC="CID:122234@43500-2c04" WIDTH="100" HEIGHT="60">

In this case PureContentId = "122234@43500-2c04" (angle brackets were trimmed). Because this value is equal to CID value in IMG SRC tag, the image for the tag must be taken from this attachment.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "PureContentID = " & Attach.PureContentID
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

ContentID Property
IsInline Property


Size Property

The size of the attachment's content (in bytes).

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        MsgBox "The size is: " & Attach.Size
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Filename Property
Content Property
SaveFile Method
IsInline Property


SaveFile Method

Writes content of the attachment (value of Content property) to disk.

blnResult = ObjectName.SaveFile(DirPath, [Filename])
Parameters: |
DirPath As String | Path to the directory where to store attached file
Filename As String | (optional) The attachment will be saved to disk under this name. If this parameter is omitted, Attachment.Filename property will be used as filename
Return value As Boolean | True if successful, False if error has occurred

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      For Each Attach In Msg.Attachments
        If Not Attach.SaveFile ("C:\Data Files") Then MsgBox "I/O Error"
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Attachment Object
IsInline Property
Content Property


Remove Method

Removes the attachment with the specified index from the collection.

This method can be used, for example, to remove attachments from the existing message.

blnResult = ObjectName.Remove(Index)
Parameters: |
Index As Long | Index of the attachment to be removed. Allowed range is: 1 <= Index <= Attachments.Count
Return value As Boolean | True if successful, False if error has occurred

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      If Msg.Attachments.Count > 0 Then
        ' Remove first attachment from the message
        Msg.Attachments.Remove 1
      End If
    End If
  End If
  Mailer.Disconnect
End If

See Also:

RemoveAll Method


RemoveAll Method

Removes all the attachments from the collection.

This method can be used, for example, to clear list of attachments in the existing message.

ObjectName.RemoveAll
Parameters: | None
Return value | None

Usage example:

Dim Mailer, Msg, Attach
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.POP3")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.POP3")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
Mailer.Connect "mailserver.com", 110, "MyName", "MyPassword"
If Mailer.Connected Then
  If Mailer.MessageCount > 0 Then
    Set Msg = Mailer.RetrieveSingleMessage(1)
    If Not Msg Is Nothing Then
      ' Remove all attachments from the message
      Msg.Attachments.RemoveAll
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Remove Method


Attachments Collection

The Attachments collection contains all of the attachments to a message. The collection can be used to determine the total number of attachments to the message, or to access individual Attachment objects within the collection.

Syntax

Attachments.property|method

Properties
Count | Returns the number of attachments in the collection.
Item | Returns a reference to an attachment in the collection.
Methods
Remove | Removes the attachment with the specified index from the collection.
RemoveAll | Removes all the attachments from the collection.

Remarks

Item is the default property of the collection, so Attachments.Item(index) and Attachments(index) are equivalents.

To iterate through the collection, you can use either a For .. Each statement or any common loop statement such as For .. To.

Example

The following examples use different syntax to display filenames of all attachments to a message. It's assumed that the message has already been retrieved and stored in objMsg object.

For .. Each syntax
For Each objAttach In objMsg.Attachments
  MsgBox objAttach.Filename
  ' In ASP, use Response.Write instead of MsgBox
Next

For .. To syntax
For I = 1 To objMsg.Attachments.Count
  MsgBox objMsg.Attachments(I).Filename
  ' In ASP, use Response.Write instead of MsgBox
Next

See Also

Attachment Object, Message.Attachments Property

Send feedback to AfterLogic


BodyPartStructure Object

The BodyPartStructure object provides access to properties of the structure of a MIME part of a message, including the structure of all MIME parts nested in the given part.

A reference to the BodyPartStructure object is returned by BodyStructure property of the Envelope object when the envelopes were retrieved using IMAP4.RetrieveEnvelopesEx method, with AlsoGetBodyStructure parameter set to True.

Syntax

BodyPartStructure.property

Collections
SubParts | Contains structures for all of the MIME parts nested in the given part.
Properties
ContentCommonType | The general content type of the MIME part.
ContentID | Content-ID of the MIME part
ContentSubType | The content sub type of the MIME part.
Description | A textual description of the MIME part.
Disposition | The content disposition of the MIME part.
Filename | The filename of the MIME part.
IsMultipart | Denotes whether the MIME part does contain nested parts.
LineCount | The number of text lines in the MIME part.
Size | The size of the MIME part in its original (undecoded) state.

Remarks

With MailBee, the entire structure of the MIME parts of a message is a tree of BodyPartStructure objects. The root BodyPartStructure object provides access to the smaller parts; each of these parts provides access to its own sub parts, and so on.

The total number of BodyPartStructure objects within the tree depends on the message complexity. In the simplest case (a message without any attachments and alternative text bodies), the whole tree contains only one BodyPartStructure object.

A MIME part which contains any sub parts is called multipart. For such a part, IsMultipart property returns True and SubParts property returns a reference to the collection of BodyPartStructure objects where each BodyPartStructure object describes structure of one of the sub parts.

If IsMultipart is False, the MIME part is singlepart and the SubParts collection is not available.

Note: Multipart MIME parts perform only grouping function: they group smaller MIME parts into larger parts. In other words, multipart MIME part cannot have its own content (such as text body or attachment data) besides nested sub parts.

Example

The following example retrieves a message from the server, and iterates through all of the MIME parts of the message, building the MIME parts tree. For each branch of the tree, the content type of the respective MIME part is used. Finally, the tree is displayed. GetTree function is a key part of the example.

Final output greatly depends on the particular message structure, but for the complex message it may look like this:

multipart/mixed
--multipart/related
----multipart/alternative
-------text/plain
-------text/html
----image/gif
----image/gif
----image/jpeg
--application/octet-stream
' Returns a string which contains content types
' of the given part and all its sub parts
Function GetTree(objBodyPart, nOffset)
  Dim objSubPart

  ' Content type of the part
  GetTree = _
    String(nOffset * 2, "-") & _
    objBodyPart.ContentCommonType & "/" & _
    objBodyPart.ContentSubType

  ' If the part is multipart, add content types of
  ' the sub parts to the string
  If objBodyPart.IsMultipart Then
    For Each objSubPart In objBodyPart.SubParts
      GetTree = GetTree & vbCrLf & GetTree(objSubPart, nOffset + 1)
      ' In ASP, use "<br>" instead of vbCrLf
    Next
  End If
End Function

Dim objIMAP4, objEnvelopes

' Using Visual Basic to create object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Using ASP to create object
' Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "jdoe"
objIMAP4.Password = "secret"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Get envelope and body structure for
    ' the first message in the inbox
    Set objEnvelopes = _
      objIMAP4.RetrieveEnvelopesEx(1, 1, False, True)

    ' Check for errors
    If Not objIMAP4.IsError Then
      If objEnvelopes.Count > 0 Then
        ' The message is ok,
        ' display its body structure
        MsgBox GetTree(objEnvelopes(1).BodyStructure, 0)
        ' In ASP, use Response.Write instead of MsgBox
      End If
    End If
  End If

  ' Close the connection
  objIMAP4.Disconnect
End If

See Also

BodyPartStructures Collection, Envelope Object

Send feedback to AfterLogic


SubParts Property

Contains BodyPartStructures collection of child parts of multipart MIME part.

This property is Nothing if the MIME part is non-multipart (IsMultipart=False).

Value Type: | MailBee.BodyPartStructures
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays the size of non-multipart parts of the first email in Inbox.

' This subroutine is recursive
Sub DisplaySize(BodyPart)
  Dim Part
  MsgBox BodyPart.Size & " bytes"
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplaySize Part
    Next
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplaySize Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

IsMultipart Property

BodyPartStructures Collection

BodyPartStructure Object
Envelope Object


ContentCommonType Property

Contains main part of Content-Type of the MIME part.

For example, if Content-Type header looks like:

Content-Type: text/plain; charset=us-ascii

then ContentCommonType property will return "text".

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Content-Type for all parts
' and subparts of the first email in Inbox.

' This subroutine is recursive
Sub DisplayContentType(BodyPart)
  Dim Part
  MsgBox BodyPart.ContentCommonType & "/" & BodyPart.ContentSubType
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplayContentType Part
    Next
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplayContentType Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

ContentSubType Property
IsMultipart Property
SubParts Property

BodyPartStructure Object
Envelope Object


ContentID Property

Contains the Content-ID of the MIME part, as returned by the IMAP server.

This value usually does not contain angle brackets <> unless the server returns Content-ID value with them.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays ContentID for all parts
' and subparts of the first email in Inbox.

' This subroutine is recursive
Sub DisplayContentID(BodyPart)
  Dim Part
  MsgBox BodyPart.ContentID
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplayContentID Part
    Next
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplayContentID Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

IsMultipart Property
SubParts Property

BodyPartStructure Object
Envelope Object


ContentSubType Property

Contains sub part of Content-Type of the MIME part.

For example, if Content-Type header looks like:

Content-Type: text/plain; charset=us-ascii

then ContentSubType property will return "plain".

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Content-Type for all parts
' and subparts of the first email in Inbox.

' This subroutine is recursive
Sub DisplayContentType(BodyPart)
  Dim Part
  MsgBox BodyPart.ContentCommonType & "/" & BodyPart.ContentSubType
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplayContentType Part
    Next
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplayContentType Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

ContentCommonType Property
IsMultipart Property
SubParts Property

BodyPartStructure Object
Envelope Object


Description Property

Contains the description of the MIME part.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Description for all parts
' and subparts of the first email in Inbox.

' This subroutine is recursive
Sub DisplayDescription(BodyPart)
  Dim Part
  MsgBox BodyPart.Description
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplayDescription Part
    Next
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplayDescription Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

Filename Property
IsMultipart Property
SubParts Property

BodyPartStructure Object
Envelope Object


Disposition Property

Contains the Content-Disposition of the MIME part.

For example, if Content-Disposition header looks like:

Content-Disposition: attachment; filename="archive.zip"

then Disposition property will return "attachment".

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Disposition for all parts
' and subparts of the first email in Inbox.

' This subroutine is recursive
Sub DisplayDisposition(BodyPart)
  Dim Part
  MsgBox BodyPart.Disposition
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplayDisposition Part
    Next
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplayDisposition Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

Filename Property
IsMultipart Property
SubParts Property

BodyPartStructure Object
Envelope Object


Filename Property

Contains the filename of the MIME part.

For example, if Content-Disposition header looks like:

Content-Disposition: attachment; filename="archive.zip"

then Filename property will return "archive.zip".

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Filename for all parts
' and subparts of the first email in Inbox.

' This subroutine is recursive
Sub DisplayFilename(BodyPart)
  Dim Part
  MsgBox BodyPart.Filename
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplayFilename Part
    Next
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplayFilename Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

IsMultipart Property
Size Property
SubParts Property

BodyPartStructure Object
Envelope Object


IsMultipart Property

Indicates if the MIME part is multipart.

If IsMultipart=True, the MIME part is a container of child MIME parts. These parts can be accessed through SubParts property.

If IsMultipart=False, the MIME part is a body text or an attachment; SubParts is Nothing.

Value Type: | Boolean
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Filename for non-multipart parts of the first email in Inbox.

' This subroutine is recursive
Sub DisplayFilename(BodyPart)
  Dim Part
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplayFilename Part
    Next
  Else
    MsgBox BodyPart.Filename
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplayFilename Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

SubParts Property

BodyPartStructure Object
Envelope Object


LineCount Property

Contains the number of text lines in the MIME part.

This property is only valid on parts of text type (whose ContentCommonType property value is "text").

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays number of lines in text parts of the first email in Inbox.

' This subroutine is recursive
Sub DisplayLineCount(BodyPart)
  Dim Part
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplayLineCount Part
    Next
  ElseIf BodyPart.ContentCommonType = "text" Then
    MsgBox BodyPart.LineCount & " lines"
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplayLineCount Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

ContentCommonType Property
Size Property
SubParts Property

BodyPartStructure Object
Envelope Object


Size Property

Contains the size (in bytes) of the MIME part.

If the MIME part is multipart (IsMultipart=True), the size is zero.

Note: This size is larger than the size of the data encoded in the MIME part due to the presence of the MIME part headers and encoding overhead.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays the size of non-multipart parts of the first email in Inbox.

' This subroutine is recursive
Sub DisplaySize(BodyPart)
  Dim Part
  MsgBox BodyPart.Size & " bytes"
  If BodyPart.IsMultipart Then
    For Each Part In BodyPart.SubParts
      DisplaySize Part
    Next
  End If
End Sub

' Main code
Sub Main
  Dim Mailer, Envelopes, Envelope
  'Using visual basic to create object
  Set Mailer = CreateObject("MailBee.IMAP4")
  'Using ASP to create object
  'Set Mailer = Server.CreateObject("MailBee.IMAP4")
  'In ASP use Response.Write instead of MsgBox
  Mailer.EnableLogging = True
  Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
  Mailer.ClearLog
  Mailer.LicenseKey = "put your license key here"
  If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
    If Mailer.SelectMailbox("Inbox") Then
      Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
      If Not Envelopes Is Nothing Then
        For Each Envelope In Envelopes
          DisplaySize Envelope.BodyStructure
        Next
      End If
    End If
    Mailer.Disconnect
  End If
End Sub

See Also:

IsMultipart Property
SubParts Property

BodyPartStructure Object
Envelope Object


BodyPartStructures Collection

The BodyPartStructures collection contains BodyPartStructure objects which organize the structure of the multipart MIME part.

The BodyPartStructures collection can be obtained via SubParts property of the multipart BodyPartStructure object. Multipart BodyPartStructure objects have IsMultipart property set to True. The BodyPartStructures collection is recursive since contained BodyPartStructure objects can also be multipart and thus can expose their own BodyPartStructures collections.

Syntax

BodyPartStructures.property

Properties
Count | Returns the number of BodyPartStructure objects in the collection.
Item | Returns a reference to BodyPartStructure object in the collection.

Remarks

Note: A simple e-mail message can have a single MIME part only, thus all its structure is represented by a single BodyPartStructure object. The BodyPartStructures collection is not available for single MIME part messages.

Item is the default property of the collection, so BodyPartStructures.Item(index) and BodyPartStructures(index) are equivalents.

To iterate through the collection, you can use either For .. Each statement or any common loop statement such as For .. To.

Example

The following examples use different syntax to display grouping status (whether multipart or not) of the body parts. It's assumed the BodyPartStructures collection has been already obtained through SubParts property of the BodyPartStructure object, and stored in objBodyPartStructures variable.

For .. Each syntax
For Each objBodyPartStructure In objBodyPartStructures
  MsgBox objBodyPartStructure.IsMultipart
  ' In ASP, use Response.Write instead of MsgBox
Next

For .. To syntax
For I = 1 To objBodyPartStructures.Count
  MsgBox objBodyPartStructures(I).IsMultipart
  ' In ASP, use Response.Write instead of MsgBox
Next

See Also

BodyPartStructure Object

Send feedback to AfterLogic


Count Property

Returns the number of BodyPartStructure objects in the collection.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays the number of sub parts of main MIME part of the first email in Inbox
Dim Mailer, Envelope, Envelopes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        If Envelope.BodyStructure.IsMultipart Then
          MsgBox Envelope.BodyStructure.SubParts.Count & " parts"
        Else
          MsgBox "1 part"
        End If
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Item Property

BodyPartStructure Object

Mailboxes Collection


Item Property

Returns a BodyPartStructure object from the collection.

Index parameter specifies the index of the MIME part structure in the collection. If Index is out of range, automation error occurs.

Item is the default property of the collection. The following two statements (assuming Parts has MailBee.BodyPartStructures type) are equivalent:

Set Part = Parts(1)

and

Set Part = Parts.Item(1)

Value Type: | MailBee.BodyPartStructure
Parameters: |
Index As Long | Index of the MIME part structure to return. Allowed range is: 1 <= Index <= BodyPartStructures.Count
Remarks: | This property is read-only

Usage example:

' This sample displays the size of the first part of multipart email message.
' The size may be zero if the first part is multipart too.
' For non-multipart message, the size of the body is displayed.
Dim Mailer, Envelope, Envelopes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        If Envelope.BodyStructure.IsMultipart Then
          MsgBox Envelope.BodyStructure.SubParts(1).Size & " bytes" ' Using Item as Default property
        Else
          MsgBox Envelope.BodyStructure.Size
        End If
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Count Property

BodyPartStructure Object

BodyPartStructures Collection


Envelope Object

You can use the Envelope object to examine properties of messages located on the IMAP4 server.

Syntax

Envelope.property

Properties
AddressDelimiter | Specifies the delimiter to be used to separate individual items when returning e-mail addresses' or friendly names' strings.
BCCAddr | The e-mail addresses of the blind-carbon-copy recipients.
BodyStructure | A reference to the root BodyPartStructure object of the message structure tree. Can be Nothing.
CCAddr | The e-mail addresses of the carbon-copy recipients.
CCFriendlyName | The friendly names of the carbon-copy recipients.
Date | The date and time of the moment when the server received the message.
Flags | The flags set for the message.
FlagsAsString | All the flags (including non-standard ones) which are set for the message, as a string.
FromAddr | The e-mail address of the sender.
FromFriendlyName | The friendly name of the sender.
MessageID | The value of "Message-ID:" header of the message.
MessagePreview | A reference to the Message object which contains the partial message. Can be Nothing.
PureCCAddr | The e-mail addresses (with friendly names removed) of the carbon-copy recipients.
PureFromAddr | The e-mail address (with friendly name removed) of the sender.
PureToAddr | The e-mail addresses (with friendly names removed) of the primary recipients.
ReplyToAddr | The e-mail address of the entity specified to receive all replies to the message.
RFC822Date | The date and time as it's specified in "Date:" header of the message.
Size | The size of the entire message (in bytes).
Subject | The subject of the message.
ToAddr | The e-mail addresses of the primary recipients.
ToFriendlyName | The friendly names of the primary recipients.
UID | The Unique-ID (UID) of the message on the IMAP4 server.

Remarks

The Envelope object allows you to preview messages and examine their properties without overhead of downloading entire messages.

The Envelope object effectively replaces message headers widely used in the POP3-based e-mail solutions. With the IMAP4 envelopes, you have access to the extra information not available with the POP3 protocol such as the date and time of the moment when the server received the message (Date property).

If you need to examine certain message headers which are not exposed by the Envelope object (such as "X-Spam:"), you can still obtain the message headers via MessagePreview property. Also, this property can be used to preview some part of the message body.

Also, the Envelope object can expose the structure of the message parts via BodyStructure property. For instance, you can obtain the attachments filenames, or determine whether the message is HTML-formatted or just plain-text.

To obtain the Envelope object, either call RetrieveEnvelopes or RetrieveEnvelopesEx method of the IMAP4 object. These methods return the Envelopes collection of the Envelope objects.

Note: By default, BodyStructure and MessagePreview properties of the Envelope object are available because of additional information (and network traffic) required to set them. You must use RetrieveEnvelopesEx method if you want to have these properties set.

Example

The following example connects to the IMAP4 server, logs in certain e-mail account, selects Inbox folder, and displays the size for the first 5 messages.
Dim objIMAP4, objEnvelopes, objEnvelope

' Using Visual Basic to create object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Using ASP to create object
' Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "jdoe"
objIMAP4.Password = "secret"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Select Inbox folder
  If objIMAP4.SelectMailbox("Inbox") Then

    ' Get envelopes for the first 5 messages
    Set objEnvelopes = _
      objIMAP4.RetrieveEnvelopes(1, 5, False)

    ' Check for errors
    If Not objIMAP4.IsError Then
      For Each objEnvelope In objEnvelopes
        ' Display the message size
        MsgBox "Size = " & objEnvelope.Size
        ' In ASP, use Response.Write instead of MsgBox
      Next
    End If
  End If

  ' Close the connection
  objIMAP4.Disconnect
End If

See Also

BodyPartStructure Object, Envelopes Collection, IMAP4 Object, Message Object

Send feedback to AfterLogic


AddressDelimiter Property

Specifies the delimiter of addresses which will be used when returning values of FromAddr, ToAddr, PureCCAddr, ToFriendlyName and other similar properties. The default value is ", " (comma followed by space).

This property is useful if you have "," chars in the values of e-mail addresses or display names and you need to split the entire string to get individual addresses. You can assign it to a somewhat like "{|}" (which is highly unlikely to appear in addresses) and split by this value.

Value Type: | String
Parameters: | None

Usage example:

' This sample displays To recipients (separately for each recipient) for the last message in Inbox
Dim Mailer, Envelopes, Envelope, ToRecipients, SingleTo
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        Envelope.AddressDelimiter = "{|}"
        ToRecipients = Split(Envelope.ToAddr, "{|}")
        For Each SingleTo In ToRecipients
          MsgBox SingleTo
        Next
      Next
    End If
  End if
  Mailer.Disconnect
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

Envelope Object


BCCAddr Property

Contains comma-separated list of email addresses of blind-carbon-copy recipients.

Example of complex BCCAddr (3 recipients, 2 of them also have friendly names, third address is "pure" address):

"John Doe" <jdoe@host1.com>, Mike Douglas <m.douglas@pbox.foo.com> (Foo Company), nofriendlyname@server.com

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses.

Note: This property will be empty in nearly 100% cases because BCC recipients are usually not listed in messages.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays BCC for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.BCCAddr
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

FromAddr Property
CCAddr Property
ToAddr Property


BodyStructure Property

Contains a reference to root BodyPartStructure object of the tree of MIME part structures of the message body.

Note: To get Envelope objects with BodyStructure property set, call RetrieveEnvelopesEx method of IMAP4 object with AlsoGetBodyStructure parameter set to True. Otherwise, BodyStructure property will return Nothing.

Value Type: | MailBee.BodyPartStructure
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays message type (multipart or not) for the first email in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopesEx(1, 1, False, True)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        If Envelope.BodyStructure.IsMultipart Then
          MsgBox "Multipart message"
        Else
          MsgBox "Singlepart message"
        End If
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

MessagePreview Property

BodyPartStructure Object
Envelope Object

IMAP4.RetrieveEnvelopesEx Method


CCAddr Property

Contains comma-separated list of email addresses of carbon-copy recipients.

Example of complex CCAddr (3 recipients, 2 of them also have friendly names, third address is "pure" address):

"John Doe" <jdoe@host1.com>, Mike Douglas <m.douglas@pbox.foo.com> (Foo Company), nofriendlyname@server.com

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses.

To get friendly names only, examine CCFriendlyName property. To get pure email addresses, examine PureCCAddr property.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays CC for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.CCAddr
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

BCCAddr Property
CCFriendlyName Property
FromAddr Property
PureCCAddr Property
ToAddr Property


CCFriendlyName Property

Contains comma-separated list of friendly names of carbon-copy recipients.

If no friendly name is available, the corresponding item in the list will be empty.

If CCAddr is:

"John Doe" <jdoe@host1.com>, Mike Douglas <m.douglas@pbox.foo.com> (Foo Company), nofriendlyname@server.com, Nick <Nick@Server.Com>

then CCFriendlyName will return:

John Doe, Mike Douglas, , Nick

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays CCFriendlyName for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.CCFriendlyName
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

CCAddr Property
FromFriendlyName Property
PureCCAddr Property
ToFriendlyName Property


Date Property

Contains the date and time of the moment when the message was received by the server.

This may be different from RFC822Date specified in the message headers.

You can use GetDateFromString method of the Message object to convert this value from String type into Date type.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Date for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.Date
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

RFC822Date Property

Message.GetDateFromString Method


Flags Property

Contains the flags set for the message.

This can be zero, or any combination of the following values:

  • 1 - Answered
  • 2 - Deleted
  • 4 - Draft
  • 8 - Flagged
  • 16 - Recent
  • 32 - Seen
To search mailbox for messages with specific flag set, use Search method of IMAP4 object.

To examine non-standard flags, use FlagsAsString property.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays all flags for the last message in Inbox
Dim Mailer, Envelopes, Envelope, Flags
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        Flags = Envelope.Flags
        If (Flags And 1) = 1 Then MsgBox "Answered"
        If (Flags And 2) = 2 Then MsgBox "Deleted"
        If (Flags And 4) = 4 Then MsgBox "Draft"
        If (Flags And 8) = 8 Then MsgBox "Flagged"
        If (Flags And 16) = 16 Then MsgBox "Recent"
        If (Flags And 32) = 32 Then MsgBox "Seen"
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

IMAP4.Search Method


FlagsAsString Property

Gets all the IMAP flags for the message as a space-separated string.

This property is useful if you need to use non-standard IMAP flags. Example of the return value: "\Answered \Flagged $Spam".

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays all the flags for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.FlagsAsString
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Flags Property


FromAddr Property

Contains the email address of the sender.

To get the sender's friendly name, examine FromFriendlyName property. To get pure email address, examine PureFromAddr property.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays "From:" value for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.FromAddr
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

BCCAddr Property
CCAddr Property
FromFriendlyName Property
PureFromAddr Property
ReplyToAddr Property
ToAddr Property


FromFriendlyName Property

Contains the friendly name of the sender.

If no friendly name is available, the property is empty.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays FromFriendlyName for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.FromFriendlyName
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

CCFriendlyName Property
FromAddr Property
PureFromAddr Property
ToFriendlyName Property


MessageID Property

Contains the Message-ID of the message.

E.g. if Message-ID header looks like:

Message-ID: <14816287800.20040305185837@localhost>

then MessageID property returns "14816287800.20040305185837@localhost".

Note: Dont't confuse Message-ID (which is a string taken from "Message-ID" message header) with UID (which is unique number assigned to each message in IMAP4 mailbox).

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Message-ID for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.MessageID
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

UID Property


MessagePreview Property

Contains the reference (if it is available) to the Message object which holds the partial message.

By default, this property is Nothing and partial message is not avialable. To get envelopes with this property set, call RetrieveEnvelopesEx method of IMAP4 object with AlsoGetMessagePreview parameter set to True.

The degree of completeness of the partial message depends on value of BodyPreviewSize parameter of RetrieveEnvelopesEx method of IMAP4 object. If BodyPreviewSize=0, only message headers are available. Bigger BodyPreviewSize, more bytes of the message body are retrieved.

MessagePreview holds the same message you can get standalone using RetrieveSingleMessageHeaders method of IMAP4 object. However, using MessagePreview property, you can get envelopes and message previews for multiple messages at once.

Value Type: | MailBee.Message
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays preview of body text (taken from first
' 1000 bytes of the body) of the last message in Inbox.
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopesEx _
      (Mailer.MessageCount, Mailer.MessageCount, False, False, True, 1000)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.MessagePreview.BodyText
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

BodyStructure Property

Message Object
Envelope Object

IMAP4.RetrieveEnvelopesEx Method
IMAP4.RetrieveSingleMessageHeaders Method


PureCCAddr Property

Contains comma-separated list of pure email addresses (without friendly names) of carbon-copy recipients.

If CCAddr is:

"John Doe" <jdoe@host1.com>, Mike Douglas <m.douglas@pbox.foo.com> (Foo Company), nofriendlyname@server.com, Nick <Nick@Server.Com>

then PureCCAddr will return:

jdoe@host1.com, m.douglas@pbox.foo.com, nofriendlyname@server.com, Nick@Server.Com

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays PureCCAddr for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.PureCCAddr
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

CCAddr Property
CCFriendlyName Property
PureFromAddr Property
PureToAddr Property


PureFromAddr Property

Contains pure email address (without friendly name) of the sender.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays PureFromAddr for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.PureFromAddr
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

FromAddr Property
FromFriendlyName Property
PureCCAddr Property
PureToAddr Property


PureToAddr Property

Contains comma-separated list of pure email addresses (without friendly names) of "To:" recipients.

If ToAddr is:

"John Doe" <jdoe@host1.com>, Mike Douglas <m.douglas@pbox.foo.com> (Foo Company), nofriendlyname@server.com, Nick <Nick@Server.Com>

then PureToAddr will return:

jdoe@host1.com, m.douglas@pbox.foo.com, nofriendlyname@server.com, Nick@Server.Com

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays PureToAddr for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.PureToAddr
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

PureCCAddr Property
PureFromAddr Property
ToAddr Property
ToFriendlyName Property


ReplyToAddr Property

Contains the email address where all replies to this message will arrive to.

Note: This property is often empty. In this case, replies must be sent to "From" address (FromAddr property).

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays Reply-To for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.ReplyToAddr
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

FromAddr Property


RFC822Date Property

Contains the value of "Date" message header. Usually this value is the date and time of the moment when the sender created the message.

This may be different from Date which indicates the moment when the message was received by the server.

You can use GetDateFromString method of the Message object to convert this value from String type into Date type.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays RFC822Date for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.RFC822Date
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Date Property

Message.GetDateFromString Method


Size Property

Contains the size of the message in bytes.

This is the size of overall message including headers, body and any attachments.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays the size for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.Size & " bytes"
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

IMAP4.Search Method


Subject Property

Contains the subject of the message.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays "Subject:" value for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.Subject
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Envelope Object


ToAddr Property

Contains comma-separated list of email addresses of "To:" recipients.

Example of complex ToAddr (3 recipients, 2 of them also have friendly names, third address is "pure" address):

"John Doe" <jdoe@host1.com>, Mike Douglas <m.douglas@pbox.foo.com> (Foo Company), nofriendlyname@server.com

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses.

To get friendly names only, examine ToFriendlyName property. To get pure email addresses, examine PureToAddr property.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays "To:" for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.ToAddr
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

BCCAddr Property
CCAddr Property
FromAddr Property
PureToAddr Property
ToFriendlyName Property


ToFriendlyName Property

Contains comma-separated list of friendly names of primary recipients.

If no friendly name is available, the corresponding item in the list will be empty.

If ToAddr is:

"John Doe" <jdoe@host1.com>, Mike Douglas <m.douglas@pbox.foo.com> (Foo Company), nofriendlyname@server.com, Nick <Nick@Server.Com>

then ToFriendlyName will return:

John Doe, Mike Douglas, , Nick

Set AddressDelimiter if you want to use another string (not a comma character) to delimit individual addresses.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays ToFriendlyName for the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.ToFriendlyName
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

CCFriendlyName Property
FromFriendlyName Property
PureToAddr Property
ToAddr Property


UID Property

Contains the unique-id (UID) of the message.

UID is a 32-bit number which uniquely identifies the message in IMAP4 mailbox. This number is guaranteed to be always larger for each new message in the mailbox than any UIDs of the messages existed in the mailbox before.

UIDs are useful for message management and search (such as looking for or retrieving new messages). Most methods of IMAP4 object allow UIDs as alternative form of message indices.

Note: Dont't confuse UID with MessageID (which is a string taken from "Message-ID" message header).

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample displays UID of the last message in Inbox
Dim Mailer, Envelopes, Envelope
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(Mailer.MessageCount, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For Each Envelope In Envelopes
        MsgBox Envelope.UID
      Next
    End If
  End If
  Mailer.Disconnect
End If

See Also:

IMAP4.Search Method


Envelopes Collection

The Envelopes collection contains Envelope objects used to examine properties of messages on the IMAP4 server.

To obtain the Envelopes collection, either call RetrieveEnvelopes or RetrieveEnvelopesEx method of the IMAP4 object.

Syntax

Envelopes.property

Properties
Count | Returns the number of Envelope objects in the collection.
Item | Returns a reference to Envelope object in the collection.

Remarks

Item is the default property of the collection, so Envelopes.Item(index) and Envelopes(index) are equivalents.

To iterate through the collection, you can use either For .. Each statement or any common loop statement such as For .. To.

Example

The following examples use different syntax to display "Subject:" field of all messages in the IMAP4 folder. It's assumed the Envelopes collection has been already obtained with RetrieveEnvelopes method call and stored in objEnvelopes variable.

For .. Each syntax
For Each objEnvelope In objEnvelopes
  MsgBox objEnvelope.Subject
  ' In ASP, use Response.Write instead of MsgBox
Next

For .. To syntax
For I = 1 To objEnvelopes.Count
  MsgBox objEnvelopes(I).Subject
  ' In ASP, use Response.Write instead of MsgBox
Next

See Also

Envelope Object, IMAP4 Object, IMAP4.RetrieveEnvelopes Method

Send feedback to AfterLogic


Count Property

Returns the number of Envelope objects in the collection.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample iterates envelope collection in reverse order
Dim Mailer, Envelopes, I
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(1, Mailer.MessageCount, False)
    If Not Envelopes Is Nothing Then
      For I = Envelopes.Count To 1 Step -1
        MsgBox Envelopes(I).Subject
      Next
    End If
  End If
  Mailer.Disconnect
End I

See Also:

Item Property

Envelope Object

Envelopes Collection


Item Property

Returns an Envelope object from the collection.

Index parameter specifies the index of the mailbox in the collection. If Index is out of range, automation error occurs.

Item is the default property of the collection. The following two statements (assuming Envelopes has MailBee.Envelopes type) are equivalent:

Set Envelope = Envelopes(1)

and

Set Envelope = Envelopes.Item(1)

Value Type: | MailBee.Envelope
Parameters: |
Index As Long | Index of the mailbox to return. Allowed range is: 1 <= Index <= Envelopes.Count
Remarks: | This property is read-only

Usage example:

' This sample displays Subject for the first message in the collection
Dim Mailer, Envelopes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  If Mailer.SelectMailbox("Inbox") Then
    Set Envelopes = Mailer.RetrieveEnvelopes(1, 1, False)
    If Not Envelopes Is Nothing Then
      If Envelopes.Count > 0 Then
        MsgBox Envelopes(1).Subject
      End If
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Count Property

Mailbox Object

Mailboxes Collection


Mailbox Object

The Mailbox object contains properties used to examine a mailbox on the IMAP4 server.

Individual Mailbox objects can be accessed by iterating through the Mailboxes collection returned by RetrieveMailboxes method of the IMAP4 object.

Syntax

Mailbox.property

Properties
Delimiter | The character that is used as hierarchy delimiter of mailbox levels.
Flags | Flags which set for the mailbox.
Name | Name of the mailbox.
OriginalName | Gets the original mailbox name as it's provided by the IMAP server (not decoded from UTF-7M).

Example

The following example displays names of all mailboxes available in the user account.
Dim objIMAP4, objMailboxes, objMailbox

' Using Visual Basic to create object
Set objIMAP4 = CreateObject("MailBee.IMAP4")

' Using ASP to create object
' Set objIMAP4 = Server.CreateObject("MailBee.IMAP4")

' Unlock IMAP4 object
objIMAP4.LicenseKey = "put your license key here"

' Set IMAP4 server name
objIMAP4.ServerName = "mail.server.com"

' Set user credentials
objIMAP4.UserName = "jdoe"
objIMAP4.Password = "secret"

' Connect to the server and
' log in email account
If objIMAP4.Connect Then

  ' Download list of mailboxes
  Set objMailboxes = objIMAP4.RetrieveMailboxes

  ' Check for errors
  If Not objIMAP4.IsError Then
    For Each objMailbox In objMailboxes
      ' Display name of each mailbox
      MsgBox "Name = " & objMailbox.Name
      ' In ASP, use Response.Write instead of MsgBox
    Next
  End If

  ' Close the connection
  objIMAP4.Disconnect
End If

See Also

Mailboxes Collection, IMAP4.RetrieveMailboxes Method

Send feedback to AfterLogic


Delimiter Property

Specifies the character that is used as hierarchy delimiter of mailbox levels.

For example, if there is "Archive/Private" mailbox on the server and Delimiter="/", then "Private" is a subfolder of "Archive" mailbox.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample prints hierarchy delimiter used in the IMAP4 account
Dim Mailer, Mailboxes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Set Mailboxes = Mailer.RetrieveMailboxes
  If Not Mailboxes Is Nothing Then
    If Mailboxes.Count > 0 Then
      MsgBox "Delimiter: " & Mailboxes(1).Delimiter
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Flags Property
Name Property


Flags Property

Contains flags which are set for the mailbox.

This can be zero, or any combination of the following values:

  • 1 - "\Noinferiors" flag. No child mailboxes can exist or be created for this mailbox
  • 2 - "\Noselect" flag. The mailbox cannot be selected or examined
  • 4 - "\Marked" flag. The server has marked the mailbox as "interesting". This usually happens when new messages have been added to the mailbox since last time the mailbox was selected
  • 8 - "\Unmarked" flag. No new messages since last time the mailbox was selected
  • 16 - "\Inbox" flag. This mailbox serves Inbox purpose
  • 32 - "\Drafts" flag. This mailbox serves Drafts purpose
  • 64 - "\Sent" flag. This mailbox serves Sent Items purpose
  • 128 - "\Spam" flag. This mailbox contains spam
  • 256 - "\Trash" flag. This mailbox contains deleted items
  • 512 - "\Archive" flag. This mailbox contains archived items
  • 1024 - "\Starred" flag. This mailbox contains starred or flagged items (usually, it's a virtual mailbox and all items here are also available in other mailboxes)
  • 2048 - "\Important" flag. This mailbox contains important items (usually, a virtual mailbox)
  • 4096 - "\AllMail" flag. This mailbox is a virtual mailbox which groups items from other mailboxes into a single list
  • 8192 - "\HasChildren" flag. This mailbox contains child mailboxes
  • 16384 - "\HasNoChildren" flag. This mailbox does not contain child mailboxes (if neither "\HasChildren" nor "\HasNoChildren" is set, the status is unknown)
Note: special folder flags (\Inbox, \Drafts, \Sent, \Spam, \Trash, etc) can only be returned if the server supports XLIST or SPECIAL-USE extensions. \HasChildren and \HasNoChildren flags - if the server supports CHILDREN extension. See RetrieveMailboxesEx method for details.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample prints all flags of the first mailbox in the IMAP4 account
Dim Mailer, Mailboxes, Flags
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Set Mailboxes = Mailer.RetrieveMailboxes
  If Not Mailboxes Is Nothing Then
    If Mailboxes.Count > 0 Then
      Flags = Mailboxes(1).Flags
      If (Flags And 1) = 1 Then MsgBox "\Noinferiors flag set"
      If (Flags And 2) = 2 Then MsgBox "\Noselect flag set"
      If (Flags And 4) = 4 Then MsgBox "\Marked flag set"
      If (Flags And 8) = 8 Then MsgBox "\Unmarked flag set"
      If (Flags And 16) = 16 Then MsgBox "\Inbox flag set"
      If (Flags And 32) = 32 Then MsgBox "\Drafts flag set"
      If (Flags And 64) = 64 Then MsgBox "\Sent flag set"
      If (Flags And 128) = 128 Then MsgBox "\Spam flag set"
      If (Flags And 256) = 256 Then MsgBox "\Trash flag set"
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Name Property


Name Property

Contains the human-readable name of the mailbox.

You should use this property to display the mailbox name to the user. To pass the mailbox name to the IMAP server, it's recommended to set UTF7EncodeMailboxNames to False and use Mailbox.OriginalName instead.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample prints name of the first mailbox in the IMAP4 account
Dim Mailer, Mailboxes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Set Mailboxes = Mailer.RetrieveMailboxes
  If Not Mailboxes Is Nothing Then
    If Mailboxes.Count > 0 Then
      MsgBox "Name: " & Mailboxes(1).Name
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Delimiter Property
Flags Property
 Mailbox.OriginalName Property


OriginalName Property

Gets the original mailbox name as it's provided by the IMAP server (not decoded from UTF-7M). This property always contains original mailbox name and doesn't matter if UTF7EncodeMailboxNames is set to False or True.

It's recommended to set UTF7EncodeMailboxNames property to False and use this property value as a mailbox name when passing it to a method (like SelectMailbox, ExamineMailbox, AppendMessage or any other which accepts the mailbox name as a parameter). This will allow you to avoid various issues if your IMAP server doesn't support UTF-7M encoding for mailbox names.

At the same time, use Name property to display human-readable name of the mailbox. In other words, IMAP servers understand OriginalName while human users understand Name. This is valid if UTF7EncodeMailboxNames is False.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample gets the list of all mailboxes and selects the last mailbox.
' Then, it displays the number of messages in that mailbox.

Dim Mailer, Mailboxes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  ' Turn off encoding of mailbox names when submitting them to the server
  Mailer.UTF7EncodeMailboxNames = False
  Set Mailboxes = Mailer.RetrieveMailboxes
  If Not Mailboxes Is Nothing Then
    If Mailboxes.Count > 0 Then
      If Mailer.SelectMailbox(Mailboxes(Mailboxes.Count).OriginalName) Then
        MsgBox Mailer.MessageCount & " messages in " & Mailboxes(Mailboxes.Count).Name
      End If
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Name Property
UTF7EncodeMailboxNames Property


Mailboxes Collection

The Mailboxes collection contains Mailbox objects used to examine properties of the IMAP4 mailboxes.

RetrieveMailboxes method of the IMAP4 object returns Mailboxes collection of all mailboxes in a user account.

Syntax

Mailboxes.property

Properties
Count | Returns the number of mailboxes in the collection.
Item | Returns a reference to a mailbox in the collection.

Remarks

Item is the default property of the collection, so Mailboxes.Item(index) and Mailboxes(index) are equivalents.

To iterate through the collection, you can use either For .. Each statement or any common loop statement such as For .. To.

Example

The following examples use different syntax to display names of all mailboxes in a user account. It's assumed the Mailboxes collection has been already retrieved and stored in objMailboxes object.

For .. Each syntax
For Each objMailbox In objMailboxes
  MsgBox objMailbox.Name
  ' In ASP, use Response.Write instead of MsgBox
Next

For .. To syntax
For I = 1 To objMailboxes.Count
  MsgBox objMailboxes(I).Name
  ' In ASP, use Response.Write instead of MsgBox
Next

See Also

Mailbox Object, IMAP4.RetrieveMailboxes Method

Send feedback to AfterLogic


Count Property

Returns the number of Mailbox objects in the collection.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample prints the number of mailboxes in the IMAP4 account
Dim Mailer, Mailboxes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Set Mailboxes = Mailer.RetrieveMailboxes
  If Not Mailboxes Is Nothing Then
    MsgBox Mailboxes.Count & " mailboxe(s) in the account"
  End If
  Mailer.Disconnect
End If

See Also:

Item Property

Mailbox Object

Mailboxes Collection


Item Property

Returns a Mailbox object from the collection.

Index parameter specifies the index of the mailbox in the collection. If Index is out of range, automation error occurs.

Item is the default property of the collection. The following two statements (assuming Mailboxes has MailBee.Mailboxes type) are equivalent:

Set Mailbox = Mailboxes(1)

and

Set Mailbox = Mailboxes.Item(1)

Value Type: | MailBee.Mailbox
Parameters: |
Index As Long | Index of the mailbox to return. Allowed range is: 1 <= Index <= Mailboxes.Count
Remarks: | This property is read-only

Usage example:

' This sample prints the name of the first mailbox in the IMAP4 account
Dim Mailer, Mailboxes
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mailserver.com", 143, "MyName", "MyPassword") Then
  Set Mailboxes = Mailer.RetrieveMailboxes
  If Not Mailboxes Is Nothing Then
    If Mailboxes.Count > 0 Then
      MsgBox "First mailbox name: " & Mailboxes(1).Name ' Using Item as Default property
    End If
  End If
  Mailer.Disconnect
End If

See Also:

Count Property

Mailbox Object

Mailboxes Collection


MailboxStatus Object

The MailboxStatus object contains properties used to examine a mailbox statistics on the IMAP4 server.

You can get this object using GetMailboxStatus method of the IMAP4 object.

Syntax

MailboxStatus.property

Properties
MessageCount | Number of all messages in the mailbox.
Name | Name of the mailbox.
OriginalName | The original mailbox name as it's provided by the IMAP server (not decoded from UTF-7M).
RecentCount | Number of recent messages in the mailbox.
UIDNext | Next predicted UID value in the mailbox.
UIDValidity | UIDVALIDITY value of the mailbox.
UnseenCount | Number of unread messages in the mailbox.

Example

This sample retrieves and displays all the stats of Inbox.
Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "MessageCount=" & Stats.MessageCount & " RecentCount=" & Stats.RecentCount & " UnseenCount=" & Stats.UnseenCount
    MsgBox "UIDValidity=" & Stats.UIDValidity & " UIDNext=" & Stats.UIDNext
  End If
  Mailer.Disconnect
End If

See Also

GetMailboxStatus Method

Send feedback to AfterLogic


MessageCount Property

The overall number of messages in the mailbox.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "MessageCount=" & Stats.MessageCount & " RecentCount=" & Stats.RecentCount & " UnseenCount=" & Stats.UnseenCount
    MsgBox "UIDValidity=" & Stats.UIDValidity & " UIDNext=" & Stats.UIDNext
  End If
  Mailer.Disconnect
End If

See Also:

UnseenCount Property


Name Property

Contains the human-readable name of the mailbox.

You should use this property to display the mailbox name to the user. To pass the mailbox name to the IMAP server, it's recommended to set UTF7EncodeMailboxNames to False and use MailboxStatus.OriginalName instead.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample retrieves and displays the name of Inbox
Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "Name=" & Stats.Name
    MsgBox "OriginalName=" & Stats.OriginalName
  End If
  Mailer.Disconnect
End If

See Also:

Delimiter Property
Flags Property
 Mailbox.OriginalName Property


OriginalName Property

Gets the original mailbox name as it's provided by the IMAP server (not decoded from UTF-7M). This property always contains original mailbox name and doesn't matter if UTF7EncodeMailboxNames is set to False or True.

It's recommended to set UTF7EncodeMailboxNames property to False and use this property value as a mailbox name when passing it to a method (like SelectMailbox, ExamineMailbox, AppendMessage or any other which accepts the mailbox name as a parameter). This will allow you to avoid various issues if your IMAP server doesn't support UTF-7M encoding for mailbox names.

At the same time, use Name property to display human-readable name of the mailbox. In other words, IMAP servers understand OriginalName while human users understand Name. This is valid if UTF7EncodeMailboxNames is False.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample retrieves and displays the name of Inbox as-is.
' This doesn't make a lot of sense because "Inbox" name is in Latin and will return Inbox
' but for non-English names it will be different than Name property value.
Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "OriginalName=" & Stats.OriginalName
  End If
  Mailer.Disconnect
End If

See Also:

Name Property
UTF7EncodeMailboxNames Property


RecentCount Property

The number of recent messages in the mailbox.

Recent messages are those which first appeared in this session.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "MessageCount=" & Stats.MessageCount & " RecentCount=" & Stats.RecentCount & " UnseenCount=" & Stats.UnseenCount
    MsgBox "UIDValidity=" & Stats.UIDValidity & " UIDNext=" & Stats.UIDNext
  End If
  Mailer.Disconnect
End If

See Also:

UnseenCount Property


UIDNext Property

The next predicted UID value in the mailbox.

When a new message appears in the mailbox, it will be assigned this UID value.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "MessageCount=" & Stats.MessageCount & " RecentCount=" & Stats.RecentCount & " UnseenCount=" & Stats.UnseenCount
    MsgBox "UIDValidity=" & Stats.UIDValidity & " UIDNext=" & Stats.UIDNext
  End If
  Mailer.Disconnect
End If

See Also:

UIDValidity Property


UIDValidity Property

UIDVALIDITY value of the mailbox.

Unchanged UIDVALIDITY for the mailbox ensures that UIDs in this mailbox are valid since the previous session. If it changed, you can no longer trust the UIDs in this mailbox and be prepared to re-download all the messages.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "MessageCount=" & Stats.MessageCount & " RecentCount=" & Stats.RecentCount & " UnseenCount=" & Stats.UnseenCount
    MsgBox "UIDValidity=" & Stats.UIDValidity & " UIDNext=" & Stats.UIDNext
  End If
  Mailer.Disconnect
End If

See Also:

UIDNext Property


UnseenCount Property

The number of unread messages in the mailbox.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer, Stats
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.IMAP4")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.IMAP4")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\imap4_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"
If Mailer.Connect("mail.server.com", 143, "MyName", "MyPassword") Then
  Set Stats = Mailer.GetMailboxStatus("Inbox")
  If Not Stats Is Nothing Then
    MsgBox "MessageCount=" & Stats.MessageCount & " RecentCount=" & Stats.RecentCount & " UnseenCount=" & Stats.UnseenCount
    MsgBox "UIDValidity=" & Stats.UIDValidity & " UIDNext=" & Stats.UIDNext
  End If
  Mailer.Disconnect
End If

See Also:

RecentCount Property


CertInfo Object

The CertInfo object provides access to properties of the client or the server certificate.

Syntax

CertInfo.property

Properties
ExpirationDate | Date and time after which the certificate is not valid.
Email | Email address associated with the certificate.
FriendlyName | Friendly name of the person or entity to whom the certificate is being issued. May be empty.
IssuedBy | Name of the certification authority which issued the certificate.
IssuedTo | Name of the person or entity to whom the certificate is being issued.

See Also

SSL Object, SMIME Object

Send feedback to AfterLogic


ExpirationDate Property

Contains the date when the certificate expires.

Value Type: | Date
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  MsgBox Mailer.SSL.ServerCert.ExpirationDate ' display the expiration date the server certificate
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

CertInfo Object


FriendlyName Property

Contains the friendly name of the certificate owner.

The friendly name is often empty. The primary name of the certificate owner is contained in IssuedTo property.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  MsgBox Mailer.SSL.ServerCert.IssuedTo' display the name of the certificate owner
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

CertInfo Object

IssuedTo Property


Email Property

Contains the e-mail address of the certificate owner.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  MsgBox Mailer.SSL.ServerCert.Email' display the email of the certificate owner
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

CertInfo Object

IssuedTo Property


IssuedBy Property

Contains the issuer name.

The issuer is a certification authority who issued the certificate to the IssuedTo.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  MsgBox Mailer.SSL.ServerCert.IssuedBy ' display info on who issued the certificate to the server
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

CertInfo Object

FriendlyName Property
IssuedTo Property


IssuedTo Property

Contains the certificate owner name.

This is the server or person name the certificate is issued to.

Also, the certificate owner often has FriendlyName.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

Dim Mailer
'Using visual basic to create object
Set Mailer = CreateObject("MailBee.SMTP")
'Using ASP to create object
'Set Mailer = Server.CreateObject("MailBee.SMTP")
'In ASP use Response.Write instead of MsgBox
Mailer.EnableLogging = True
Mailer.LogFilePath = "C:\Temp\smtp_log.txt"
Mailer.ClearLog
Mailer.LicenseKey = "put your license key here"

' Set SSL connection over STARTTLS command
Mailer.SSL.Enabled = True
Mailer.SSL.UseStartTLS = True

Mailer.ServerName = "mail.server.com"
If Mailer.Connect Then
  MsgBox Mailer.SSL.ServerCert.IssuedTo' display the name of the certificate owner
Else
  MsgBox Mailer.ErrDesc
End If

See Also:

CertInfo Object

FriendlyName
IssuedBy Property


Uploader Object

Uploader object allows to upload files selected in the HTML-form on to the server. It is used only in ASP. All the HTML-form data are stored in corresponding Uploader object collections:

  • FormElements - a collection of FormElement objects (for example, input elements, select elements and etc., except for files)
  • FormFiles - a collection of FormFile objects defined in HTML-form by the <INPUT TYPE=file> tag
To initialize the collections with the HTML-form elements use ParseRequest method. It gets as a parameter the data sent to the server from the client as part of a POST request (generally, value returned by ASP's Request.BinaryRead method).

If you have problems with the representation of uploaded data (for example, '???' or 'aei' instead of international characters) or if you use <@ CODEPAGE> or Session.Codepage directives on your ASP page, consider Uploader.Codepage property.

Syntax

Uploader.property|method

Collections
FormElements | The collection of the HTML-form elements
FormFiles | The collection of the HTML-form files
Properties
Codepage | Defines the codepage in which the request will be treated
Methods
ParseRequest | Initializes Uploader object collections with HTML-form elements

Remarks

Use MailBee.Uploader object only in ASP applications.

Example

For proper work of this example you should create two separate files. In the first file implement ASP's commands intended for work with uploaded elements and files (the first piece of the example's code, "filename.asp"). In the second file HTML-form should be implemented (the second piece of the code, "filename.htm").

' "filename.asp"
<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
For Each File In Uploader.FormFiles
   File.SaveToDisk "C:\Temp"
Next %>

' "filename.htm"
<form action="filename.asp" method="post" enctype="multipart/form-data">
<input type=file name=file1>
<input type=file name=file2>
<select name="abc" multiple>
   <option selected>1
   <option selected>2
</select>
<select name="abc" multiple>
   <option selected>1
   <option selected>2
</select>
<input type=text name=x>
<input type=submit>
</form>

See Also

FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object

Send feedback to AfterLogic


ParseRequest Method

ParseRequest method handles all HTML-form data and initializes the FormElements and FormFiles collections with the corresponding objects.

blnResult = ObjectName.ParseRequest(pvt)
Parameters: |
pvt as Variant Byte Array | An array which contains the data sent to the server from the client form (generally, value returned by ASP's Request.BinaryRead method)
Return value As Boolean | True if successful, False otherwise

Usage example:

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
For Each File In Uploader.FormFiles
   File.SaveToDisk "C:\Temp\"
Next %>

See Also:

FormElements Collection| FormFiles Collection| FormElement Object| FormFile Object| Uploader Object


Codepage Property

This property determines the codepage in which the request will be treated. Set this property if you use specific languages (for example, Japanese, Hindi, etc.) or the codepage of the HTML-form data differs from the server's one.

The default value is 0, that means the system codepage.

Value Type: | Long
Parameters: | None

Usage example:

' For proper work of this example you should create two separate files.
' In the first file implement ASP's commands intended for work with uploaded elements and files
' (the first piece of the example's code, "filename.asp").
' In the second file HTML-form should be implemented (the second piece of the code, "filename.htm").
' This sample writes the content of the last file in the collection.

' "filename.asp"
<%@ CODEPAGE = 1252 %>
<% Response.CharSet = "windows-1252" %>
<%
Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.Codepage = 1252
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormFiles.Count <> 0) Then
   Set Element = Uploader.FormElements(Uploader.FormElements.Count)
   Response.Write Element.Value
End If
%>

' "filename.htm"
<form action="filename.asp" method="post" enctype="multipart/form-data">
<input type=file name=file1>
<input type=file name=file2>
<input type=text name=field>
<input type=submit>
</form>

See Also:

Uploader Object


FormElements Collection

The FormElements collection contains FormElement objects used to store all the HTML-form elements except for files.

The FormElement objects are retrieved by the Uploader.ParseRequest method.

Syntax

FormElements.property

Properties
Count | Returns the number of FormElement objects in the collection.
Item | Returns a reference to an element of the collection.

Remarks

Item is the default property of the collection, so FormElements.Item(index) and FormElements(index) are equivalents.

To iterate through the collection, you can use either For .. Each statement or any common loop statement such as For .. To.

Example

The following examples use different syntax to display names of all elements in a HTML-form. It's assumed the FormElements collection has been already retrieved and stored in objFormElements object.

For .. Each syntax
For Each objFormElement In objFormElements
  Response.Write objFormElement.Name
Next

For .. To syntax
For I = 1 To objFormElements.Count
  Response.Write objFormElement.Name
Next

See Also

FormFiles Collection | FormFile Object | Uploader Object

Send feedback to AfterLogic


Count Property

Returns the number of FormElement objects in the collection.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the number of HTML-form elements in the collection

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
Response.Write Uploader.FormElements.Count %>

See Also:

Item Property | Uploader Object


Item Property

Returns a FormElement object from the collection.

Index parameter specifies the index of the element in the collection. If Index is out of range, automation error occurs.

Item is the default property of the collection.

Value Type: | MailBee.FormElement
Parameters: |
Index As Long | Index of the element to return. Allowed range is: 1 <= Index <= FormElements.Count
Remarks: | This property is read-only

Usage example:

' This sample writes the name of the last HTML-form element

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormElements.Count <> 0) Then
   Set FormElement = Uploader.FormElements(Uploader.FormElements.Count)
   Response.Write FormElement.Name
End If %>

See Also:

Count Property | Uploader Object


FormElement Object

FormElement object contains uploaded HTML-form elements. FormElements collection is initialized with this objects.

Syntax

FormElement.property

Properties
Name | The name of the associated form element.
Value | The value of the associated form element.

Example

This sample writes the name and the value of the last FormElement object in the collection.
<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormElements.Count <> 0) Then
   Set FormElement = Uploader.FormElements(Uploader.FormElements.Count)
   Response.Write FormElement.Name
   Response.Write " = "
   Response.Write FormElement.Value
End If %>

See Also

FormElements Collection | FormFiles Collection | FormFile Object | Uploader Object

Send feedback to AfterLogic


Name Property

Contains name of the associated HTML-form element.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the names of all HTML-form elements in the collection

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormElements.Count) <> 0 Then
   For Each Element in Uploader.FormElements
      Response.Write Element.Name
      Response.Write ";"
   Next
End If %>

See Also:

Value Property | FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


Value Property

Contains value of the associated HTML-form element (content of the data field, or value of such elements as 'select', etc.). In case of multiple element values are comma separated.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the values of all HTML-form elements in the collection

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormElements.Count <> 0) Then
   For Each Element in Uploader.FormElements
      Response.Write Element.Value
      Response.Write "|"
   Next
End If %>

See Also:

Name Property | FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


FormFiles Collection

The FormFiles collection contains FormFile objects used to store files selected in HTML-form.

The FormFile objects are retrieved by the Uploader.ParseRequest method.

Syntax

FormElements.property

Properties
Count | Returns the number of FormFile objects in the collection.
Item | Returns a reference to an element of the collection.

Remarks

Item is the default property of the collection, so FormFiles.Item(index) and FormFiles(index) are equivalents.

To iterate through the collection, you can use either For .. Each statement or any common loop statement such as For .. To.

Example

The following examples use different syntax to display names of all files selected in a HTML-form. It's assumed the FormFiles collection has been already retrieved and stored in objFormFiles object.

For .. Each syntax
For Each objFormFile In objFormFiles
  Response.Write objFormFile.Name
Next

For .. To syntax
For I = 1 To objFormFiles.Count
  Response.Write objFormFile.Name
Next

See Also

FormElements Collection | FormElement Object | Uploader Object

Send feedback to AfterLogic


Count Property

Returns the number of FormFile objects in the collection.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the number of file elements existed in HTML-form

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
Response.Write Uploader.FormFiles.Count %>

See Also:

Item Property | Uploader Object


Item Property

Returns a FormFile object from the collection.

Index parameter specifies the index of the element in the collection. If Index is out of range, automation error occurs.

Item is the default property of the collection.

Value Type: | MailBee.FormFile
Parameters: |
Index As Long | Index of the element to return. Allowed range is: 1 <= Index <= FormFile.Count
Remarks: | This property is read-only

Usage example:

' This sample writes the name of the last file element existed in HTML-form

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormFiles.Count <> 0) Then
   Set FormFile = Uploader.FormFiles(Uploader.FormFiles.Count)
   Response.Write FormFile.Name
End If %>

See Also:

Count Property | Uploader Object


FormFile Object

Each file uploaded via HTML-form corresponds to FormFile object. All FormFile objects are contained in FormFiles collection.

Syntax

FormFile.property|method

Properties
ContentType | Returns the uploaded file's content type.
Filename | Returns the uploaded file's name.
Name | The name of the associated file element.
Size | Returns the uploaded file's size.
Value | Returns the uploaded file's content.
ValueAsArray | Returns the uploaded file's content as array of bytes.
Methods
SaveToDisk | Saves the file to disk.

Example

This sample writes the name of the last FormFile object in the collection.
<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormFiles.Count <> 0) Then
   Set FormFile = Uploader.FormFiles(Uploader.FormFiles.Count)
   Response.Write FormFile.Name
End If %>

See Also

FormElements Collection | FormFiles Collection | FormElement Object | Uploader Object

Send feedback to AfterLogic


SaveToDisk Method

Call the SaveToDisk method to save the uploaded file to disk.

ObjectName.SaveToDisk(DirPath, [Filename])
Parameters: |
DirPath as String | Specifies the folder path to save the uploaded file in.
Filename as String | (optional) Specifies the file name associated with the uploaded file. If the Filename parameter is empty, the uploaded file will be saved with its original name.
Return valueBoolean | True if successful, False if error has occurred

Usage example:

' This sample saves the last file in the collection with the specified by user file name

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormElements.Count <> 0) Then
   Set File = Uploader.FormFiles(Uploader.FormFiles.Count)
   File.SaveToDisk "C:\Temp\", "type the new file name here"
End If %>

See Also:

FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


ContentType Property

Returns the uploaded file's content-type.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the content-types of all selected files

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
For Each File in Uploader.FormFiles
   Response.Write File.ContentType
   Response.Write ";"
Next %>

See Also:

FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


Filename Property

Returns name of the file selected in the file element.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the names of all files in the collection

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
For Each File in Uploader.FormFiles
   Response.Write File.Filename
   Response.Write ";"
Next %>

See Also:

FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


Name Property

Returns name of form's <input type=file> element used for selecting a file to upload (e.g. myFile in <input type=file name=myFile>).
Note: To get actual filename of the file have been uploaded, use Filename property.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the names of all file elements in the collection

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
For Each File in Uploader.FormFiles
   Response.Write File.Name
   Response.Write ";"
Next %>

See Also:

FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


Size Property

Returns the uploaded file's size in bytes.

Value Type: | Long
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the size of the last uploaded file

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormFiles.Count <> 0) Then
   Set File = Uploader.FormFiles(Uploader.FormFiles.Count)
   Response.Write File.Size
End If %>

See Also:

FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


Value Property

Returns the uploaded file's content as a string.

Value Type: | String
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the content of the last uploaded file

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormFiles.Count <> 0) Then
   Set File = Uploader.FormFiles(Uploader.FormFiles.Count)
   Response.Write File.Value
End If %>

See Also:

Size Property | ValueAsArray Property | FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


ValueAsArray Property

Returns the uploaded file's content as array of bytes.

Value Type: | Array
Parameters: | None
Remarks: | This property is read-only

Usage example:

' This sample writes the content of the last uploaded file

<% Set Uploader = Server.CreateObject("MailBee.Uploader")
Uploader.ParseRequest Request.BinaryRead(Request.TotalBytes)
If (Uploader.FormFiles.Count <> 0) Then
   Set File = Uploader.FormFiles(Uploader.FormFiles.Count)
   Response.BinaryWrite File.ValueAsArray
End If %>

See Also:

Size Property | Value Property | FormElements Collection | FormFiles Collection | FormElement Object | FormFile Object | Uploader Object


AfterLogic Software License Agreement

1. IMPORTANT NOTICE.
YOU SHOULD READ THE FOLLOWING TERMS AND CONDITIONS CAREFULLY BEFORE
YOU DOWNLOAD, INSTALL OR USE AFTERLOGIC'S PROPRIETARY SOFTWARE AND
RELATED DOCUMENTATION (THE "LICENSED SOFTWARE") DISTRIBUTED UNDER THE
TRADEMARK OF MAILBEE AND/OR AFTERLOGIC. BY INSTALLING OR USING THE
LICENSED SOFTWARE, YOU AGREE TO BE BOUND BY THIS LICENSE AGREEMENT,
AND ITS TERMS SHALL BE BINDING WITH RESPECT TO YOUR USE OF THE
LICENSED SOFTWARE. IF YOU DO NOT AGREE TO THE FOLLOWING TERMS AND
CONDITIONS, DO NOT INSTALL OR USE THE SOFTWARE.

2. DEFINITIONS.
When used in this Agreement, "AfterLogic" means AfterLogic
Corporation, located in Cheyenne, WY, USA, and the words "You" and
"Your" mean the party purchasing a license to use the Licensed
Software under the terms of this agreement.

"Licensed Software" means compiled Objects, Modules, License Key and
any and all updates thereto, together with all associated
documentation provided by AfterLogic or its authorized resellers.
Licensed Software also means uncompiled source code if such source
code is provided to You by AfterLogic.

"License Key" means a unique code provided by AfterLogic or its
authorized resellers which identifies You, as well as the license
type, and which unlocks or enables certain features of the Licensed
Software.

"Application" or "Your Application" means a software application that
You develop which incorporates all or parts of the Licensed Software.

"Evaluation Trial Period" means a specified period of time during
which You may temporarily use the Licensed Software for evaluation
purposes only.

"Third Party Code" means compiled and/or source code of third party
software modules which may be distributed alongside Licensed Software.

3. LICENSE GRANT.
The Cumulative License granted to You by AfterLogic is a combination
of the Base License Grant, described in section (3A) below, which is
common to every Licensed Software title covered by this agreement, and
one or more supplemental License Grant which covers the specific
product obtained by You from AfterLogic or its authorized resellers.
Four basic types of supplemental License Grants are described in
sections (3B) through (3E): Evaluation License, Developer License,
Computer License, Hosting Provider License. These four basic types are
hereby further defined and/or restricted as to the number of
developers, servers, locations and distribution method(s), depending
on the specific product(s) being licensed by You. The precise
combination of the Base License Grant and one or more supplemental
License Grant(s) obtained by You is identified by AfterLogic at the
time of purchase or most recent upgrade.

3A. BASE LICENSE GRANT.
In consideration of Your payment of applicable license fees and/or
Your acceptance of the terms of this Agreement, AfterLogic hereby
grants to You certain nonexclusive and nontransferable rights limited
by the terms of this Agreement. The Licensed Software is licensed (not
sold) to You, for use strictly under the terms of this Agreement, and
AfterLogic reserves all rights not expressly granted to You herein. If
You upgrade the Licensed Software to a higher-numbered version thereof
or to a comparable AfterLogic product, this license is terminated and
Your rights shall be limited to the license associated with the
upgraded product or version. In addition, You acknowledge that the
Licensed Software may contain certain third party software components
which are distributed under the terms of their own licenses.

3B. EVALUATION LICENSE.
In order to facilitate an efficient evaluation process of the Licensed
Software by developers, AfterLogic may, at its discretion, provide
specially designed, temporary License Key(s) that are encoded with an
embedded expiration date. The License granted in conjunction with such
License Key(s) is considered temporary, and multiple developers may
use it for the sole purpose of evaluating the Licensed Software during
a specific Evaluation Trial Period. Licensed Evaluation Trial Software
contains mechanisms that inhibit its ability to function at a later
date. It is Your responsibility to ensure that the Applications You
create do not contain Licensed Evaluation Trial Software and that
their ability to function at a later date is not inhibited or
diminished.

3C. DEVELOPER LICENSE.
The following terms and conditions contained in this section (3C)
apply to You ONLY if at the time of original purchase or most recent
upgrade, the License granted to You by AfterLogic was defined as
"Developer License". The specific license level selected by you at the
time of purchase or most recent upgrade determines whether the license
applies to (1) a single named developer, or (2) a team of named
developers, for example a “4 Developer Team,” or (3) a single site
(facility or campus) whereby an unlimited number of developers located
within said site (facility or campus) may be allowed access to the
Licensed Software. You are hereby granted a nonexclusive, royalty-free
license to integrate the Licensed Software into Your Applications and
to distribute such Licensed Software in connection with said
Applications, provided that (a) said Applications do not in any way
compete with the Licensed Software, or provide substantially the same
functionality as the Licensed Software, or expose the functionality of
the Licensed Software through a programmable interface; (b) each of
Your Applications developed using Licensed Software is substantially
larger, more complex, and contains a significantly wider range of
functions as compared to the Licensed Software; (c) each of Your
Applications developed using Licensed Software is designed for end
users, rather than for developers who would be able to build other
software that would compete with the Licensed Software, and (d) You do
not permit further distribution of the Licensed Software by Your end
users. You may embed the License Keys in the Applications You
distribute, provided that the following conditions are met: (a) each
such Application must be marked with a prominent copyright notice
bearing Your name as declared by You during purchase of the License;
(b) the License Key may not be embedded in any such Application or
distributed in any other manner that makes the License Key visible to
the end user, and (c) each such Application must include the following
comment in its source code within close proximity to each copy of an
embedded License Key: "This application utilizes a licensed copy of
AfterLogic software, copyright (c) 2002-2020, which is the property of
AfterLogic Corporation, www.afterlogic.com. All rights are reserved by
AfterLogic. Use of any objects outside of the context of this
application is a violation of United States and international
copyright laws and other applicable laws." For each License Key
provided to You by AfterLogic, depending on the specific license level
selected by you at the time of purchase or most recent upgrade, You
are granted a nonexclusive License to make the Licensed Software
and/or the License Key(s) available either to the specified number of
Your named developers or to an unlimited number of Your developers
located at a single site (facility or campus) as indicated by
AfterLogic and further explained below. Should either the number of
named developers or the number of sites with access to the Licensed
Software and/or the License Key(s) ever exceed the number indicated at
the time of original purchase or most recent upgrade, You agree to
inform AfterLogic of such change and to upgrade Your License
accordingly by paying an upgrade fee to AfterLogic in a timely manner.

"1 Developer License" which may also be referred to as "Single
Developer License" means that only one named individual developer
employed by You may be given access to the Licensed Software and/or
the License Key(s) for the sole purpose of developing and maintaining
Your Applications. For as long as this specific individual developer
is employed or engaged by You in any capacity whatsoever whereby he or
she may access the Licensed Software and/or the License Key(s), no
other developer may be given access to the Licensed Software and/or
the License Key(s). Should said individual developer leave Your employ
and cease any professional association with You, or otherwise
relinquish any and all access the Licensed Software and/or the License
Key(s), a new named individual developer may then take his or her
place and be given access to the Licensed Software and/or the License
Key(s).

"Developer Team License" is equivalent to a specified number of single
developer licenses. For example a "4 Developers Team License" is
equivalent to 4 single developer licenses. The number of developers in
a team identifies the maximum number of the named individual
developers employed by You who may be given access to the Licensed
Software and/or the License Key(s) for the sole purpose of developing
and maintaining Your Applications. For as long as the allowed maximum
number of named individual developers are employed or engaged by You
in any capacity whatsoever whereby these named individual developers
may access the Licensed Software and/or the License Key(s), no other
developer may be given access to the Licensed Software and/or the
License Key(s). Should any single named individual developer leave
Your employ and cease any professional association with You, or
otherwise relinquish any and all access the Licensed Software and/or
the License Key(s), a new named individual developer may then take his
or her place and be given access to the Licensed Software and/or the
License Key(s), whereby the total number of said named developers
would not exceed the licensed team size.

"Unlimited Developer Site License" means that an unlimited number of
developers at one site (facility or campus) may be given access to the
Licensed Software and/or the License Key(s) for the sole purpose of
developing and maintaining Your Applications.

"Enterprise License" means that an unlimited number of developers
employed by You (including subsidiaries and contractors of Your
organization) may be given access to the Licensed Software and/or the
License Key(s) for the sole purpose of developing and maintaining Your
Applications.

3D. COMPUTER LICENSE.
The following terms and conditions contained in this section (3D)
apply to You ONLY if at the time of original purchase or most recent
upgrade, the License granted to You by AfterLogic was defined as
"Single Computer License" or "Unlimited Computer License". Important
Note: Under the terms of the Computer License, distribution of the
Licensed Software or the related License Keys, in any form whatsoever,
is strictly prohibited. Furthermore, under the Computer License the
use of the Licensed Software may NOT be extended by hosting providers
to their hosting clients and/or subscribers. Hosting providers and
Internet Service Providers must select the Hosting Provider License if
any functionality of the Licensed Software is to be made available,
accessible or usable by their hosting clients and/or subscribers. You
may embed the License Keys in other Applications installed on the same
physical server(s) provided that the following conditions are met: (a)
each such Application must be marked with a prominent copyright notice
bearing Your name as declared by You during purchase of the License;
(b) the License Key may not be embedded in any such Application or
stored in any other manner that makes the License Key visible to the
end user, and (c) each such Application must include the following
comment in its source code within close proximity to each copy of an
embedded License Key: "This application utilizes a licensed copy of
AfterLogic software, copyright (c) 2002-2010, which is the property of
AfterLogic Corporation, www.afterlogic.com. All rights are reserved by
AfterLogic. Use of any objects outside of the context of this
application is a violation of United States and international
copyright laws and other applicable laws."

"Single Computer License" means that You are granted a license to
install the Licensed Software on a single physical production server,
without limitation as to the number of central processing units on the
server, and on any number of development workstations and servers
which can only be used for testing and development purposes.

"Unlimited Computer License" means that You are granted a license to
install the Licensed Software on any number of physical servers
maintained or owned by You, without limitation as to the number of
central processing units on each server.

3E. HOSTING PROVIDER LICENSE.
The following terms and conditions contained in this section (3E)
apply to You ONLY if at the time of original purchase or most recent
upgrade, the License granted to You by AfterLogic was defined as
"Hosting Provider License" which permits access to or use of shared
server installed instance(s) of the Licensed Software by third party
users, including hosting clients and/or Internet service subscribers.
Important Note: Under the terms of the Hosting Provider License,
distribution of the Licensed Software or the related License Keys, in
any form whatsoever, is strictly prohibited. You are hereby granted a
nonexclusive license to install the Licensed Software on physical
server(s) maintained or owned by You, without limitation as to the
number of central processing units on each server. The specific
license level selected by you at the time of purchase or most recent
upgrade determines the maximum number of allowed shared server
installed instances of the Licensed Software as well as the maximum
number of domain names that may be serviced by the Licensed Software.
The License Key obtained by You as part of Your Hosting Provider
License may only be entered into the registry or config file of the
applicable physical server provided that the License Key may not be
stored in any manner that makes the License Key visible to the end
user. Installation of the Licensed Software on any server, accessible
to your hosting clients and/or subscribers, in any manner, which would
make it physically possible for Your hosting clients, subscribers, or
any other individual not directly employed by Your organization, to
potentially migrate, reinstall, transfer or copy the Licensed Software
to any other server whatsoever would be considered unauthorized
distribution and is expressly prohibited under this license. In case
any of Your hosting clients and/or subscribers desires to use a
dedicated installed server instance of the Licensed Software, or to
gain the type of access to the Licensed Software which may potentially
allow such client and/or subscriber to migrate, reinstall, transfer or
copy the Licensed Software to another server, each such client and/or
subscriber would be required to obtain a separate software license
from AfterLogic Corporation.

4. RESTRICTIONS ON USE AND TRANSFER.
You may not sublicense, rent, lease, assign or otherwise transfer the
Licensed Software or any of Your rights thereto, either in whole or in
part, to anyone else, except that:
- You may, after obtaining written permission from AfterLogic, permanently
transfer the Licensed Software in its entirety, provided You retain no
copies of the Licensed Software and the transferee agrees to the terms and
conditions of this Agreement.
- You may assign the agreement to a subsequent entity without Afterlogic
consent in case of acquisition of Your organization by that entity.

Use of the Licensed Software with a License Key obtained
from a source other than AfterLogic or its authorized resellers is
expressly and strictly forbidden. AfterLogic reserves the right to
take any and all actions that AfterLogic, in its sole discretion,
deems necessary to protect against, monitor and control the use of the
Licensed Software with illegal License Keys. You agree to ensure that
anyone who uses any portion of the Licensed Software provided to You
complies with the terms and conditions of this Agreement.

5. INTELLECTUAL PROPERTY RIGHTS.
You acknowledge that the Licensed Software contains copyrighted
material, trade secrets, trademarks and other proprietary material of
AfterLogic ("Confidential Information"), and is protected under United
States and international copyright law and other applicable laws. You
may not engage in any unauthorized use or disclosure of any
Confidential Information. You agree that the source code of the
Licensed Software is confidential and proprietary to AfterLogic.
Accordingly, You may not copy the Licensed Software, or decompile,
disassemble, reverse engineer or create a derivative work based upon
the Licensed Software, or authorize anyone else to do so. You must
reproduce and maintain all copyright notices that are contained in the
Licensed Software on any copy thereof that You make or use.

6. TERM AND TERMINATION.
Except as otherwise provided in this Agreement, depending on the
specific license level selected by you at the time of purchase or most
recent upgrade, the term of the license granted herein is either
perpetual, or alternatively the license is periodic, valid for a
specific period of time, such as a month or a year. The license
becomes effective when You install or use the Licensed Software. You
may terminate this license at any time by destroying any and all
copies of the Licensed Software or by returning all such copies to
AfterLogic. This Agreement and the associated license for the Licensed
Software will terminate automatically and without provision of notice
by AfterLogic if You fail to comply with any of the terms or
conditions of this Agreement or if You cease permanent use of the
Licensed Software, for whatever reason. Upon termination of this
Agreement for any reason, You agree that You will destroy all copies
of the Licensed Software or return all such copies to AfterLogic. In
addition to this sentence and the previous sentence, Sections 4, 5 and
7-13 shall survive any termination of this Agreement.

7. LIMITED WARRANTY.
AfterLogic warrants that the Licensed Software will perform
substantially in accordance with its accompanying documentation, when
operated in the execution environment specified in such documentation,
for the warranty period ending thirty (30) days following the date on
which You first install or first use the Licensed Software. This
limited warranty is void if failure of the Licensed Software to
conform to such warranty is caused in whole or in part by (a) any
defect in any hardware or other equipment used with the Licensed
Software; (b) any failure of any hardware or any other equipment used
with the Licensed Software to function in accordance with applicable
manufacturer's specifications for such items; (c) any alteration,
modification or enhancement of the Licensed Software by You or anyone
other than AfterLogic; (d) any failure by You or anyone else to follow
AfterLogic's instructions with respect to proper use of the Licensed
Software; or (e) improper use, abuse, accident, neglect or negligence
on the part of You or anyone other than AfterLogic. AfterLogic will
not be obligated to honor the limited warranty or provide any remedy
thereunder unless the Licensed Software is returned to AfterLogic
along with the original dated receipt. Any replacement Licensed
Software will be warranted for thirty (30) days following the date on
which AfterLogic provides it to You. You understand that no Licensed
Software updates or upgrades are included with this limited warranty
and that AfterLogic may update or revise the Licensed Software at any
time and, in so doing, incurs no obligation to furnish such updates or
revisions to You.

EXCEPT AS OTHERWISE SET FORTH IN THIS AGREEMENT, THE LICENSED SOFTWARE
IS PROVIDED TO YOU "AS IS", AND AFTERLOGIC MAKES NO EXPRESS OR IMPLIED
WARRANTIES WHATSOEVER WITH RESPECT TO ITS FUNCTIONALITY, CONDITION,
PERFORMANCE, OPERABILITY OR USE. WITHOUT LIMITING THE FOREGOING,
AFTERLOGIC DISCLAIMS ALL IMPLIED WARRANTIES INCLUDING, WITHOUT
LIMITATION, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE OR FREEDOM FROM INFRINGEMENT. SOME JURISDICTIONS DO
NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO THE ABOVE EXCLUSIONS
MAY NOT APPLY TO YOU. THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL
RIGHTS, AND YOU MAY ALSO HAVE OTHER RIGHTS THAT VARY FROM ONE
JURISDICTION TO ANOTHER.

8. LIMITATIONS OF LIABILITY.
YOUR SOLE AND EXCLUSIVE REMEDY FOR ANY BREACH OF THE FOREGOING LIMITED
WARRANTY SHALL BE, AT AFTERLOGIC'S OPTION, EITHER (A) REPAIR OR
REPLACEMENT OF THE LICENSED SOFTWARE SO THAT IT CONFORMS TO THE
FOREGOING LIMITED WARRANTY, OR (B) REFUND OF THE FEE THAT YOU PAID TO
LICENSE THE LICENSED SOFTWARE. IN NO EVENT SHALL AFTERLOGIC BE LIABLE
FOR ANY DAMAGES OF ANY TYPE, WHETHER DIRECT OR INDIRECT,
CONSEQUENTIAL, INCIDENTAL OR SPECIAL DAMAGES, INCLUDING WITHOUT
LIMITATION, LOST REVENUES, LOST PROFITS, LOSSES RESULTING FROM
BUSINESS INTERRUPTION OR LOSS OF DATA, REGARDLESS OF THE FORM OF
ACTION OR LEGAL THEORY UNDER WHICH SUCH LIABILITY MAY BE ASSERTED,
EVEN IF AFTERLOGIC HAS BEEN ADVISED OF THE POSSIBILITY OR LIKELIHOOD
OF SUCH DAMAGES. AFTERLOGIC SHALL HAVE NO LIABILITY WITH RESPECT TO
ANY DATA THAT IS READ, ACCESSED, STORED OR PROCESSED WITH THE LICENSED
SOFTWARE, OR FOR THE COSTS OF RECOVERING ANY SUCH DATA. IN NO EVENT
SHALL AFTERLOGIC'S MAXIMUM AGGREGATE LIABILITY UNDER THIS AGREEMENT
EXCEED THE TOTAL FEES PAID OR PAYABLE BY YOU TO LICENSE THE LICENSED
SOFTWARE. SOME JURISDICTIONS DO NOT ALLOW THE LIMITATION OR EXCLUSION
OF LIABILITY FOR INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THE ABOVE
LIMITATION OR EXCLUSION MAY NOT APPLY TO YOU.

9. INDEMNIFICATION.
You agree to defend, indemnify, and hold AfterLogic and all of its
employees, agents, representatives, directors, officers, partners,
shareholders, attorneys, predecessors, successors, and assigns
harmless from and against any and all claims, proceedings, damages,
injuries, liabilities, losses, costs, and expenses (including
reasonable attorneys' fees and litigation expenses), relating to or
arising from Your use of the Licensed Software, or any breach of this
Agreement, except to the extent such claim relates to or arises from a
violation by AfterLogic of any third party copyright, trademark, trade
secret or other intellectual property right.

10. EXPORT.
You agree that You will not export or transmit the Licensed Software
or any Applications, directly or indirectly, to any restricted
countries or in any manner that would violate United States laws and
regulations as shall from time to time govern the license and delivery
of technology abroad by persons subject to the jurisdiction of the
United States government, including the Export Administration Act of
1979, as amended, and any applicable laws or regulations issued
thereafter.

11. U.S. GOVERNMENT RESTRICTED RIGHTS.
If You are licensing the Licensed Software on behalf of the U.S.
Government or any of its agencies ("Government"), the use,
duplication, reproduction, release, modification, disclosure or
transfer of the Licensed Software by the Government is subject to
restricted rights in accordance with Federal Acquisition Regulation
("FAR") 12.212 for civilian agencies and Defense Federal Acquisition
Regulation Supplement ("DFARS") 227.7202 for military agencies. The
Licensed Software is commercial. Use of the Licensed Software by the
Government is further restricted in accordance with the terms and
conditions of this Agreement.

12. MISCELLANEOUS.
If any provision of this Agreement is held to be invalid or
unenforceable under any circumstances, its application in any other
circumstances and the remaining provisions of this Agreement shall not
be affected. No waiver of any right under this Agreement shall be
effective unless given in writing by an authorized representative of
AfterLogic. No waiver by AfterLogic of any right shall be deemed to be
a waiver of any other right of AfterLogic arising under this
Agreement. This Agreement is solely between You and AfterLogic and
shall not be construed to create any third party beneficiary rights in
any other individual, partnership, corporation or other entity. This
Agreement shall be governed by and interpreted in accordance with the
laws of the State of New York, without regard to its provisions
governing conflicts of law. Any and all disputes between You and
AfterLogic pertaining to this Agreement shall be submitted to one
arbitrator in binding arbitration within ten miles of New York City,
New York in accordance with the Commercial Rules of the American
Arbitration Association ("AAA"). The arbitrator shall be experienced
in computer consulting, the development of custom software, the sale
of packaged software, or related services. If You and AfterLogic do
not agree on an arbitrator within sixty (60) days of the institution
of the arbitration, the arbitrator shall be chose by AAA. Evidence and
argument may be presented in person or by telephone, fax, postal mail,
electronic mail, and other methods of communication approved by the
arbitrator. The prevailing party in such proceeding shall be entitled
to recover its actually incurred costs, including reasonable
attorney's fees, arbitration and court costs. All hearings shall be
held and a written arbitration award issued within one-hundred eighty
(180) days of the date on which the arbitrator is appointed. Judgment
on the award shall be final and binding and may be entered in any
court of competent jurisdiction.

13. ENTIRE AGREEMENT.
YOU AGREE THAT THIS AGREEMENT IS THE COMPLETE AND EXCLUSIVE STATEMENT
OF THE AGREEMENT BETWEEN YOU AND AFTERLOGIC, AND THAT IT SUPERSEDES
ANY PROPOSALS OR PRIOR AGREEMENTS, ORAL OR WRITTEN, AND ANY OTHER
COMMUNICATIONS RELATING TO THE LICENSED SOFTWARE AND THE SUBJECT
MATTER HEREOF. AFTERLOGIC SHALL NOT BE BOUND BY ANY PROVISION OF ANY
PURCHASE ORDER, RECEIPT, ACCEPTANCE, CONFIRMATION, CORRESPONDENCE OR
OTHERWISE, OR BY ANY AGREEMENT BETWEEN YOU AND ANY OTHER PARTY, UNLESS
AFTERLOGIC SPECIFICALLY AGREES TO SUCH PROVISION IN WRITING IN A FORM
OF A LEGAL CONTRACT, DATED AND SIGNED BY YOU AND BY AFTERLOGIC'S
OFFICER OR AUTHORIZED EMPLOYEE. NO VENDOR, DISTRIBUTOR, PROVIDER,
RESELLER, OEM, SALES REPRESENTATIVE, OR OTHER PERSON IS AUTHORIZED TO
MODIFY THIS AGREEMENT OR TO MAKE ANY WARRANTY, REPRESENTATION OR
PROMISE REGARDING THE LICENSED SOFTWARE WHICH IS DIFFERENT FROM THOSE
SET FORTH IN THIS AGREEMENT.