I'm trying to implement a CLR stored procedure that will send emails upon request using office365 SMTP.
This is my code:
[Microsoft.SqlServer.Server.SqlProcedure()]
public static void SendMail(string recipients, string subject, string from, bool isHtml, string body, string smtpServer, int smtpPort, string smtpUser, string smtpPassword, string cc = "", string bcc = "")
{
using (MailMessage mailMessage = new MailMessage())
{
mailMessage.From = new MailAddress(from);
mailMessage.Subject = subject;
mailMessage.IsBodyHtml = isHtml;
mailMessage.Body = body;
string[] strTo = recipients.Split(';');
foreach (var item in strTo)
mailMessage.To.Add(new MailAddress(item));
if (cc != "")
{
string[] strCc = cc.Split(';');
foreach (var item in strCc)
mailMessage.CC.Add(new MailAddress(item));
}
if (bcc != "")
{
string[] strBcc = bcc.Split(';');
foreach (var item in strBcc)
mailMessage.Bcc.Add(new MailAddress(item));
}
SmtpClient smtpClient = new SmtpClient
{
Host = smtpServer,
Port = 587,
UseDefaultCredentials = false,
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new System.Net.NetworkCredential(smtpUser, smtpPassword),
TargetName = smtpServer,
EnableSsl = true
};
smtpClient.Send(mailMessage);
}
}
The above code runs without any errors while in a console app (on the same target machine), but when I run it as a CLR stored procedure, I get this error:
Msg 6522, Level 16, State 1, Procedure brx.uspSendMail, Line 0 [Batch Start Line 2]
A .NET Framework error occurred during execution of user-defined routine or aggregate "uspSendMail":System.Net.Mail.SmtpException: Failure sending mail.
System.IO.IOException: Unable to read data from the transport connection: net_io_connectionclosed.
System.IO.IOException:
at System.Net.Mail.SmtpReplyReaderFactory.ProcessRead(Byte[] buffer, Int32 offset, Int32 read, Boolean readLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLines(SmtpReplyReader caller, Boolean oneLine)
at System.Net.Mail.SmtpReplyReaderFactory.ReadLine(SmtpReplyReader caller)
at System.Net.Mail.CheckCommand.Send(SmtpConnection conn, 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)System.Net.Mail.SmtpException:
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at StoredProcedure.SendMail(String recipients, String subject, String from, Boolean isHtml, String body, String smtpServer, Int32 smtpPort, String smtpUser, String smtpPassword, String cc, String bcc)
The strange thing is this same stored procedure worked up till lately (30/5/2022 to be exact) - when google stopped supporting gmail SMTP.
Any thoughts?
Thanks in advance, Erez