Many people ask me, "Is it possible to send emails via SQL Server?" or “How do I send emails via SQL Server?”. In this post I will show you how to enable the sending of emails on your SQL Server and how to send and monitor the emails sent.
A feature that is widely used in most systems, is the sending of automatic emails containing notifications, promotions, newsletter and much more. Therefore, it would be very interesting to send these emails directly from our SP's in the database, which can be scheduled by the SQL Server Agent to automate their execution.
Enabling server e-mail sending using T-SQL
View how to enable and configure Database mail via command line (using T-SQL)Enabling SSMS to Send Mail on the Server
View how to configure Database Mail through Management StudioTesting email sending
After configuring Database Mail, we will test if the server is allowing sending normally. To do this, open Object Explorer in Management Studio, navigate to Management> Database Mail and right click on the option “Send Test E-mail…”
Just select the profile you created (In the example, it is the MSSQLServer), fill in the email of the recipient who will receive the test and click on the “Send Test E-mail” button
After submitting the test, a screen will open confirming that the email went to the Database Mail queue.
If you received the test email, just click on the “OK” button. If you haven't received it, click on the “Trobleshooting” button to be taken to the Microsoft help page (https://technet.microsoft.com/pt-br/library/ms187540(v=sql.105))
Sample test email sent by SQL Server Database Mail:
To view the Database Mail log and check if your emails were sent or the error message when trying to send, see more in the “Monitoring email sending” section of this post, below.
Sending Email
Now that we have set up the server, we are ready to send our emails. The sp we will use is sp_send_dbmail, from SQL Server itself, which allows sending text or HTML emails and attachments.
Sending Email in HTML Format
1 2 3 4 5 6 7 |
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'ProfileEnvioEmail', @subject = 'Assunto do E-mail', @body = 'Olá! <strong>Teste</strong>', @body_format = 'html', |
Sending Email Concatenating the Result of a Query to the Message Body
1 2 3 4 5 6 7 8 |
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'ProfileEnvioEmail', @subject = 'Assunto do E-mail', @body = 'Olá! <strong>Teste</strong>', @body_format = 'html', @query = 'SELECT TOP 10 * FROM sys.sysobjects' |
Sending email with query result as attachment (CSV)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'ProfileEnvioEmail', @subject = 'Assunto do E-mail', @body = 'Olá! <strong>Teste</strong>', @body_format = 'html', @query = 'SET NOCOUNT ON; SELECT TOP 10 * FROM sys.sysobjects', @query_attachment_filename = 'anexo.csv', @attach_query_result_as_file = 1, @query_result_header = 1, @query_result_width = 256, @query_result_separator = ';', @query_result_no_padding = 1 |
Emailing 2 Files Attached
1 2 3 4 5 6 7 8 |
EXEC msdb.dbo.sp_send_dbmail @profile_name = 'ProfileEnvioEmail', @subject = 'Assunto do E-mail', @body = 'Olá! <strong>Teste</strong>', @body_format = 'html', @file_attachments = 'C:\Imagem.jpg;C:\Teste.txt' |
Monitoring the sending of emails
Tracking actions is always important in IT. Sending emails is no exception to the rule. As much as it is possible to monitor emails through the mail server, it is not always so fast to be able to validate this, mainly because it is a bit out of scope for the DBA / Scheduler, where this control is usually controlled by the Infrastructure team.
In addition, the mail server keeps logs of all email traffic from all accounts, making it harder to extract this information than simply querying SQL Server catalog tables, which are msdb.dbo.sysmail_mailitems and msdb.dbo.sysmail_event_log.
To make it easier to extract information, I usually create this view, and then just query it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
CREATE VIEW [dbo].[vwMonitoramento_Email] AS SELECT A.send_request_date AS DataEnvio, A.sent_date AS DataEntrega, (CASE WHEN A.sent_status = 0 THEN '0 - Aguardando envio' WHEN A.sent_status = 1 THEN '1 - Enviado' WHEN A.sent_status = 2 THEN '2 - Falhou' WHEN A.sent_status = 3 THEN '3 - Tentando novamente' END) AS Situacao, A.from_address AS Remetente, A.recipients AS Destinatario, A.subject AS Assunto, A.reply_to AS ResponderPara, A.body AS Mensagem, A.body_format AS Formato, A.importance AS Importancia, A.file_attachments AS Anexos, A.send_request_user AS Usuario, B.description AS Erro, B.log_date AS DataFalha FROM msdb.dbo.sysmail_mailitems A WITH(NOLOCK) LEFT JOIN msdb.dbo.sysmail_event_log B WITH(NOLOCK) ON A.mailitem_id = B.mailitem_id |
Another way is by using the SQL Server Management Studio interface.
After selecting the “View Database Mail Log” option, you will see the Database Mail logs screen, in an interface similar to the SQL Server Activity Monitor
Quick Troubleshooting Help (Troubleshooting Database Mail)
If you're having trouble setting up or sending emails, here are some tips that can help you resolve these issues.
Validate access data
This topic may sound silly, but make sure that you correctly entered the SMTP server address, port, user, password, and if you checked the option to use SSL if your SMTP server requests it.
I recently had a big battle with Database Mail to set up one Yahoo account and one hosted on Hostgator. Although the documentation indicates that I should use the 465 (SSL) port in both cases, I have used an email client (Outlook) configured using the 465 port and sent email normally and made a push test using the 465 port on a VBscript successfully, in Database Mail I could only send when I put the 587 (TLS) port. On port 465 the email was not sent at all, probably because it was SSL protocol.
Therefore, consult your email provider's documentation, and if you have problems setting up Database Mail, try using other alternate ports (Providers generally provide two ports for secure SMTP sending, one SSL and one TLS).
Verify that Service Broker is enabled for database msdb (must return 1):
1 |
SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb' |
If the query result is 0, then Service Broker is not active. As a result, sent messages will not be queued by it and sending will not occur. To fix this, run the command below:
1 2 3 4 5 |
USE master; GO ALTER DATABASE msdb SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE; GO |
I have seen several reports of people trying to activate Service Broker in MSDB, but the process crashed or simply did not activate because Broker could not get the locks in MSDB to make the necessary changes. If this happens to you, either drop all MSDB connections or restart the SQL Service service and try again.
Check if Database Mail is running on MSDB database:
1 2 3 4 |
EXECUTE msdb.dbo.sysmail_help_status_sp -- Se não retornar "STARTED", executar o comando abaixo para iniciar o Database Mail: EXECUTE msdb.dbo.sysmail_start_sp |
Check message queue status:
1 |
EXECUTE msdb.dbo.sysmail_help_queue_sp @queue_type = 'Mail' |
Check Database Mail Logs:
1 |
SELECT * FROM msdb.dbo.sysmail_event_log |
Check information about sent items and message errors:
1 |
SELECT * FROM msdb.dbo.sysmail_allitems |
Firewall and Antivirus
Often the sending of E-mail may end up not happening because Firewall / Antivirus blocks the attempt of sending messages by SMTP protocol by the Database Mail process. One way to ensure that the problem is not Firewall is to either release the port used by the connection (usually 25, 465 or 587) or even disable Firewall / Antivirus temporarily just to test if they are blocking the sending or is it some other way. thing.
Send an email test using VBscript script:
Another alternative of checking if the problem is with SQL Server or the server is by trying to send an email in another way. For this you can use the VBscript script below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
Const cdoAnonymous = 0 'Sem autenticação Const cdoBasic = 1 'Autenticação Básica (Base64) Const cdoNTLM = 2 'NTLM Set objMessage = CreateObject("CDO.Message") objMessage.Subject = "Teste de E-mail" objMessage.TextBody = "Teste de Mensagem.." & vbCRLF & "Foi enviada utilizando autenticação Base64 e SSL." objMessage.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 ' Endereço do servidor SMTP objMessage.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "mail.seudominio.com" ' Tipo de autenticação objMessage.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = cdoBasic ' Usuário de autenticação objMessage.Configuration.Fields.Item _ ' Senha de autenticação objMessage.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "sua_senha" ' Porta do SMTP objMessage.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465 ' Utiliza SSL ? objMessage.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = True ' Timeout objMessage.Configuration.Fields.Item _ ("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout") = 60 objMessage.Configuration.Fields.Update objMessage.Send If err.number = 0 then Msgbox "Email enviado com sucesso" |
After you create the script, simply run it from Command Prompt (CMD.exe):
Validate network protocols
Another validation that can be done is whether Named Pipes and TCP / IP network protocols are enabled for your instance. If not, enable and restart your instance's SQL Server service.
Review the SQL Server Service Account
Another point to consider if you are unable to send your emails is to verify that the service account being used to run SQL Server has permissions to access the external network. It does not necessarily have to be a Local Administrator or Domain Admin account, but it does need to have basic network access permissions to be able to send SMTP email.
For more details about service accounts, visit this link.
Install the latest version of Service Pack and Cumulative Updates
Microsoft SQL Server 2016 SP1
Microsoft SQL Server 2016 Latest Cumulative Update
For other editions, visit this link.
Install the latest version of Service Pack and Cumulative Updates
If you are using SQL Server 2016 RTM or SP1, be aware of a common Database Mail issue, which is that you need to install Microsoft .NET Framework 3.5 on your server to prevent your messages from getting stuck in the SQL Server queue. Service Broker and always have unsent status. Otherwise, Database Mail will not work due to a product bug that was fixed in Cumulative Update 2 (Reference Link), reoccurred on the 1 CU1 Service Pack and has been fixed again in the 1 CU2 Service Pack (Reference Link).
Microsoft link to help troubleshoot Database Mail issues
Troubleshooting Database Mail
How to send email mail from sql server, how to send email mail from within sql server
How to send email mail from sql server, how to send email mail from within sql server
Great. Helped me create some alerts. I would like to leave as a suggestion (if it doesn't already exist), a post on how to format the body of the email and the attached query, seeking a better visual presentation, using HTML and CSS, for example.
Hello Dirceu,
Can I send to more than one email in the same query?
in the @recipients parameter, add the recipients you want separated, by ; (semicolon). Example:
EXEC msdb.dbo.sp_send_dbmail
@recipients = '[email protected];[email protected]’,
… (rest of code)
Good afternoon again,
After exhausting the logical options I started for the non logical ones.
We used alias on our servers to make it easier to connect between them, there was an alias with the name of the server itself, I removed this and the emails were sent again normally.
Best Regards,
Jeverson Marcon
Dirceu, good afternoon, all right?
I learned how to configure e-mails in SQL with your posts for a certain time, and used to send e-mails through SQL Server's JOBs normally, however, for reasons of standardization, we changed the name of our servers, and after that the e-mails are no longer sent, if I return the old name of the server, the e-mails will be sent again, but this is not an “acceptable” option, I have already scoured numerous sites, posts, tutorials and the like about related issues but in no way managed to resolve this issue and send emails again.
In this part of your post “EXECUTE msdb.dbo.sysmail_help_queue_sp @queue_type = 'Mail'” I notice that the queue is always “INACTIVE” and emails are in the “0 - Awaiting sending” situation.
Have you ever experienced anything similar / do you know what can be done to solve this problem?
Best Regards,
Jeverson Marcon
Is it possible to resend failed emails?
Great article, it helped me a lot! Thanks.
Good afternoon Dirceu!
thank you very much for the contribution.
when i try to create the email account at the end i get the following message: It is not possible to insert the value NULL in the column “servername”. 'msdb.dbo.sysmail_server' table
following your step by step setting up by SSMS, I checked and the email service is active.
hugs.
Great, DIRCEU knows any SQLMAil features that can be used to send email to everyone in a SELECT Mail table? I tried here but found nothing.
Luciano, good night.
You will have to create a while loop by concatenating the recipients in a string or sending the email individually one by one.
It almost gave ...
The mail could not be sent to the recipients because of the mail server failure. (Sending Mail using Account 4 (2017-01-27T14: 56: 47). Exception Message: Cannot send mail to mail server. (Service not available, closing transmission channel. The server reply was: Cannot connect to SMTP server 64.233.186.108 (64.233.186.108: 587), connect error 10060).
)
Leonardo, there are several things that may be preventing you from sending the email, such as:
- Firewall blocking sending
- Incorrect port settings, SSL in the profile configuration
- Some email providers block the use of SMTP / POP by default, such as Yahoo and Gmail, and you must activate them if you want to use them.
- Internet connection problem
You can try to make a connection test using PowerShell or Telnet to check if it is something on your network that is preventing sending.
This link may also help: https://technet.microsoft.com/pt-br/library/ms187540(v=sql.105).aspx
If you are still having problems after checking all these items, email me through the contact page and I will try to help you.