Wednesday, November 30, 2011

SQL Script to send mail with embedded image

Hello All,

If you are working on SQL then most of the time you think that we should get automated mail in our mailbox on any event/alert.

There is Database mail configuration facility is available in SSMS 2008. If this Database mail configuration is  setup with your SMTP profile account then you will get mails automatically.

If you want to send out mail to your team member or friend using this Database mail facility then you will need below code. Which will make your work easier and simpler. This code imbedd image in your mail too which will make your mail more customized and attractive

DECLARE @tableHTML  NVARCHAR(MAX) ;
    SET @tableHTML =
N'<H1>Going home!!!</H1>'+
N'<img src="2.gif" />';

    EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Profilename',  --this is a profile name which is used in Database mail configuration setting
@recipients = 'user@gmail.com',
@subject = 'Sending Mail from SQL Server Test',
@file_attachments =N'C:\Users\Pictures\2.gif',  --this should be location where 2.gif picture is located
@body=@tableHTML,
@body_format = 'HTML';

You have keep 2.gif picture on server c$ or any drive from which you are going to send mail using SQL script.

you can do lot of modification in this content also e.g. you can add friend name after
N'<H1>Going Home!!!</H1> code so that it will look like more customized.

Get back to me if you need any help or any doubt while implementing it.







6 comments:

  1. Hi Amit

    the blog is cool man ...

    one doubt man ..
    say the image is in table how to use it man... ?

    ReplyDelete
  2. ohh good question.
    Its simple..
    DECLARE @tableHTML NVARCHAR(MAX) ;
    SET @tableHTML = write select query to get the image here.

    e.g. select image from imagetable where id=1

    make sure datatype of image column is Nvarchar(max)

    let's try out this one. get back to me if this doesn't work

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. Mr. Amit ghorpade, i am the first memeber of ur blog,give me party

    ReplyDelete
  5. hi,
    images are not open in email. it showing only icon not image

    ReplyDelete
  6. image is opening in outlook desktop application but in gmail and other web mailer its not opening how to deal this problem plzzz help

    ReplyDelete