If you are searching for the solution regarding SQL CLR Send an email, you came to the right place. Recently, we need to send notification emails to the customer from SQL Express 2012 Database. However, the latest SQL Server Express editions got deprecated send emails from the SQL server.
Despite little search around turns into great help and, finally, I found a way to get it done is, create a CLR Store procedure and few configurations make you enable to send emails!
First of all, here is the series of steps involved to get it done!
Step 1: Write Block of code in your favorite language C# or VB
C# Block
using System.Net;
using System.Net.Mail;public class StoredProcedure
{
[Microsoft.SqlServer.Server.SqlProcedure()]
public static void spSendMail(string recipients, string subject, string from, string body)
{
using (MailMessage mailMessage = new MailMessage(from, recipients))
{
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
SmtpClient smtpClient = new SmtpClient(“YOUR SMTP SERVER”);
smtpClient.Credentials = new NetworkCredential(“EMAIL ADDRESS”, “PASSWORD”);
smtpClient.Port = YOUR SMTP PORT;
smtpClient.UseDefaultCredentials = false;
smtpClient.EnableSsl = true/false (Depands on your SMTP Setting);
smtpClient.Send(mailMessage);
}
}
}
VB Block
Imports System.Net
Imports System.Net.MailPublic Class StoredProcedure
<Microsoft.SqlServer.Server.SqlProcedure()> _
Public Shared Sub spSendMail(ByVal recipients As String, ByVal subject As String, ByVal from As String, ByVal body As String)
Dim mySmtpClient As SmtpClientUsing myMessage As New MailMessage(from, recipients)
myMessage.Subject = subject
myMessage.Body = bodymyMessage.IsBodyHtml = True
mySmtpClient = New SmtpClient(“YOUR SMTP SERVER”)
mySmtpClient.Credentials = New NetworkCredential(“EMAIL ADDRESS”, “PASSWORD”)
mySmtpClient.Port = YOUR SMTP PORT
mySmtpClient.UseDefaultCredentials = falsemySmtpClient.EnableSsl = true/false (Depands on your SMTP Setting)
mySmtpClient.Send(myMessage)
End Using
End Sub
End Class
Step 2: Compile your code using command line
C# Block
C:\Windows\Microsoft.NET\Framework\v2.0.50727>csc /target:library C:\Users\Administrator\Desktop\SendEmail.cs
VB Block
C:\Windows\Microsoft.NET\Framework\v2.0.50727>vbc /target:library C:\Users\Administrator\Desktop\SendEmail.vb
Step 3: Register your assembly
USE msdb
GOCREATE ASSEMBLY SendEmail FROM ‘C:\SendEmail.dll’
WITH PERMISSION_SET = UNSAFE
GOCREATE PROCEDURE [dbo].[spSendMail]
@recipients [nvarchar](4000),
@subject [nvarchar](4000),
@from [nvarchar](4000),
@body [nvarchar](4000)
WITH EXECUTE AS CALLER
AS
EXTERNAL NAME [SendEmail].[StoredProcedure].[spSendMail]
Step 4: Enable CLR Configuration
sp_configure ‘clr enabled’,1
GO
RECONFIGURE
GO
sp_configure ‘clr enabled’ — make sure it took
GO
Step 5: Drop Assembly / Store Procedure (Optional)
USE msdb
GO
DROP PROCEDURE dbo.spSendMail
GO
DROP ASSEMBLY SendEmail
GO
Finally, to test your CLR Store procedure
EXEC msdb.dbo.spSendMail @recipients = ‘[email protected]’, @subject = ‘Email from SQL Express’, @from = ‘[email protected]’, @body = ‘This is a test email using CLR Assembly’
Source : MSDN
Let me know if you are facing issues regarding SQL CLR Send email. Happy Coding !
If you liked this article, then please subscribe to our Blog for more updates like this. You can also connect me on Twitter, LinkedIn and GitHub.
Hi, Vinay.
I was going through same sequence : but:
VS2010, MS SQL EXPRESS 2005.,
problem statement : 1. I have to generate monthly usage bill of club member in pdf format
2. Send the generated bills to member ID.
3. I have to maintain the status of bills sent/not sent /remarks etc
.
I goggled few things and got to know send by SMTP with attachment i can do, so i have tested basic SMTP with attachment by gmail.com ,. Now i have to go with Database…
I code in C# and .Net : Windows Forms, plz help …. if possible i’ll share code.
thank you
anup.
Hi, i have this error
Msg 6528, Level 16, State 1, Procedure spSendMail, Line 3
Assembly ‘SendEmail’ was not found in the SQL catalog of database ‘msdb’.
Did you register your assembly ?
Please make sure your DLL is available – ‘C:\SendEmail.dll’ ( i.e – this is path of example – you can have it anywhere – just make sure its available !
Let me know if its not working.
Thanks
Vinay
Hello,
I tried exactly the same way. After all things when I try to execute I get the following error.
Msg 6522, Level 16, State 1, Procedure spSendMail, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate “spSendMail”:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
System.Net.Mail.SmtpException:
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, String from)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at StoredProcedure.spSendMail(String recipients, String subject, String from, String body)
.
Can you please help me with this ?
Thanks,
Nuthan Gowda
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
This means – you need to make sure SSL is enable in your settings using which you are sending emails – and proper SMTP port is used.
Thanks
Vinay
Here is the code which I am using. I have enabled SSL and gmail port is 587.
SmtpClient smtpClient = new SmtpClient(“smtp.gmail.com”);
smtpClient.Credentials = new NetworkCredential(“******@gmail.com”, “****”);
smtpClient.Port = 587;
smtpClient.UseDefaultCredentials = false;
smtpClient.EnableSsl = true;
Can you give a try by setting up smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
Make sure you are able to send email by logging in to account – please double check.
Thanks
Vinay
Thanks for the quick reply.
Still I’m getting the same error. I tried to send a mail from the mail ID which I have used in the config file and it is working fine.I’m already using the same mail ID in my web application and there it works fine but through SQL Express it is giving me the above mentioned error and for your reference I have installed both SQL Server 2008 and SQL Express 2012.
Thanks,
Nuthan Gowda
Actually – Proc is successfully calling to your DLL – now things you need to fix is your code that sends email
Please make sure to send test email with that function if its working or not.
Thanks
Vinay
I have tested the C# code and made a following changes for it and it works fine.
Added the Port number while creating the object
SmtpClient smtpClient= new SmtpClient(“smtp.gmail.com”, 587);
and deleted the following line.
smtpClient.Port = 587;
Thanks,
Nuthan Gowda
respected sir ,
i have done code but when i run then this errors come,and also i change port number like 465,25,587 but also same problem .
Msg 6522, Level 16, State 1, Procedure spSendMail, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate “spSendMail”:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
System.Net.Mail.SmtpException:
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at StoredProcedures.spSendMail(String recipients, String subject, String from, String body)
.
Replace your smtp client with port attribute as below.
SmtpClient smtpClient= new SmtpClient(“smtp.gmail.com”, 587);
smtpClient.EnableSsl = true;
That may help you
Thanks
Vinay
Hello Vinay,
I got this error
Msg 6522, Level 16, State 1, Procedure spSendMail, Line 0
A .NET Framework error occurred during execution of user-defined routine or aggregate “spSendMail”:
System.Net.Mail.SmtpException: Server does not support secure connections.
System.Net.Mail.SmtpException:
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at StoredProcedure.spSendMail(String recipients, String subject, String from, String body, String Attachments)
I am alreay SSL is enable in my settings using and also proper SMTP port is used.
But I am using my own smtp server
Thanks & Ragards
Shreyas Jawalikar
Can you please provide your SMTP settings ?
Thanks
Vinay
The mySmtpClient.UseDefaultCredentials = false needs to come before the credentials are defined. This is creating the problem of the secure connection because it resets the credentials.
Then it worked.
R.
Hi, thanks for the tip, I modify, send the code
using System.Net;
using System.Net.Mail;
public class StoreProcedure
{
[Microsoft.SqlServer.Server.SqlProcedure()]
public static void spSendMail(string smtp, string usuario, string password, int port, string recipients, string subject, string from, string body)
{
using (MailMessage mailMessage = new MailMessage(from, recipients))
{
mailMessage.Subject = subject;
mailMessage.Body = body;
mailMessage.IsBodyHtml = true;
using (SmtpClient smtpClient = new SmtpClient(smtp, port))
{
smtpClient.EnableSsl = true;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new NetworkCredential(usuario, password);
smtpClient.Send(mailMessage);
}
}
}
}
Hi,
please help. I recive this error:
Msg 6522, Level 16, State 1, Procedure spSendMail, Line 36
A .NET Framework error occurred during execution of user-defined routine or aggregate “spSendMail”:
System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
System.Net.Mail.SmtpException:
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.MailCommand.Send(SmtpConnection conn, Byte[] command, MailAddress from, Boolean allowUnicode)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at StoredProcedure.spSendMail(String recipients, String subject, String from, String body)
My configuration vb script is next:
mySmtpClient = New SmtpClient(“xxserver”)
mySmtpClient.Credentials = New NetworkCredential(“xxuser”, “xxpassw”,”xxdomain”)
mySmtpClient.Port= 587
mySmtpClient.UseDefaultCredentials = false
mySmtpClient.EnableSsl=false
mySmtpClient.Send(myMessage)
Can you please help me with this ?
Thanks,
Lili
The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required.
This means – you need to make sure SSL is enable in your settings using which you are sending emails – and proper SMTP port is used.
for example
SmtpClient smtpClient = new SmtpClient(“smtp.gmail.com”,587);
smtpClient.Credentials = new NetworkCredential(“******@gmail.com”, “****”);
smtpClient.UseDefaultCredentials = false;
smtpClient.EnableSsl = true;
Thanks
Vinay