• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 928
  • Last Modified:

Send email with attachments from stored procedure in MS SQL 2005


I want to create a sql job that will run every night at 3 AM and send emails.

I am able to send emails from the stored procedure using "msdb.dbo.sp_send_dbmail".

                SET @SQL =     ' EXEC msdb.dbo.sp_send_dbmail
                @profile_name = ''' + @Profile_Name + ''',
                @recipients = ''' + @EmailRecipients + ''',
                @body_format = ''html'',
                @subject = ''' + @EmailSubjectToSend + ''',
                @body = ''' + @EmailBodyToSend + ''';'

        EXEC (@SQL)

Now In many cases I want to attach some files (one or more than one) to the email. The attachments are stored in the database itself (in one table. The table structure is:

CREATE TABLE [dbo].[tblCourseAutoEmailAttachments](
    [AttachmentID] [int] IDENTITY(1,1) NOT NULL,
    [CourseAutomatedEmailID] [int] NULL,
    [Attachment] [image] NULL,
    [AttachmentName] [varchar](50) COLLATE SQL_Latin1_General_CP1_CI_AS NULL,
    [AttachmentSize] [int] NULL)

Please let me know how can I send emails with attachments from the stored procedure.

Thanks in advance.

  • 2
1 Solution
You have to use bcp to dump you Attachment to a temp folder on the Hard Drive and then use the database mail to pick that up and send.

This link will help you with the above task

This can be used to send the mail

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Administrator',
    @recipients = 'me@somewhere.com',
    @file_attachments =  'D:\File1.txt;D:\File2.txt'  
    @body = 'Test File Attachments',
    @subject = 'Files Attached';
aplusexpertAuthor Commented:

I will try this solution and let you know.

- Ankit
aplusexpertAuthor Commented:

This is not the solution I was looking for. The suggested solution above creates .txt file only, while I needed to get any type of file which was saved in that table, like .doc, .doc, .xls, .pdf, .jpg, .txt.

I have selected an alternate way to achieve this functionality by creating windows service.


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now