SQL Server
SQL Server
Download MIME Source of Emails in IMAP Mailbox
Demonstrates how to download the MIME source for emails on an IMAP server.Chilkat SQL Server Downloads
-- Important: See this note about string length limitations for strings returned by sp_OAMethod calls.
--
CREATE PROCEDURE ChilkatSample
AS
BEGIN
DECLARE @hr int
-- Important: Do not use nvarchar(max). See the warning about using nvarchar(max).
DECLARE @sTmp0 nvarchar(4000)
DECLARE @success int
SELECT @success = 0
-- This example assumes the Chilkat API to have been previously unlocked.
-- See Global Unlock Sample for sample code.
DECLARE @imap int
EXEC @hr = sp_OACreate 'Chilkat.Imap', @imap OUT
IF @hr <> 0
BEGIN
PRINT 'Failed to create ActiveX component'
RETURN
END
-- Connect to an IMAP server.
-- Use TLS
EXEC sp_OASetProperty @imap, 'Ssl', 1
EXEC sp_OASetProperty @imap, 'Port', 993
EXEC sp_OAMethod @imap, 'Connect', @success OUT, 'imap.example.com'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @imap, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @imap
RETURN
END
-- Login
EXEC sp_OAMethod @imap, 'Login', @success OUT, 'myLogin', 'myPassword'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @imap, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @imap
RETURN
END
-- Select an IMAP mailbox
EXEC sp_OAMethod @imap, 'SelectMailbox', @success OUT, 'Inbox'
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @imap, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @imap
RETURN
END
-- The NumMessages property contains the number of messages in the selected mailbox.
DECLARE @numMessages int
EXEC sp_OAGetProperty @imap, 'NumMessages', @numMessages OUT
IF @numMessages = 0
BEGIN
PRINT 'No messages exist in the Inbox.'
EXEC @hr = sp_OADestroy @imap
RETURN
END
DECLARE @sbMime int
EXEC @hr = sp_OACreate 'Chilkat.StringBuilder', @sbMime OUT
DECLARE @seqNum int
SELECT @seqNum = 1
WHILE @seqNum <= @numMessages
BEGIN
EXEC sp_OAMethod @sbMime, 'Clear', NULL
EXEC sp_OAMethod @imap, 'FetchSingleAsMimeSb', @success OUT, @seqNum, 0, @sbMime
IF @success = 0
BEGIN
EXEC sp_OAGetProperty @imap, 'LastErrorText', @sTmp0 OUT
PRINT @sTmp0
EXEC @hr = sp_OADestroy @imap
EXEC @hr = sp_OADestroy @sbMime
RETURN
END
-- The MIME source of the downloaded email is contained in sbMime.
SELECT @seqNum = @seqNum + 1
END
-- Disconnect from the IMAP server.
EXEC sp_OAMethod @imap, 'Disconnect', @success OUT
EXEC @hr = sp_OADestroy @imap
EXEC @hr = sp_OADestroy @sbMime
END
GO