Friday, August 24, 2012

Get Email Addresses and Send Email SQL

Let say, you have a form to order books and 'Customer' table to save the information with 'Customer Name', 'Email', 'Shipped Date', 'Received' columns.

I want to write an auto email query in SQL and would like to run by SQL agent so that the customer would get an e-mail reminder if they forget to return the books in 3 weeks from the shipped date.
Create Procedure [dbo].[AutoEmail] AS 
BEGIN 
    SET NOCOUNT ON 
            
     DECLARE @EmailList varchar(MAX)
     
     SELECT  @EmailList = COALESCE(@EmailList + ';', '') + Email
        FROM    Customer
            WHERE   (Email IS NOT NULL)
                   AND
                   (received = 0)  'bit value
                   AND
                   (ShippedDate < DATEADD(day, -21, GETDATE()))
                   
       SELECT  @EmailList
            
                
     exec msdb.dbo.sp_send_dbmail
@profile_name = 'Your Profile Name',
        @recipients='abc@hotmail.com',       
        @blind_copy_recipients = @EmailList,
        @subject = 'Books return time reminder',        
        @execute_query_database='Database Name',
        @body = 'Hello, this is a reminder email, please send us back
                           the books which you received 3 weeks ago. If you 
                           have already sent them please disregard this 
                           message.'
End
   
 

No comments:

Post a Comment

Highly Appreciated your comments