The only way I could accomplish this was by temporarily exporting the file to local folder and then attach it to the email. Set @Pid=CAST(@ID as.
![]() By: Tim Ford | Updated: 2008-02-20 | Comments (19) | Related: 1 | 2 | 3 | More >Database Mail![]() Problem
One of the most welcome SQL Server 2005 enhancements over its predecessors is Database Mail. Database Mail is built on the Simple Mail Transfer Protocol (SMTP) as compared to SQL Server 2000 Mail which used a buggy and temperamental MAPI client causing significant frustration. Just like with everything else, every enhancement comes with its own learning curve. If you're new to Database Mail in SQL 2005 it is quite easy to get lost somewhere between the Surface Area Configuration Tool (where Database Mail is enabled) and SQL Server Management Studio (where the settings for Database Mail configured). I'll show you the basics of getting Database Mail configured for basic use in Management Studio and then show you a much quicker method via T-SQL. You'll be able to get Database Mail running in under a minute once this script is customized for your environment. At the end of this tip we will review a few of the most common stored procedures associated with Database Mail and compare them to their SQL Mail stored procedure equivalents.
Solution
Before SQL 2005 even had an official name and we were all referring to the product as Yukon, we've been told by Microsoft that the release would be 'Secure by Default'. What does that mean exactly? Well, what it means is that the base installation's configuration settings are as restrictive as possible. You must explicitly enable features and services that provide additional functionality for SQL Server 2005, yet may expose it to unwanted intrusion. The tool Microsoft has provided for this task is the SQL Server Surface Area Configuration. This tip will focus on one of the features that is enabled via this tool: Database Mail.
SQL Server 2005 Surface Area Configuration - Database Mail
Step 1 - The enabling of this feature is simple enough; launch SQL Server Surface Area Configuration from your Start Menu:
Step 2 - Select Surface Area Configuration for Features:
Step 3 - Expand Database Engine, select Database Mail, and check the Enable Database Mail Stored Procedures checkbox.
SQL Server 2005 Management Studio - Database Mail Configuration
At this point you've simply enabled the 25 system stored procedures that are used to perform email operations in SQL 2005 under the auspices of Database Mail. It is now necessary to configure Database Mail for your environment. For that we must move onto more familiar territory: SQL Server management Studio (SSMS).
Database Mail configuration in SQL Server 2005 Management Studio Step 1 - After launching SSMS, you'll need to connect to the server for which you wish to configure Database Mail. Expand the Management folder, then right-click Database Mail and select Configure Database Mail.
Step 2 - Doing so will launch the Configure Database Mail Wizard. It may look a little confusing at first, but once we step through it the script at the end of this tip will make more sense.
Step 3 - Since we're setting up Database Mail for the first time, select the Setup option as recommended.
Step 4 - The first step is to set up an email profile to be used with mail being sent from your SQL Server 2005 instance on this screen you will be required to create a profile name, description, and then assign an SMTP account to the profile.
Step 5 - Click the Add button to assign an SMTP account to the profile you're creating. You may need to work with your Server Technicians and/or Security Teams to collect some of the information you'll need. It's best to have this ahead of time so as not to hold up the process of configuring Database Mail. You will need the account name, description, email address (both incoming and outgoing), display name, and SMTP server name for this account. Be sure to confirm the port number with your Server Technicians as well. Typically, the default of port 25 will work. Select how you want to authenticate to the SMTP server and then click OK to proceed.
Step 6 - You will notice that the account information is now listed. You can set up multiple accounts for the Database Mail profile to allow for failover if you so choose. Click Next to continue onto setting up security for the Database Mail profile. I've already taken the liberty of setting this up as a Public Profile. This means that all users of the SQL instance will have access to this Database Mail profile. You have the option of creating Private Profiles that are only accessible to certain users of the instance. In our environment we have a default Database Mail profile that is used across all SQL instances. Your environment may differ. A Future tip will outline creation and use of Private Database Mail Profiles.
Step 7 - Once your form looks similar to this click Next to proceed to setting up your Database Mail system parameters, that form will look something like the one below. I make no suggestions here. You need to configure these settings to best-suit your environment. In our environment I tend to allow for up to 5 retry attempts, but other than that I leave the defaults unchanged.
Step 8 - It is finally time to finish up with the wizard. Click Next for a summary of all the configuration settings you've made. Once you've reviewed them you can proceed with running the underlying stored procedures that create .
Database Mail T-SQL Commands
Congratulations, at this point you're now able to utilize Database Mail in the same manner as you utilized SQL Mail in previous versions of Microsoft SQL Server. However, you may have noticed that stepping through the wizard was a little time-consuming. I would rather script-out repetitive tasks rather than step through a wizard. If you're like me, you support more than a single instance of Microsoft SQL Server with more instances coming online all the time. That is why I maintain a SQL Server Solution that contains a listing of approximately a dozen scripts that I can run immediately after I install SQL Server 2005 and run through the Surface Area Configuration tool. The last script I run executes four Database Mail stored procedures (enabled during our visit to the Surface Area Configuration tool) that cumulatively create the default profile I use across all my SQL Server instances, then sets up the associated account, security, parameters for that profile.
SQL Server 2005 Database Mail Configuration Script
This is a simple process, much more simple than the wizard. First, you pass the profile name and description into the dbo.sysmail_add_profile_sp system stored procedure to create the profile. The next stored procedure, dbo.sysmail_add_account_sp creates the account that you'll assign to the profile. The third system stored procedure you'll execute is dbo.sysmail_add_profileaccount_sp; assigning the account to the profile. Finally, execute dbo.sysmail_add_principalprofile_sp to set the account priority and to assign the prodile to the DBMailUsers role on the SQL Server instance. The SELECT statements that close out the statement block will confirm your settings executed successfully. Twenty-eight lines of code and 2 seconds versus stepping through nine screens in the Configure Database Mail wizard. You be the judge.
Additional Important Database Mail Stored Procedures
The first thing you'll notice when comparing SQL Mail versus Database Mail stored procedures is the sheer increase in available stored procedures that are now associated with the de-facto messaging component for SQL Server 2005. These stored procedures give you unprecedented control over mail accounts, logs, tables, queues, and of course the composition and sending of query results to recipients. Previously, when using SQL Mail, you had access to only a single stored procedure (sp_processmail, which in-turn called three different extended stored procedures and was declared a security risk by Microsoft Books Online) and a half-dozen extended stored procedures that had limited control over the SQL Mail inbox in addition to composing and sending query results to recipients. By far, the most-important query for Database Mail is sp_send_dbmail. This stored procedure affords you the ability to create a mail document, embed or attach query results, attach additional files, include message text, set a myriad of mail document properties and then send the mail message. The SQL Mail counterpart to sp_send_dbmail is xp_sendmail. All functionality from xp_sendmail exists in sp_send_dbmail, with some important differences as they relate to parameter data types. The parameters for both mail message and query text are limited in SQL Mail to 8000 bytes each; sp_send_dbmail is able to bypass that limitation by making use of the nvarchar(max) data type that was first released in SQL Server 2005. Additionally, Boolean parameters have been replaced by bit data types. I've presented the syntax for each stored procedure and also summarized their differences below:
SQL Mail (Microsoft SQL 2000 and earlier)Database Mail (Microsoft SQL 2005)Parameter Comparisons
Below outlines the parameter comparisons between xp_sendmail and sp_send_mail with some additional commentary:
Next Steps
Last Updated: 2008-02-20 About the author
Tim Ford is a Senior Database Administrator with MindBody.
View all my tips
Related Resources -->
APLICA-SE A: SQL Server Banco de Dados SQL do Azure (somente a Instância Gerenciada) Azure Synapse Analytics (SQL DW) Parallel Data Warehouse APPLIES TO: SQL Server Azure SQL Database (Managed Instance only) Azure Synapse Analytics (SQL DW) Parallel Data Warehouse
Envia uma mensagem de email aos destinatários especificados.Sends an e-mail message to the specified recipients.A mensagem pode incluir um conjunto de resultados da consulta, anexos de arquivo ou ambos.The message may include a query result set, file attachments, or both.Quando o email é colocado com êxito na fila de Database Mail, sp_send_dbmail retorna o mailitem_id da mensagem.When mail is successfully placed in the Database Mail queue, sp_send_dbmail returns the mailitem_id of the message.Esse procedimento armazenado está no banco de dados msdb .This stored procedure is in the msdb database.
Convenções da sintaxe Transact-SQLTransact-SQL Syntax Conventions
SintaxeSyntaxArgumentosArguments[ @profile_name = ] 'profile_name' à o nome do perfil do qual enviar a mensagem.[ @profile_name = ] 'profile_name' Is the name of the profile to send the message from.O profile_name é do tipo sysname, com um padrão de NULL.The profile_name is of type sysname, with a default of NULL.O profile_name deve ser o nome de um perfil de Database Mail existente.The profile_name must be the name of an existing Database Mail profile.Quando nenhum profile_name for especificado, sp_send_dbmail usará o perfil privado padrão para o usuário atual.When no profile_name is specified, sp_send_dbmail uses the default private profile for the current user.Se o usuário não tiver um perfil privado padrão, sp_send_dbmail usará o perfil público padrão para o banco de dados msdb .If the user does not have a default private profile, sp_send_dbmail uses the default public profile for the msdb database.Se o usuário não tiver um perfil privado padrão e não houver um perfil público padrão para o banco de dados, ** @profile_name** deverá ser especificado.If the user does not have a default private profile and there is no default public profile for the database, @profile_name must be specified.
[ @recipients = ] 'recipients' à uma lista delimitada por ponto-e-vÃrgula de endereços de email para os quais enviar a mensagem.[ @recipients = ] 'recipients' Is a semicolon-delimited list of e-mail addresses to send the message to.A lista de destinatários é do tipo varchar (max).The recipients list is of type varchar(max).Embora esse parâmetro seja opcional, pelo menos um dos ** @destinatários**, ** @copy_recipients**ou ** @blind_copy_recipients** deve ser especificado ou sp_send_dbmail retorna um erro.Although this parameter is optional, at least one of @recipients, @copy_recipients, or @blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
[ @copy_recipients = ] 'copy_recipients' à uma lista delimitada por ponto-e-vÃrgula de endereços de email para copiar a mensagem para.[ @copy_recipients = ] 'copy_recipients' Is a semicolon-delimited list of e-mail addresses to carbon copy the message to.A lista de cópias de destinatários é do tipo varchar (max).The copy recipients list is of type varchar(max).Embora esse parâmetro seja opcional, pelo menos um dos ** @destinatários**, ** @copy_recipients**ou ** @blind_copy_recipients** deve ser especificado ou sp_send_dbmail retorna um erro.Although this parameter is optional, at least one of @recipients, @copy_recipients, or @blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
[ @blind_copy_recipients = ] 'blind_copy_recipients' à uma lista delimitada por ponto-e-vÃrgula de endereços de email a serem ocultados na cópia da mensagem.[ @blind_copy_recipients = ] 'blind_copy_recipients' Is a semicolon-delimited list of e-mail addresses to blind carbon copy the message to.A lista de destinatários de cópia oculta é do tipo varchar (max).The blind copy recipients list is of type varchar(max).Embora esse parâmetro seja opcional, pelo menos um dos ** @destinatários**, ** @copy_recipients**ou ** @blind_copy_recipients** deve ser especificado ou sp_send_dbmail retorna um erro.Although this parameter is optional, at least one of @recipients, @copy_recipients, or @blind_copy_recipients must be specified, or sp_send_dbmail returns an error.
[ @from_address = ] 'from_address' à o valor do ' endereço remetente ' da mensagem de email.[ @from_address = ] 'from_address' Is the value of the 'from address' of the email message.Esse é um parâmetro opcional usado para substituir as configurações no perfil de email.This is an optional parameter used to override the settings in the mail profile.Esse parâmetro é do tipo varchar (max).This parameter is of type varchar(MAX).As configurações de segurança de SMTP determinarão se essas substituições serão aceitas.SMTP security settings determine if these overrides are accepted.Se nenhum parâmetro for especificado, o padrão será NULL.If no parameter is specified, the default is NULL.
[ @reply_to = ] 'reply_to' à o valor do ' responder para endereço ' da mensagem de email.[ @reply_to = ] 'reply_to' Is the value of the 'reply to address' of the email message.Aceita apenas um endereço de email como um valor válido.It accepts only one email address as a valid value.Esse é um parâmetro opcional usado para substituir as configurações no perfil de email.This is an optional parameter used to override the settings in the mail profile.Esse parâmetro é do tipo varchar (max).This parameter is of type varchar(MAX).As configurações de segurança de SMTP determinarão se essas substituições serão aceitas.SMTP security settings determine if these overrides are accepted.Se nenhum parâmetro for especificado, o padrão será NULL.If no parameter is specified, the default is NULL.
[ @subject = ] 'subject' à o assunto da mensagem de email.[ @subject = ] 'subject' Is the subject of the e-mail message.O assunto é do tipo nvarchar (255).The subject is of type nvarchar(255).Se nenhum assunto for especificado, o padrão será 'SQL Server Message'.If no subject is specified, the default is 'SQL Server Message'.
[ @body = ] 'body' à o corpo da mensagem de email.[ @body = ] 'body' Is the body of the e-mail message.O corpo da mensagem é do tipo nvarchar (max), com um padrão de NULL.The message body is of type nvarchar(max), with a default of NULL.
[ @body_format = ] 'body_format' à o formato do corpo da mensagem.[ @body_format = ] 'body_format' Is the format of the message body.O parâmetro é do tipo varchar (20), com um padrão de NULL.The parameter is of type varchar(20), with a default of NULL.Quando especificado, os cabeçalhos da mensagem de saÃda são definidos para indicar que o corpo da mensagem tem o formato especificado.When specified, the headers of the outgoing message are set to indicate that the message body has the specified format.O parâmetro pode conter um dos seguintes valores:The parameter may contain one of the following values:
Assume TEXT como padrão.Defaults to TEXT.
[ @importance = ] 'importance' à a importância da mensagem.[ @importance = ] 'importance' Is the importance of the message.O parâmetro é do tipo varchar (6).The parameter is of type varchar(6).O parâmetro pode conter um dos seguintes valores:The parameter may contain one of the following values:
Assume Normal como padrão.Defaults to Normal.
[ @sensitivity = ] 'sensitivity' à a sensibilidade da mensagem.[ @sensitivity = ] 'sensitivity' Is the sensitivity of the message.O parâmetro é do tipo varchar (12).The parameter is of type varchar(12).O parâmetro pode conter um dos seguintes valores:The parameter may contain one of the following values:
Assume Normal como padrão.Defaults to Normal.
[ @file_attachments = ] 'file_attachments' à uma lista delimitada por ponto-e-vÃrgula de nomes de arquivos a serem anexados à mensagem de email.[ @file_attachments = ] 'file_attachments' Is a semicolon-delimited list of file names to attach to the e-mail message.Os arquivos da lista devem ser especificados como caminhos absolutos.Files in the list must be specified as absolute paths.A lista de anexos é do tipo nvarchar (max).The attachments list is of type nvarchar(max).Por padrão, o Database Mail limita os anexos de arquivo a 1 MB por arquivo.By default, Database Mail limits file attachments to 1 MB per file.
Importante
Esse parâmetro não está disponÃvel no Azure SQL Instância Gerenciada porque ele não pode acessar o sistema de arquivos local.This parameter is not available in Azure SQL Managed Instance because it cannot access local file system.
[ @query = ] 'query' à uma consulta a ser executada.[ @query = ] 'query' Is a query to execute.Os resultados da consulta podem ser anexados a um arquivo ou incluÃdos no corpo da mensagem de email.The results of the query can be attached as a file, or included in the body of the e-mail message.A consulta é do tipo nvarchar (max) e pode conter quaisquer instruções válidas Transact-SQLTransact-SQL .The query is of type nvarchar(max), and can contain any valid Transact-SQLTransact-SQL statements.Observe que a consulta é executada em uma sessão separada, portanto, as variáveis locais no script que chamam sp_send_dbmail não estão disponÃveis para a consulta.Note that the query is executed in a separate session, so local variables in the script calling sp_send_dbmail are not available to the query.
[ @execute_query_database = ] 'execute_query_database' à o contexto de banco de dados no qual o procedimento armazenado executa a consulta.[ @execute_query_database = ] 'execute_query_database' Is the database context within which the stored procedure runs the query.O parâmetro é do tipo sysname, com um padrão do banco de dados atual.The parameter is of type sysname, with a default of the current database.Esse parâmetro só será aplicável se ** @a consulta** for especificada.This parameter is only applicable if @query is specified.
[ @attach_query_result_as_file = ] attach_query_result_as_file Especifica se o conjunto de resultados da consulta é retornado como um arquivo anexado.[ @attach_query_result_as_file = ] attach_query_result_as_file Specifies whether the result set of the query is returned as an attached file.attach_query_result_as_file é do tipo bit, com um padrão de 0.attach_query_result_as_file is of type bit, with a default of 0.
Quando o valor for 0, os resultados da consulta serão incluÃdos no corpo da mensagem de email, após o conteúdo do parâmetro ** @Body** .When the value is 0, the query results are included in the body of the e-mail message, after the contents of the @body parameter.Quando o valor é 1, os resultados são retornados como um anexo.When the value is 1, the results are returned as an attachment.Esse parâmetro só será aplicável se ** @a consulta** for especificada.This parameter is only applicable if @query is specified.
[ @query_attachment_filename = ] query_attachment_filename Especifica o nome do arquivo a ser usado para o conjunto de resultados do anexo da consulta.[ @query_attachment_filename = ] query_attachment_filename Specifies the file name to use for the result set of the query attachment.query_attachment_filename é do tipo nvarchar (255), com um padrão de NULL.query_attachment_filename is of type nvarchar(255), with a default of NULL.Esse parâmetro é ignorado quando attach_query_result é 0.This parameter is ignored when attach_query_result is 0.Quando attach_query_result é 1 e esse parâmetro é nulo, Database Mail cria um nome de arquivo arbitrário.When attach_query_result is 1 and this parameter is NULL, Database Mail creates an arbitrary filename.
[ @query_result_header = ] query_result_header Especifica se os resultados da consulta incluem cabeçalhos de coluna.[ @query_result_header = ] query_result_header Specifies whether the query results include column headers.O valor de query_result_header é do tipo bit.The query_result_header value is of type bit.Quando o valor é 1, os resultados da consulta contêm cabeçalhos de coluna.When the value is 1, query results contain column headers.Quando o valor é 0, resultados da consulta não incluem cabeçalhos de coluna.When the value is 0, query results do not include column headers.O padrão desse parâmetro é 1.This parameter defaults to 1.Esse parâmetro só será aplicável se ** @a consulta** for especificada.This parameter is only applicable if @query is specified.
Observação
O erro a seguir pode ocorrer ao @definir query_result_header como 0 e @definir query_no_truncate como 1:The following error may occur when setting @query_result_header to 0 and setting @query_no_truncate to 1:
MSG 22050, nÃvel 16, estado 1, linha 12: falha ao inicializar a biblioteca sqlcmd com o número de erro-2147024809.Msg 22050, Level 16, State 1, Line 12: Failed to initialize sqlcmd library with error number -2147024809. [ @query_result_width = ] query_result_width à a largura da linha, em caracteres, a ser usada para formatar os resultados da consulta.[ @query_result_width = ] query_result_width Is the line width, in characters, to use for formatting the results of the query.O query_result_width é do tipo int, com um padrão de 256.The query_result_width is of type int, with a default of 256.O valor fornecido deve estar entre 10 e 32767.The value provided must be between 10 and 32767.Esse parâmetro só será aplicável se ** @a consulta** for especificada.This parameter is only applicable if @query is specified.
[ @query_result_separator = ] 'query_result_separator' à o caractere usado para separar colunas na saÃda da consulta.[ @query_result_separator = ] 'query_result_separator' Is the character used to separate columns in the query output.O separador é do tipo Char (1).The separator is of type char(1).Usa como padrão ' ' (espaço).Defaults to ' ' (space).
[ @exclude_query_output = ] exclude_query_output Especifica se a saÃda da execução da consulta deve ser retornada na mensagem de email.[ @exclude_query_output = ] exclude_query_output Specifies whether to return the output of the query execution in the e-mail message.exclude_query_output é bit, com um padrão de 0.exclude_query_output is bit, with a default of 0.Quando esse parâmetro é 0, a execução do procedimento armazenado sp_send_dbmail imprime a mensagem retornada como resultado da execução da consulta no console.When this parameter is 0, the execution of the sp_send_dbmail stored procedure prints the message returned as the result of the query execution on the console.Quando esse parâmetro é 1, a execução do procedimento armazenado sp_send_dbmail não imprime nenhuma das mensagens de execução de consulta no console.When this parameter is 1, the execution of the sp_send_dbmail stored procedure does not print any of the query execution messages on the console.
[ @append_query_error = ] append_query_error Especifica se o email deve ser enviado quando um erro retorna da consulta especificada no argumento de ** @consulta** .[ @append_query_error = ] append_query_error Specifies whether to send the e-mail when an error returns from the query specified in the @query argument.append_query_error é bit, com um padrão de 0.append_query_error is bit, with a default of 0.Quando esse parâmetro é 1, o Database Mail envia a mensagem de email e inclui a mensagem de erro de consulta no corpo da mensagem de email.When this parameter is 1, Database Mail sends the e-mail message and includes the query error message in the body of the e-mail message.Quando esse parâmetro for 0, Database Mail não enviará a mensagem de email e sp_send_dbmail terminará com o código de retorno 1, indicando falha.When this parameter is 0, Database Mail does not send the e-mail message, and sp_send_dbmail ends with return code 1, indicating failure.
[ @query_no_truncate = ] query_no_truncate Especifica se a consulta deve ser executada com a opção que evita o truncamento de tipos de dados de comprimento variável grande (varchar (max), nvarchar (max), varbinary (max), XML, Text, ntext, Imagee tipos de dados definidos pelo usuário).[ @query_no_truncate = ] query_no_truncate Specifies whether to execute the query with the option that avoids truncation of large variable length data types (varchar(max), nvarchar(max), varbinary(max), xml, text, ntext, image, and user-defined data types).Quando definido, os resultados da consulta não incluem cabeçalhos de coluna.When set, query results do not include column headers.O valor de query_no_truncate é do tipo bit.The query_no_truncate value is of type bit.Quando o valor é 0 ou não especificado, as colunas na consulta são truncadas com 256 caracteres.When the value is 0 or not specified, columns in the query truncate to 256 characters.Quando o valor é 1, as colunas da consulta não são truncadas.When the value is 1, columns in the query are not truncated.Esse parâmetro assume 0 como padrão.This parameter defaults to 0.
Observação
Quando usado com grandes quantidades de dados, a @opção query_no_truncate consome recursos adicionais e pode reduzir o desempenho do servidor.When used with large amounts of data, the @query_no_truncate option consumes additional resources and can slow server performance.
[ @query_result_no_padding ] @query_result_no_padding O tipo é bit.[ @query_result_no_padding ] @query_result_no_padding The type is bit.O padrão é 0.The default is 0.Quando você define como 1, os resultados da consulta não são preenchidos, possivelmente reduzindo o tamanho do arquivo. Se você definir @query_result_no_padding como 1 e definir o @parâmetro query_result_width, o @parâmetro query_result_no_padding substituirá o @parâmetro query_result_width.When you set to 1, the query results are not padded, possibly reducing the file size.If you set @query_result_no_padding to 1 and you set the @query_result_width parameter, the @query_result_no_padding parameter overwrites the @query_result_width parameter.
Nesse caso, não ocorre nenhum erro.In this case no error occurs.
Observação
O erro a seguir pode ocorrer ao @definir query_result_no_padding como 1 e fornecer um parâmetro @para query_no_truncate:The following error may occur when setting @query_result_no_padding to 1 and providing a parameter for @query_no_truncate:
MSG 22050, nÃvel 16, estado 1, linha 0: falha ao executar a consulta porque as @opções query_result_no_append @e query_no_truncate são mutuamente exclusivas.Msg 22050, Level 16, State 1, Line 0: Failed to execute the query because the @query_result_no_append and @query_no_truncate options are mutually exclusive.
Se você definir o @query_result_no_padding como 1 e definir o @parâmetro query_no_truncate, um erro será gerado.If you set the @query_result_no_padding to 1 and you set the @query_no_truncate parameter, an error is raised.
[ @mailitem_id = ] mailitem_id [ OUTPUT ] O parâmetro output opcional retorna o mailitem_id da mensagem.[ @mailitem_id = ] mailitem_id [ OUTPUT ] Optional output parameter returns the mailitem_id of the message.O mailitem_id é do tipo int.The mailitem_id is of type int.
Valores do código de retornoReturn Code Values
Um código de retorno de 0 significa êxito.A return code of 0 means success.Qualquer outro valor significa falha.Any other value means failure.O código de erro para a instrução que falhou é armazenado na @ @variável de erro.The error code for the statement that failed is stored in the @@ERROR variable.
Conjuntos de resultadosResult Sets
Com êxito, retorna a mensagem que 'Email enfileirado'.On success, returns the message 'Mail queued.'
ComentáriosRemarks
Antes de usar, Database Mail deve ser habilitado usando o assistente de configuração do Database Mail ou sp_configure.Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure.
sysmail_stop_sp para Database Mail interrompendo os objetos de Service Broker que o programa externo usa.sysmail_stop_sp stops Database Mail by stopping the Service Broker objects that the external program uses.sp_send_dbmail ainda aceitará email quando Database Mail for interrompido usando sysmail_stop_sp.sp_send_dbmail still accepts mail when Database Mail is stopped using sysmail_stop_sp.Para iniciar Database Mail, use sysmail_start_sp.To start Database Mail, use sysmail_start_sp.
Quando ** @o perfil** não é especificado, sp_send_dbmail usa um perfil padrão.When @profile is not specified, sp_send_dbmail uses a default profile.Se o usuário que envia a mensagem de email tiver um perfil particular padrão, o Database Mail irá utilizá-lo.If the user sending the e-mail message has a default private profile, Database Mail uses that profile.Se o usuário não tiver um perfil particular padrão, sp_send_dbmail usará o perfil público padrão.If the user has no default private profile, sp_send_dbmail uses the default public profile.Se não houver nenhum perfil particular padrão para o usuário e nenhum perfil público padrão, sp_send_dbmail retornará um erro.If there is no default private profile for the user and no default public profile, sp_send_dbmail returns an error.
sp_send_dbmail não dá suporte a mensagens de email sem conteúdo.sp_send_dbmail does not support e-mail messages with no content.Para enviar uma mensagem de ** @** email, você deve especificar pelo menos um corpo, ** @consulta**, ** @file_attachments**ou ** @assunto**.To send an e-mail message, you must specify at least one of @body, @query, @file_attachments, or @subject.Caso contrário, sp_send_dbmail retornará um erro.Otherwise, sp_send_dbmail returns an error.
O Database Mail usa o contexto de segurança do usuário atual do MicrosoftMicrosoft Windows para controlar o acesso a arquivos.Database Mail uses the MicrosoftMicrosoft Windows security context of the current user to control access to files.Portanto, os usuários autenticados com SQL ServerSQL Server autenticação não podem anexar arquivos usando ** @file_attachments**.Therefore, users who are authenticated with SQL ServerSQL Server Authentication cannot attach files using @file_attachments.O Windows não permite que o SQL ServerSQL Server forneça credenciais de um computador remoto para outro.Windows does not allow SQL ServerSQL Server to provide credentials from a remote computer to another remote computer.Portanto, o Database Mail pode não conseguir anexar arquivos de um compartilhamento de rede caso o comando seja executado de um computador diferente daquele em que o SQL ServerSQL Server é executado.Therefore, Database Mail may not be able to attach files from a network share in cases where the command is run from a computer other than the computer that SQL ServerSQL Server runs on.
Se ** @Query** e ** @file_attachments** forem especificados e o arquivo não puder ser encontrado, a consulta ainda será executada, mas o email não será enviado.If both @query and @file_attachments are specified and the file cannot be found, the query is still executed but the e-mail is not sent.
Quando uma consulta é especificada, o conjunto de resultados é formatado como texto em linha.When a query is specified, the result set is formatted as inline text.Dados binários no resultado são enviados em formato hexadecimal.Binary data in the result is sent in hexadecimal format.
Os ** @destinatáriosde parâmetros, ** @copy_recipientse ** @blind_copy_recipients** são listas de endereços de email delimitadas por ponto e vÃrgula.The parameters @recipients, @copy_recipients, and @blind_copy_recipients are semicolon-delimited lists of e-mail addresses.Pelo menos um desses parâmetros deve ser fornecido ou sp_send_dbmail retorna um erro.At least one of these parameters must be provided, or sp_send_dbmail returns an error.
Ao executar sp_send_dbmail sem um contexto de transação, Database Mail inicia e confirma uma transação implÃcita.When executing sp_send_dbmail without a transaction context, Database Mail starts and commits an implicit transaction.Ao executar sp_send_dbmail de dentro de uma transação existente, Database Mail se baseia no usuário para confirmar ou reverter quaisquer alterações.When executing sp_send_dbmail from within an existing transaction, Database Mail relies on the user to either commit or roll back any changes.Ele não inicia uma transação interna.It does not start an inner transaction.
PermissõesPermissions![]()
Permissões de execução para sp_send_dbmail padrão para todos os membros da função de banco de dados DatabaseMailUser no banco de dados msdb .Execute permissions for sp_send_dbmail default to all members of the DatabaseMailUser database role in the msdb database.No entanto, quando o usuário que envia a mensagem não tem permissão para usar o perfil da solicitação, sp_send_dbmail retorna um erro e não envia a mensagem.However, when the user sending the message does not have permission to use the profile for the request, sp_send_dbmail returns an error and does not send the message.
ExemplosExamplesa.A.Enviando uma mensagem de emailSending an e-mail message
Este exemplo envia uma mensagem de email para seu amigo usando o endereço
[email protected] de email.This example sends an e-mail message to your friend using the e-mail address [email protected] .O assunto da mensagem é Automated Success Message .The message has the subject Automated Success Message .O corpo da mensagem contém a sentença 'The stored procedure finished successfully' .The body of the message contains the sentence 'The stored procedure finished successfully' .
B.B.Enviando uma mensagem de email com os resultados de uma consultaSending an e-mail message with the results of a query
Este exemplo envia uma mensagem de email para seu amigo usando o endereço
[email protected] de email.This example sends an e-mail message to your friend using the e-mail address [email protected] .O assunto da mensagem é Work Order Count e executa uma consulta que mostra o número de ordens de trabalho com uma DueDate menor que dois dias, após 30 de abril de 2004.The message has the subject Work Order Count , and executes a query that shows the number of work orders with a DueDate less than two days after April 30, 2004.O Database Mail anexa o resultado como um arquivo de texto.Database Mail attaches the result as a text file.
C.C.Enviando uma mensagem de email HTMLSending an HTML e-mail message
Este exemplo envia uma mensagem de email para seu amigo usando o endereço
[email protected] de email.This example sends an e-mail message to your friend using the e-mail address [email protected] .O assunto da mensagem é Work Order List e contém um documento HTML que mostra o número de ordens de trabalho com uma DueDate menor que dois dias, após 30 de abril de 2004.The message has the subject Work Order List , and contains an HTML document that shows the work orders with a DueDate less than two days after April 30, 2004.O Database Mail envia a mensagem no formato HTML.Database Mail sends the message in HTML format.
Consulte TambémSee Also
Database MailDatabase Mail Database Mail objetos de configuraçãoDatabase Mail Configuration Objects Database Mail procedimentos armazenados (Transact-SQL)Database Mail Stored Procedures (Transact-SQL) sp_addrolemember (Transact-SQL)sp_addrolemember (Transact-SQL) ![]() Comments are closed.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. Archives
December 2022
Categories |