Email Queue made simple...
Just a quick task that I completed recent, and wanted to share. I needed to create a Sql Server based email queue. Here is what I did...
1. Create a table that will hold the emails that need to be sent. Watch for wrapping, if any.
CREATE TABLE [EmailQueue] (
[EmailID] [int] IDENTITY (1, 1) NOT NULL ,
[QueueDate] [datetime] NOT NULL CONSTRAINT [DF_EmailQueue_QueueDate] DEFAULT (getdate()),
[SendDate] [datetime] NULL ,
[EmailTo] [nvarchar] (150) NOT NULL CONSTRAINT [DF_EmailQueue_EmailTo] DEFAULT ('youremail@yourserver.com'),
[EmailFrom] [nvarchar] (150) NOT NULL CONSTRAINT [DF_EmailQueue_EmailFrom] DEFAULT ('youremail@yourserver.com'),
[EmailSubject] [nvarchar] (150) NOT NULL CONSTRAINT [DF_EmailQueue_EmailSubject] DEFAULT (N'[Default Subject]'),
[EmailBody] [nvarchar] (3000) NOT NULL ,
[EmailCC] [nvarchar] (150) NULL ,
[EmailBCC] [nvarchar] (150) NULL ,
[EmailPriority] [int] NOT NULL CONSTRAINT [DF_EmailQueue_EmailPriority] DEFAULT (0)
) ON [PRIMARY]
GO
2. Create a job that will send the emails, every 5 minutes.
BEGIN TRANSACTION
DECLARE @JobID BINARY(16)
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0
IF (SELECT COUNT(*) FROM msdb.dbo.syscategories WHERE name = N'[Uncategorized (Local)]') < 1
EXECUTE msdb.dbo.sp_add_category @name = N'[Uncategorized (Local)]'
-- Delete the job with the same name (if it exists)
SELECT @JobID = job_id
FROM msdb.dbo.sysjobs
WHERE (name = N'Send Email Queue')
IF (@JobID IS NOT NULL)
BEGIN
-- Check if the job is a multi-server job
IF (EXISTS (SELECT *
FROM msdb.dbo.sysjobservers
WHERE (job_id = @JobID) AND (server_id <> 0)))
BEGIN
-- There is, so abort the script
RAISERROR (N'Unable to import job ''Send Email Queue'' since there is already a multi-server job with this name.', 16, 1)
GOTO QuitWithRollback
END
ELSE
-- Delete the [local] job
EXECUTE msdb.dbo.sp_delete_job @job_name = N'Send Email Queue'
SELECT @JobID = NULL
END
BEGIN
-- Add the job
EXECUTE @ReturnCode = msdb.dbo.sp_add_job @job_id = @JobID OUTPUT , @job_name = N'Send Email Queue', @owner_login_name = N'sa', @description = N'No description available.', @category_name = N'[Uncategorized (Local)]', @enabled = 1, @notify_level_email = 0, @notify_level_page = 0, @notify_level_netsend = 0, @notify_level_eventlog = 2, @delete_level= 0
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the job steps
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobstep @job_id = @JobID, @step_id = 1, @step_name = N'Run Stored Proc', @command = N'exec [dbo].[SendEmailQueue] ', @database_name = N'master', @server = N'', @database_user_name = N'', @subsystem = N'TSQL', @cmdexec_success_code = 0, @flags = 0, @retry_attempts = 0, @retry_interval = 1, @output_file_name = N'', @on_success_step_id = 0, @on_success_action = 1, @on_fail_step_id = 0, @on_fail_action = 2
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXECUTE @ReturnCode = msdb.dbo.sp_update_job @job_id = @JobID, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the job schedules
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id = @JobID, @name = N'Run the sucker', @enabled = 1, @freq_type = 4, @active_start_date = 20040726, @active_start_time = 0, @freq_interval = 1, @freq_subday_type = 4, @freq_subday_interval = 5, @freq_relative_interval = 0, @freq_recurrence_factor = 0, @active_end_date = 99991231, @active_end_time = 235959
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
-- Add the Target Servers
EXECUTE @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @JobID, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
END
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:
3. Create the Stored Procedure to actually send the emails, which the job above runs every 5 minutes
CREATE procedure [dbo].[SendEmailQueue]
as
Set NoCount on
--make sure we have items to send, if not we dont need to do any of the--
--initial overhead temp table and select--
if exists( select * from EmailQueue where SendDate is null )
begin
--global settings--
Declare @EmailServer nvarchar(10)
--*****CHANGE YOUR MAIL SERVER HERE****--
set @EmailServer = 'MYMAIL SERVER'
--message level variables--
declare @EmailID bigint
declare @QueueDate as datetime
declare @SendDate as datetime
declare @EmailTo as nvarchar(150)
declare @EmailFrom as nvarchar(150)
declare @EmailSubject as nvarchar(150)
declare @EmailBody as nvarchar(3000)
declare @EmailCC as nvarchar(150)
declare @EmailBCC as nvarchar(150)
declare @EmailPriority as int
declare @OriginalEmailID as int
--looping variables--
declare @RowCounter bigint
declare @Max bigint
--create the temp table, mirror the existing queue table--
Declare @EmQ Table (
[EmailID] [int] IDENTITY (1, 1) NOT NULL ,
[OriginalEmailID] [int] NOT NULL ,
[QueueDate] [datetime] NOT NULL ,
[SendDate] [datetime] NULL ,
[EmailTo] [nvarchar] (150) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[EmailFrom] [nvarchar] (150) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[EmailSubject] [nvarchar] (150) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[EmailBody] [nvarchar] (3000) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL ,
[EmailCC] [nvarchar] (150) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[EmailBCC] [nvarchar] (150) COLLATE SQL_Latin1_General_CP1_CI_AS NULL ,
[EmailPriority] [int] NOT NULL
)
--insert the data that we need to send into our temp table--
insert into @Emq
select EmailID as OriginalEmailID, [QueueDate], [SendDate], [EmailTo], [EmailFrom], [EmailSubject],
[EmailBody], [EmailCC], [EmailBCC], [EmailPriority]
from EmailQueue where SendDate is null
--get the max num of records for our loop--
select @Max=count(*) from @Emq
--set our row counter to the first id--
set @RowCounter=1
--loop for each record--
while @RowCounter <= @Max
begin
--grab the individual record based on our record counter--
select @OriginalEmailID=[OriginalEmailID],
@EmailID=[EmailID],
@QueueDate=[QueueDate],
@SendDate=[SendDate],
@EmailTo=[EmailTo],
@EmailFrom=[EmailFrom],
@EmailSubject=[EmailSubject],
@EmailBody=[EmailBody],
@EmailCC=[EmailCC],
@EmailBCC=[EmailBCC],
@EmailPriority=[EmailPriority]
from @Emq where [EmailID]=@RowCounter
--set @EmailBody='[EmailID='+Cast(@OriginalEmailID as nvarchar)+']' + char(10) + char(13) + @EmailBody
--send the email--
Exec master.dbo.xp_smtp_sendmail
@From_Name = @EmailFrom,
@From = @EmailFrom,
@ReplyTo = @EmailFrom,
@To = @EmailTo,
@Subject = @EmailSubject,
@Message =@EmailBody,
@Type = N'text/plain',
@Server = @EmailServer,
@Timeout = 20000
--update the original table based on the original id--
update EmailQueue set SendDate=GetDate() where [EmailID]=@OriginalEmailID
--incrememnt our rowcounter--
set @RowCounter=@RowCounter+1
end
end
GO
Thats it.
In your ASP or .NET code simply create a method that will insert items into the EmailQueue table above. How simple is that? One handy side effect is that you get a log of all emails and the exact time they were queued to be sent, and when they actually did get sent.
Oh btw, the xp_smtp_sendmail component is from http://sqldev.net/xp/xpsmtp.htm
2 Comments
Comments have been disabled for this content.
Jerry Pisk said
Wow. I though simple e-mail queue was writing e-mail messages as files into your MailRoot\Pickup. But using a relational database to send e-mails, why haven't I thought about that earlier :)
webfort said
how would you do this if the body is over 8000 chars?