본문 바로가기

work/mssql

MSSQL Sendmail 설정 (2005 이상)

[1] DataBase 메일 Enable 설정
use master
go
sp_configure 'show advanced options',1
go
reconfigure with override
go
sp_configure 'Database Mail XPs',1
go
--sp_configure 'SQL Mail XPs',0
--go
reconfigure
go


[2] 메일 계정 설정
-- delete from msdb.dbo.sysmail_account;

EXECUTE msdb.dbo.sysmail_add_account_sp
-- 사용자 정의 부분 **********************************************
    @account_name = 'MyMailAccount',
    @description = 'Mail account for Database Mail',
    @email_address = 'gmail@gmail.com',
    @display_name = 'MyAccount',
     @username='gmail@gmail.com',
     @password='password',
    @mailserver_name = 'smtp.gmail.com',
    @mailserver_type='SMTP',
    @port=587,
    @use_default_credentials=0,
    @enable_ssl=1;        -- 보안 연결 여부(0:미사용 1:사용)
   
-- ***************************************************************   

[3] profile 설정
-- @profile_name : 모두 같은 값으로
-- @account_name : [2]에서 설정한 값으로

-- delete msdb.dbo.sysmail_profile;
-- delete msdb.dbo.sysmail_profileaccount;
-- delete msdb.dbo.sysmail_principalprofile;

EXECUTE msdb.dbo.sysmail_add_profile_sp
       @profile_name = 'MyMailProfile',
       @description = 'Profile used for database mail';
      
      
EXECUTE msdb.dbo.sysmail_add_profileaccount_sp
    @profile_name = 'MyMailProfile',
    @account_name = 'MyMailAccount',
    @sequence_number = 1; 
   
EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'MyMailProfile',
    @principal_name = 'public',
    @is_default = 1 ;   
   
[4] send 메일
declare @body1 varchar(100)
set @body1 = 'Server :'+@@servername+ ' My First Database Email '
EXEC msdb.dbo.sp_send_dbmail @recipients='recipient@hanmail.net',
    @subject = 'My Mail Test',
    @body = @body1,
    @body_format = 'HTML',
    @file_attachments='D:\test.pdf';   -- 절대경로. 세미콜론(;)으로 복수의 파일 첨부 가능.

[5] 메일 로그 조회
SELECT * FROM msdb.dbo.sysmail_event_log;


[6] 기타 설정
1. 각 계정을 10번씩 다시 시도하도록 데이터베이스 메일 설정

다음 예에서는 계정에 연결할 수 없는 것으로 간주하기 전에 각 계정을 10번씩 다시 시도하도록 데이터베이스 메일을 설정합니다.

EXECUTE msdb.dbo.sysmail_configure_sp
    'AccountRetryAttempts', '10' ;

2. 최대 첨부 파일 크기를 2MB로 설정

다음 예에서는 최대 첨부 파일 크기를 2MB로 설정합니다.

EXECUTE msdb.dbo.sysmail_configure_sp
    'MaxFileSize', '2097152' ;

출처 : http://www.databasejournal.com/features/mssql/article.php/3626056/Database-Mail-in-SQL-Server-2005.htm
         http://msdn.microsoft.com/ko-kr/library/ms190307.aspx
         http://msdn.microsoft.com/ko-kr/library/ms175862.aspx
         http://sqlblog.com/blogs/jonathan_kehayias/archive/2010/01/25/setting-up-database-mail-to-use-gmail-account-for-presentations.aspx