MSSQL mail send html 문서 형식 보내기

MSSQL mail send 기능을 사용하면 데이터베이스 내용을 토대로 메일을 발송할 수 있습니다.

이 글에서는 단순 텍스트가 아닌 html 문서로 만들어 발송하는 방법과 css 적용 문제 해결 방법에 관한 글입니다.

MSSQL mail send 기능

MSSQL 기능 중 데이터베이스 메일 기능을 사용하면 이메일 발송이 가능합니다.

사전에 데이터베이스 메일 구성이 필요하며, SQL Server 에이전트가 실행 중이어야 합니다.

이 글에서는 데이터베이스 메일 구성 이후 프로시저를 활용한 메일 발송에 대해 알아보겠습니다.

EXEC msdb.dbo.sp_send_dbmail  
    @profile_name = '프로필이름',  
    @recipients = '받는사람이메일',  
    @copy_recipients = '참조이메일',  
    @blind_copy_recipients = '숨은참조이메일',  
    @subject = '이메일제목',  
    @body = '이메일본문',  
    @body_format = 'HTML | TEXT',  
    @query = '쿼리문',  
    @execute_query_database = '데이터베이스이름',  
    @attach_query_result_as_file = 0 | 1,  
    @query_attachment_filename = '파일명',  
    @query_result_separator = '구분자',  
    @query_result_no_padding = 0 | 1,  
    @query_result_width = 값,  
    @file_attachments = '파일경로',  
    @importance = 'Low | Normal | High',  
    @sensitivity = 'Normal | Personal | Private | Confidential'

msdb에 포함된 sp_send_dbmail 프로시저를 이용하여 메일을 발송할 수 있으며, 위는 모든 파라미터에 대한 정보를 표시한 것이고 아래의 필수적인 파라미터만 사용하여 간단하게 보낼 수도 있습니다.

EXEC msdb.dbo.sp_send_dbmail  
    @profile_name = 'MyMailProfile',  
    @recipients = 'user@example.com',  
    @subject = 'SQL Server 알림',  
    @body = 'DB 작업이 완료되었습니다.',  
    @body_format = 'TEXT';

MSSQL mail send HTML 문서

프로시저 파라미터의 @body_format 부분을 html로 하게 되면 @body를 통해 메일 본문을 html 형식의 문서로 발송할 수 있습니다.

본문에 html 태그로 작성하여 발송하면 규격화 및 디자인을 추가할 수 있기 때문에 쿼리 결과를 그리드 형식으로 보낼 수도 있습니다.

DECLARE @HTMLBODY VARCHAR(MAX)  -- HTML 문서(메일 본문)
DECLARE @MAILSUBJECT VARCHAR(MAX)  -- 메일 제목

SET @MAILSUBJECT = '매출 실적'
SET @HTMLBODY = '
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>매출 실적</title>
    <style>
        table {
            border-collapse: collapse;
            width: 50%;
            margin: 20px auto;
        }
        th, td {
            border: 1px solid #ddd;
            text-align: center;
            padding: 8px;
        }
        th {
            background-color: #f4f4f4;
        }
        tr:nth-child(even) {
            background-color: #f9f9f9;
        }
    </style>
</head>
<body>
    <h1 style="text-align: center;">매출 실적</h1>
    <table>
        <thead>
            <tr>
                <th>항목</th>
                <th>저번 달</th>
                <th>이번 달</th>
                <th>증감율</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>매출 실적 (원)</td>
                <td>10,000,000</td>
                <td>12,000,000</td>
                <td>+20%</td>
            </tr>
        </tbody>
    </table>
</body>
</html>
'
  EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'SQL_Mail_Profile',          -- 메일 프로필 이름
    @RECIPIENTS = 'master@info-gaeway.com',     -- 수신자 이메일
    @SUBJECT = @MAILSUBJECT,  -- 메일 제목
    @BODY = @HTMLBODY,  -- 메일 본문
    @body_format = 'HTML';  -- 메일 본문 형식

데이터베이스 메일 HTML 문서 css 적용

이렇게 발송된 메일을 각각 아웃룩과 사용하고 있는 하이웍스 그룹웨어 웹 메일에서 확인해 봤습니다.

아웃룩에서는 CSS가 적용된 디자인이 보이는데, 웹 메일에서 확인해 보면 아웃룩과 달리 테이블 css 요소가 적용이 되지 않는 것을 발견했습니다.

MSSQL-mail-send-아웃룩-vert
아웃룩에서는 css가 적용된 반면 웹 메일에서는 적용이 안된 모습

웹 메일 그룹웨어 플랫폼마다 다를 수 있으나, 보안상의 이유로 html 메일에서 script 태그 및 style 태그는 차단되는 경우가 있어, html 문서 작성 시 css는 style 태그에 지정하지 말고 html 태그 안에 인라인으로 적용해 주면 웹 메일에서도 css가 적용되어 확인할 수 있습니다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>매출 실적</title>
</head>
<body>
    <h1 style="text-align: center;">매출 실적</h1>
    <table style="border-collapse: collapse; width: 50%; margin: 20px auto;">
        <thead>
            <tr>
                <th style="border: 1px solid #ddd; text-align: center; padding: 8px; background-color: #f4f4f4;">항목</th>
                <th style="border: 1px solid #ddd; text-align: center; padding: 8px; background-color: #f4f4f4;">저번 달</th>
                <th style="border: 1px solid #ddd; text-align: center; padding: 8px; background-color: #f4f4f4;">이번 달</th>
                <th style="border: 1px solid #ddd; text-align: center; padding: 8px; background-color: #f4f4f4;">증감율</th>
            </tr>
        </thead>
        <tbody>
            <tr style="background-color: #f9f9f9;">
                <td style="border: 1px solid #ddd; text-align: center; padding: 8px;">매출 실적 (원)</td>
                <td style="border: 1px solid #ddd; text-align: center; padding: 8px;">10,000,000</td>
                <td style="border: 1px solid #ddd; text-align: center; padding: 8px;">12,000,000</td>
                <td style="border: 1px solid #ddd; text-align: center; padding: 8px;">+20%</td>
            </tr>
        </tbody>
    </table>
</body>
</html>

혹시 인라인 작성 후에도 적용이 되지 않을 경우, 아래 코드를 참고하여 head 태그 안에 meta 태그로 html 문서임을 나타내는 코드를 추가해 보시기 바랍니다.

MSSQL-mail-send-css-인라인-적용
css 스타일을 html 태그 인라인으로 적용 후 웹 메일에서도 적용된 모습
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

답글 남기기