Send Email in SQL Server Stored Procedure - Tutorial

This tutorial introduces how to send email in SQL Server Stored Procedure using SMTP. It also demonstrates SSL, Cursor and Email Queue usage.

Installation

EASendMail is a SMTP component which supports all operations of SMTP/ESMTP protocols (RFC 821, RFC 822, RFC 2554). Before you can use the following sample codes, you should download the EASendMail Installer and install it on your machine at first.

Prepare SQL Environment

MS SQL Server 2000 or later version provides several system Stored Procedures for invoking ActiveX COM object.

sp_OACreate
Creates an instance of the COM object on an instance of MS SQL Server

sp_OADestroy
Destroys a created COM object

sp_OAGetProperty
Gets a property value of a COM object.

sp_OASetProperty
Sets a property value of a COM object to a new value.

sp_OAMethod
Calls a method of a COM object.
sp_OAGetErrorInfo
Gets the exception information from OLE automation.

To use EASendMail SMTP ActiveX Object in MS SQL server, the first step is “Enable Ole Automation”. If you use SQL 2000, you can simply ignore this step. For SQL 2005, 2008 or later version, please open your SQL Server Management Studio and connect your server by Database Administrator at first, then open a new SQL Query window and input the following SQL statement:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO
Enable OLE in SQL

After you ran above statement, your “Ole Automation” environment is enabled, now you can use ActiveX Object in your SQL server.

Send email in a simple SQL stored procedure

To better demonstrate how to use send email using SMTP protocol, let’s create a simple stored procedure at first. First of all, select your database, then right click -> New Query to open a new SQL query window.

SQL query window

[SQL Stored Procedure Example - Send email]

Now add the following SQL statement to the query window and run it:

CREATE PROCEDURE [dbo].[usp_SendTextEmail]  @ServerAddr nvarchar(128),
@From nvarchar(128),
@To nvarchar(1024),
@Subject nvarchar(256),
@Bodytext nvarchar(max) = 'This is a test text email from MS SQL server, do not reply.',
@User nvarchar(128) = '',
@Password nvarchar(128) = '',
@SSLConnection int = 0,
@ServerPort int = 25
AS
DECLARE @hr int
DECLARE @oSmtp int
DECLARE @result int
DECLARE @description nvarchar(255)
EXEC @hr = sp_OACreate 'EASendMailObj.Mail',@oSmtp OUT
If @hr <> 0
BEGIN
    PRINT 'Please make sure you have EASendMail Component installed!'
    EXEC @hr = sp_OAGetErrorInfo @oSmtp, NULL, @description OUT
    IF @hr = 0
    BEGIN
        PRINT @description
    END
    RETURN
End
EXEC @hr = sp_OASetProperty @oSmtp, 'LicenseCode', 'TryIt'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', @ServerAddr
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', @ServerPort
EXEC @hr = sp_OASetProperty @oSmtp, 'UserName', @User
EXEC @hr = sp_OASetProperty @oSmtp, 'Password', @Password
EXEC @hr = sp_OASetProperty @oSmtp, 'FromAddr', @From
EXEC @hr = sp_OAMethod @oSmtp, 'AddRecipientEx', NULL,  @To, 0
EXEC @hr = sp_OASetProperty @oSmtp, 'Subject', @Subject
EXEC @hr = sp_OASetProperty @oSmtp, 'BodyText', @BodyText

/* Most mordern SMTP servers require SSL/TLS connection now*/
/* 1 means use SSL/TLS based on server port, 4 means if server supports SSL/TLS connection, SSL/TLS is used automatically */
If @SSLConnection > 0
    BEGIN
        EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 1
    END
ELSE
    BEGIN
        EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 4
    END

/* you can also add an attachment like this */
/*EXEC @hr = sp_OAMethod @oSmtp, 'AddAttachment', @result OUT, 'd:\test.jpg'*/
/*If @result <> 0 */
/*BEGIN*/
/*   EXEC @hr = sp_OAMethod @oSmtp, 'GetLastErrDescription', @description OUT*/
/*    PRINT 'failed to add attachment with the following error:'*/
/*    PRINT @description*/
/*END*/
PRINT 'Start to send email ...'
EXEC @hr = sp_OAMethod @oSmtp, 'SendMail', @result OUT
If @hr <> 0
BEGIN
    EXEC @hr = sp_OAGetErrorInfo @oSmtp, NULL, @description OUT
    IF @hr = 0
    BEGIN
        PRINT @description
    END
    RETURN
End
If @result <> 0
BEGIN
    EXEC @hr = sp_OAMethod @oSmtp, 'GetLastErrDescription', @description OUT
    PRINT 'failed to send email with the following error:'
    PRINT @description
END
ELSE
BEGIN
    PRINT 'Email was sent successfully!'
END
EXEC @hr = sp_OADestroy @oSmtp
Go

After you ran above SQL statement, you can find a new stored procedure named “usp_SendTextEmail” under your database->Programmability->Stored Procedures. Now we can use this stored procedure to send a simple test email like this:

DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.emailarchitect.net'
DECLARE @From nvarchar(128)
Set @From = 'test@emailarchitect.net'
DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'
DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from SQL server'
DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server, do not reply.'
/*User and password for ESMTP authentication, if your server doesn't require
User authentication, please set @User and @Password to '' */
DECLARE @User nvarchar(128)
Set @User = 'test@emailarchitect.net'
DECLARE @Password nvarchar(128)
Set @Password = 'testpassword'
/* If your smtp server requires SSL connection, please set @SSL = 1*/
DECLARE @SSL int
Set @SSL = 0
exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL

If you set everything right, you can get “email was sent successfully”. If you get “failed to send email with the following error:”, then please have a look at the following section.

Common SMTP Transport Error

When you execute above example code, if it returned an error about “Networking connection/Socket” or “No such host”, it is likely that your SMTP server address is not correct. If it threw an exception about “5xx Relay denied”, it is likely that you did not set user authentication. Another common error is “5xx Must issue a STARTTLS command first” or “No supported authentication marshal found!”, that is because your SMTP server requires user authentication under SSL connection. You can set the SSL connection to solve this problem. You can learn more detail in Troubleshooting section.

TLS 1.2

TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, and you got connection error with SSL/TLS connection, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

Where can I get my SMTP email server address, user and password?

Because each email account provider has different server address, so you should query your SMTP server address from your email account provider. To prevent spreading email from the server, most SMTP servers also require user authentication. User name is your email address or your email address without domain part, it depends on your email provider setting.

Finally, if you have already set your account in your email client such as Outlook or Window Mail, you can query your SMTP server address, user in your email client. For example, you can choose menu -> “Tools” - > - “Accounts” - > “Your email account” - > “Properties” - > “Servers” in Outlook express or Windows Mail to get your SMTP server, user. Using EASendMail to send email does not require you have email client installed on your machine or MAPI, however you can query your exist email accounts in your email client.

VB 6.0 console email sample

Email Address Syntax and Multiple Recipients

Mail Address Syntax in EASendMail SMTP Component:

// For single email address (From, ReplyTo, ReturnPath), the syntax can be:
// ["][display name]["]<email address>.
// For example:
"Tester, T" <test@adminsystem.com>
Tester <test@adminsystem.com>
<test@adminsystem.com>
test@adminsystem.com

// For mulitple email address (To, CC, Bcc), the syntax can be:
// [single email],[single email]...
// (,;\r\n) can be used to separate multiple email addresses.
// For example:
"Tester, T" <test1@adminsystem.com>, Tester2 <test2@adminsystem.com>,
   <test3@adminsystem.com>, test4@adminsystem.com

[SQL Stored Procedure Example - Email syntax]

To better understand the email address syntax, please refer to the following codes.

EXEC @hr = sp_OASetProperty @oSmtp, 'FromAddr', 'Tester<test@adminsystem.com>'
EXEC @hr = sp_OASetProperty @oSmtp, 'FromAddr', 'test@adminsystem.com'
EXEC @hr = sp_OASetProperty @oSmtp, 'FromAddr', '<test@adminsystem.com>'
/* Using AddRecipientEx to add To, Cc and Bcc in SQL
 Multiple addresses are separated with (,)
 The syntax is like this: "test@adminsystem.com, test1@adminsystem.com"*/
EXEC @hr = sp_OAMethod @oSmtp, 'AddRecipientEx', NULL, 'test1@adminsystem.com, test2@adminsystem.com', 0
EXEC @hr = sp_OAMethod @oSmtp, 'AddRecipientEx', NULL,
                        'Test1<test@adminsystem.com>, Test2<test2@adminsystem.com>', 0
/* You can also add carbon copy (CC) or blind carbon copy (BCC) in the email.*/
EXEC @hr = sp_OAMethod @oSmtp, 'AddRecipientEx', NULL, 'CC recipient<cc@adminsystem.com>', 1
EXEC @hr = sp_OAMethod @oSmtp, 'AddRecipientEx', NULL, 'Bcc recipient<bcc@adminsystem.com>', 2

From, ReplyTo, Sender and Return-Path and Priority

From, Reply-To, Sender and Return-Path are common email headers in email message. You should always set From property at first, it is a MUST to identify the email sender. The following table lists the header and corresponding properties:

Header Property
From Mail.FromAddr
Reply-To Mail.ReplyTo
Sender Mail.Sender
Return-Path Mail.ReturnPath
  • From

    This property indicates the original email sender. This is what you see as the “FROM” in most mail clients.

  • Reply-To

    This property indicates the reply address. Basically, when the user clicks “reply” in mail client, the Reply-To value should be used as the recpient address of the replied email. If you don’t set this property, the Reply address is same as From address.

  • Sender

    This property indicates the who submit/send the email. When the user received the email, the email client displays: From: “sender address” on behalf of “from address”. If you don’t set this property, the Sender address is same as From address. Sender property is common used by mail listing provider. This property also takes effect to DKIM/DomainKeys signature, if Sender is different with From address, then you should sign DKIM/DomainKeys based on Sender domain instead of From address domain.

  • Return-Path

    This property indicates the delivery notification report address. If you don’t set this property, the Return-Path address is same as From address. This property also takes effect to SPF record, if Return-Path is different with From address, then remote SMTP server checkes SPF record of Return-Path instead of From address.

Mail Priority

  • If you want to set Higher or Lower priority to your email, you can use Priority prority
  • If you want to set another email address to get the replied email rather than your From address, you can use ReplyTo property.
  • If you want to set another email address to get the delivery report rather than your From address, you can use ReturnPath property.

[SQL Stored Procedure Example - ReplyTo, ReturnPath and Priority]

EXEC @hr = sp_OASetProperty @oSmtp, 'FromAddr', 'Tester <test@emailarchitect.net>'
/* Set the Reply-To address*/
EXEC @hr = sp_OASetProperty @oSmtp, 'ReplyTo', 'replyto@@emailarchitect.net'
/* Set the email address to receive delivery report */
EXEC @hr = sp_OASetProperty @oSmtp, 'ReturnPath', 'report@emailarchitect.net'
/* Set high priority */
EXEC @hr = sp_OASetProperty @oSmtp, 'Priority', 1

HTML Email

If you want to send email in HTML format, you can enable HTML format like this:

EXEC @hr = sp_OASetProperty @oSmtp, 'BodyFormat', 1

Troubleshooting

When you send email in above simple SQL stored procedure, if it returned an error, please have a look at the following tips:

“No Such Host” Error

This error means DNS server cannot resolve SMTP server, you should check if you input correct server address. If your server address is correct, you should check if your DNS server setting is correct.

Common “Socket/Networking Connection” Error

This error means there is a problem with networking connection to SMTP server. You can use Windows built-in Telnet command to detect the networking connection.

Using Telnet to detect networking connection to SMTP server

Note

Notice: in Windows 2008/Windows 8 or later version, Telnet Client is not installed by default, you should enable this command in Control Panel -> Programs and Features -> Turn Windows feature on or off -> have Telnet Client checked.

Under DOS command prompt, input “telnet [serveraddress] [port]”:

telnet mail.emailarchitect.net 25
press enter.

If the networking connection to your SMTP server is good, it should return a message like 220 .... If it returns Could not open connection to ..., that means the networking connection to SMTP server is bad, or outbound 25 port is blocked by anti-virus software, firewall or ISP. Please have a look at the following screenshot:

detect SMTP connection using telnet

SMTP 25, 587, 465 port

25 port is the default SMTP server port to receive email. However, some ISP block outbound 25 port to prevent user to send email directly to other SMTP server. Therefore, many email providers also provide an alternative port 587 to receive email from such users. 465 port is the common port used to receive email over implicit SSL connection. If you use telnet to test 465 port, it doesn’t return the “220…”, because it requires SSL hand shake. But if the connection is ok, telnet returns a flash cursor.

“5xx … IP address block or on black list or bad reputation” Exception

This error means SMTP server blocks your IP address or email content. You can try to set user/password in your codes to do user authentication and try it again. If email client set user authentication, most SMTP servers do not check client source IP address in black list.

“5xx user authenticaton” Error

TThis error means user authentication is failed, you should check whether you input correct user/password. Password is always case-sensitive.

“5xx relay denied” Error

For anti-spam policy, most SMTP servers do not accept the email to outbound domain without user authentication. You should set user/password in the codes and try it again.

“5xx Must issue a STARTTLS command first”

This error means SMTP server requires SSL/TLS connection. You should enable SSL/TLS connection like this:

/* If your smtp server requires TLS connection, please add this line*/
EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 1

“No supported authentication marshal found!”

This error means SMTP server doesn’t support user authentication or it requires user authentication over SSL/TLS connection. You can try to remove user/password in your codes and try it again.

Other error returned by SMTP server

If SMTP server returns an error, it usually returns description about this error. Some descriptions also include a HTTP link, you can go to this linked web page to learn more detail. You can also use the following codes to generate a log file to learn all SMTP session between client and server.

[SQL Server - Using log file to detect SMTP server response - Example]

EXEC @hr = sp_OASetProperty @oSmtp, 'LogFileName', 'd:\smtp.txt'

32bit/x64 ActiveX DLL

Seperate builds of run-time dll for 32 and x64 platform

File Platform
Installation Path\Lib\native\x86\EASendMailObj.dll 32 bit
Installation Path\Lib\native\x64\EASendMailObj.dll 64 bit

Distribution

  • Standard EXE

    For VB6, C++, Delphi or other standard exe application, you can distribute EASendMailObj.dll with your application to target machine without COM-registration and installer. To learn more detail, please have a look at Registration-free COM with Manifest File.

  • Script

    For ASP, VBScript, VBA, MS SQL Stored Procedure, you need to install EASendMail on target machine by EASendMail installer, both 32bit/x64 DLL are installed and registered.

Next Section

In this section, I introduced the basic things of sending email in SQL stored procedure with EASendMail. At next section I will introduce how to send email over SSL connection.

Send Email over SSL/TLS in SQL Server Stored Procedure

In previous section, I introduced the basic things of email sending in SQL server stored procedure. In this section, I will introduce the SSL connection.

SSL and TLS Introduction

SSL connection encrypts data between the SMTP component and SMTP server to protects user, password and email content in TCP/IP level. Now this technology is commonly used and many SMTP servers are deployed with SSL such as Gmail, Yahoo and Hotmail. There are two ways to deploy SSL on SMTP server:

  • Explicit SSL (TLS)

    Using STARTTLS command to switch SSL channel on normal SMTP port (25 or 587);

  • Implicit SSL

    Deploying SSL on another port (465 or other port, you may query it from your server administrator

You can use ConnectType property to set different connection type.

TLS 1.2

TLS is the successor of SSL, more and more SMTP servers require TLS 1.2 encryption now.

If your operating system is Windows XP/Vista/Windows 7/Windows 2003/2008/2008 R2/2012/2012 R2, and you got connection error with SSL/TLS connection, you need to enable TLS 1.2 protocol in your operating system like this:

Enable TLS 1.2 on Windows XP/Vista/7/10/Windows 2008/2008 R2/2012

[SQL Stored Procedure Exmaple - SSL/TLS]

/* Send email by normal TCP/IP without SSL connection */
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', 'localhost'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', 25

/* Send email by SSL connection with STARTTLS command switching */
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', 'localhost'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', 25
EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 2

/* Send email by SSL connection with direct SSL */
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', 'localhost'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', 465
EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 3

/* Send email by SSL/TLS connection with auto-detect.*/
/* If port is 25 or 587, STARTTLS TLS will be used; otherwise direct SSL will be used. */

EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', 'localhost'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', 465
EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 1

EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', 'localhost'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', 25
EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 1

/* 4 means if server supports SSL/TLS connection, SSL/TLS is used automatically */
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', 'localhost'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', 25
EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 4

EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', 'localhost'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', 587
EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 4

Note

Remarks: All of samples in this section are based on first section: Send email in a simple SQL stored procedure. To run the following example codes successfully, please click here to learn how to create the test enivronment and use EASendMail in your project.

[SQL Stored Procedure Example - Send email over direct SSL on 465 port]

The following example codes demonstrate how to send email with direct SSL connection on 465 port.

Note

To get the full sample projects, please refer to Samples section.

DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.emailarchitect.net'

DECLARE @From nvarchar(128)
Set @From = 'test@emailarchitect.net'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from SQL server'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server, do not reply.'

/*User and password for ESMTP authentication, if your server doesn't require
User authentication, please set @User and @Password to '' */
DECLARE @User nvarchar(128)
Set @User = 'test@emailarchitect.net'
DECLARE @Password nvarchar(128)
Set @Password = 'testpassword'

/* Set SSL connection*/
DECLARE @SSL int
Set @SSL = 1

/* Set 465 port */
DECLARE @Port int
Set @Port = 465
exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

[SQL Stored Procedure Example - Send email over TLS on 25 or 587 port]

The following example codes demonstrate how to send email with TLS (STARTTLS command) connection on 25 port.

Note

To get the full sample projects, please refer to Samples section.

DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.emailarchitect.net'

DECLARE @From nvarchar(128)
Set @From = 'test@emailarchitect.net'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from SQL server'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server, do not reply.'

/*User and password for ESMTP authentication, if your server doesn't require
User authentication, please set @User and @Password to '' */
DECLARE @User nvarchar(128)
Set @User = 'test@emailarchitect.net'
DECLARE @Password nvarchar(128)
Set @Password = 'testpassword'

/* Set SSL connection*/
DECLARE @SSL int
Set @SSL = 1

/* Set 25 port */
DECLARE @Port int
Set @Port = 25

exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

Next Section

At next section I will introduce how to send email using Gmail account.

Send Email using Gmail in SQL Server Stored Procedure

In previous section, I introduced how to send email over SSL connection. In this section, I will introduce how to use your Gmail account to send email in SQL stored procedure.

Introduction

Gmail SMTP server address is smtp.gmail.com. It requires implicit SSL or explicit SSL (TLS) connection, and you should use your Gmail email address as the user name for ESMTP authentication.

Server Port SSL/TLS
smtp.gmail.com 25, 587 TLS
smtp.gmail.com 465 SSL

Gmail App Password

To help keep your account secure, starting May 30, 2022, ​​Google will no longer support the use of third-party apps or devices which ask you to sign in to your Google Account using only your username and password.

Therefore, you should sign in using App Passwords. An App Password is a 16-digit passcode that gives a less secure app or device permission to access your Google Account. App Passwords can only be used with accounts that have 2-Step Verification turned on. You need to use App Password instead of the user password for user authentication.

Another solution is Gmail OAUH, please see Gmail SMTP OAUTH section.

Note

Remarks: All of samples in this section are based on first section: Send email in a simple SQL stored procedure. To run the following example codes successfully, please click here to learn how to create the test enivronment and use EASendMail in your project.

[SQL Stored Procedure Example - Send email using Gmail account over SSL connection on 465 port]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Gmail account.

Note

To get the full sample projects, please refer to Samples section.

/* Gmail SMTP server address */
DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.gmail.com'

/* Set your Gmail email address */
DECLARE @From nvarchar(128)
Set @From = 'gmailid@gmail.com'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from Gmail account'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server, do not reply.'

/* Gmail user authentication should use your
 Gmail email address as the user name.
For example: your email is "gmailid@gmail.com", then the user should be "gmailid@gmail.com" */
DECLARE @User nvarchar(128)
Set @User = 'gmailid@gmail.com'

/* Create app password in Google account*/
/* https://support.google.com/accounts/answer/185833?hl=en */
DECLARE @Password nvarchar(128)
Set @Password = 'your app password'

/* Enable SSL/TLS */
DECLARE @SSL int
Set @SSL = 1

/* If you want to use TLS, please set it to 25 or 587 */
DECLARE @Port int
Set @Port = 465

PRINT 'start to send email ...'
exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

[SQL Stored Procedure Example - Send email using Gmail account over TLS connection on 587 port]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Gmail account.

Note

To get the full sample projects, please refer to Samples section.

/* Gmail SMTP server address */
DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.gmail.com'

/* Set your Gmail email address */
DECLARE @From nvarchar(128)
Set @From = 'gmailid@gmail.com'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from SQL server using gmail account'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server, do not reply.'

/* Gmail user authentication should use your
 Gmail email address as the user name.
For example: your email is "gmailid@gmail.com", then the user should be "gmailid@gmail.com" */
DECLARE @User nvarchar(128)
Set @User = 'gmailid@gmail.com'

/* Create app password in Google account*/
/* https://support.google.com/accounts/answer/185833?hl=en */
DECLARE @Password nvarchar(128)
Set @Password = 'your app password'

/* Enable SSL/TLS */
DECLARE @SSL int
Set @SSL = 1

/* Use 587 port */
DECLARE @Port int
Set @Port = 587

PRINT 'start to send email ...'
exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

Gmail SMTP OAUTH

The Gmail IMAP and SMTP servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Gmail Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.

Using Gmail SMTP OAUTH

Next Section

At next section I will introduce how to send email with Yahoo account.

Send Email using Yahoo in SQL Server Stored Procedure

In previous section, I introduced how to send email using Gmail account. In this section, I will introduce how to use your Yahoo account to send email in SQL stored procedure.

Introduction

Yahoo SMTP server address is smtp.mail.yahoo.com”. It supports both Normal/SSL connection to do user authentication, and you should use your Yahoo email address as the user name for ESMTP authentication. For example: your email is myid@yahoo.com, and then the user name should be myid@yahoo.com.

If you want to use SSL connection with Yahoo SMTP server, you must set the port to 465.

Server Port SSL/TLS
smtp.mail.yahoo.com 25, 587 TLS
smtp.mail.yahoo.com 465 SSL

Note

Remarks: All of samples in this section are based on first section: Send email in a simple SQL stored procedure. To run the following example codes successfully, please click here to learn how to create the test enivronment and use EASendMail in your project.

Important

If you got authentication error, you need to enable Allowing less secure apps in your Yahoo account. Or you can generate App Passwords and use this app password instead of your user password.

Although Yahoo supports OAUTH, but it doesn’t provide mail permission, so OAUTH is not a solution for Yahoo mail.

[SQL Stored Procedure Example - Send email using Yahoo account over direct SSL connection]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Yahoo account.

Note

To get the full sample projects, please refer to Samples section.

/* Yahoo SMTP server address */
DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.mail.yahoo.com'

/* Set your Yahoo email address */
DECLARE @From nvarchar(128)
Set @From = 'myid@yahoo.com'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from Yahoo account'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server with yahoo, do not reply.'

/* For example: your email is "myid@yahoo.com", then the user should be "myid@yahoo.com" */
DECLARE @User nvarchar(128)
Set @User = 'myid@yahoo.com'
DECLARE @Password nvarchar(128)
Set @Password = 'yourpassword'

/* Enable SSL/TLS */
DECLARE @SSL int
Set @SSL = 1

/* Because yahoo deploys SMTP server on 465 port with direct SSL connection.
  So we should change the port to 465. */
DECLARE @Port int
Set @Port = 465

PRINT 'start to send email ...'
exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

[SQL Stored Procedure Example - Send email using Yahoo account over TLS connection on 587 port ]

The following example codes demonstrate how to send email using Yahoo account over TLS 587 port.

Note

To get the full sample projects, please refer to Samples section.

/* Yahoo SMTP server address */
DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.mail.yahoo.com'

/* Set your Yahoo email address */
DECLARE @From nvarchar(128)
Set @From = 'myid@yahoo.com'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from Yahoo account'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server with yahoo, do not reply.'

/* For example: your email is "myid@yahoo.com", then the user should be "myid@yahoo.com" */
DECLARE @User nvarchar(128)
Set @User = 'myid@yahoo.com'
DECLARE @Password nvarchar(128)
Set @Password = 'yourpassword'

/* Enable SSL/TLS */
DECLARE @SSL int
Set @SSL = 1

/*set 587 port*/
DECLARE @Port int
Set @Port = 587

PRINT 'start to send email ...'
exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

Next Section

At next section I will introduce how to send email using Hotmail/MSN Live/Office 365 account.

Send Email using Hotmail/MSN Live/Oulook/Office365 in SQL Server Stored Procedure

In previous section, I introduced how to send email using Yahoo account. In this section, I will introduce how to use your Hotmail/MSN Live/Outlook.com/Office365 account to send email in SQL stored procedure.

Introduction

Hotmail/MSN Live/Outlook.com SMTP server address is smtp.office365.com. It requires TLS connection to do user authentication, and you should use your Hotmail/MSN Live/Outlook.com email address as the user name for ESMTP authentication. For example: your email is liveid@hotmail.com, and then the user name should be liveidmyid@hotmail.com.

Server Port SSL/TLS
smtp.office365.com 25, 587 TLS

Note

Remarks: All of samples in this section are based on first section: Send email in a simple SQL stored procedure. To run the following example codes successfully, please click here to learn how to create the test enivronment and use EASendMail in your project.

[SQL Stored Procedure Example - Send email using Hotmail/MSN Live account over TLS connection]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Hotmail/MSN Live account.

Note

To get the full sample projects, please refer to Samples section.

/* Hotmail SMTP server address */
DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.office365.com'

/* Set your Hotmail email address */
DECLARE @From nvarchar(128)
Set @From = 'liveid@hotmail.com'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from Hotmail/MSN Live account'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server with Hotmail, do not reply.'

/* For example: your email is "liveid@hotmail.com", then the user should be "liveid@hotmail.com" */
DECLARE @User nvarchar(128)
Set @User = 'liveid@hotmail.com'

/* If you got authentication error, try to create an app password instead of your user password.*/
/* https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944 */
DECLARE @Password nvarchar(128)
Set @Password = 'your password or app password'

/* Enable SSL/TLS */
DECLARE @SSL int
Set @SSL = 1

/* Because Live Server deploys SMTP server on 25/587 port with TLS connection.
  So we should change the port to 25 or 587. */
DECLARE @Port int
Set @Port = 587

PRINT 'start to send email ...'
exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

Hotmail SMTP OAUTH

If your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should use SMTP OAUTH or App Password.

Microsoft Live SMTP servers (Hotmail, Oultook personal account) have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.

Using Microsoft Hotmail SMTP OAUTH

Or you can generate App Passwords and use this app password instead of your user password.

Send Email using Office 365

Office 365 SMTP server uses 587 port and explicit SSL (TLS) connection.

Server Port SSL/TLS
smtp.office365.com 25, 587 (recommended) TLS

App Password and SmtpClientAuthenticationDisabled

If your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should create an App Passwords and use this App Password instead of the user password.

You should also check if authenticated client SMTP submission (SMTP AUTH) is enabled:

Enable or disable authenticated client SMTP submission (SMTP AUTH) in Exchange Online.

[SQL Stored Procedure Example - Send email using Office365 account over TLS connection]

The following example codes demonstrate how to use EASendMail SMTP component to send email using Office 365 account.

Note

To get the full sample projects, please refer to Samples section.

/* office365 SMTP server address */
DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.office365.com'

/* Set your office365 email address */
DECLARE @From nvarchar(128)
Set @From = 'myid@mydomain'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from Office365 account'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server with Office365, do not reply.'

/* For example: your email is "myid@mydomain", then the user should be "myid@mydomain" */
DECLARE @User nvarchar(128)
Set @User = 'myid@mydomain'
DECLARE @Password nvarchar(128)

/* If you got authentication error, try to create an app password instead of your user password.*/
/* https://support.microsoft.com/en-us/account-billing/using-app-passwords-with-apps-that-don-t-support-two-step-verification-5896ed9b-4263-e681-128a-a6f2979a7944 */
Set @Password = 'your password or app password'

/* Enable SSL/TLS */
DECLARE @SSL int
Set @SSL = 1

/* Use 587 port */
DECLARE @Port int
Set @Port = 587

PRINT 'start to send email ...'
exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

Office365 SMTP/EWS/Ms Graph API OAUTH

If your account enabled two-factor authentication, you cannot login your account by normal user authentication, you should use SMTP/EWS/Ms Graph API OAUTH or App Password.

Microsoft Office365 SMTP/EWS/Ms Graph API servers have been extended to support authorization via the industry-standard OAuth 2.0 protocol. Using OAUTH protocol, user can do authentication by Microsoft Web OAuth instead of inputting user and password directly in application. This way is more secure, but a little bit complex.

Using Microsoft Office365 EWS OAUTH

Or you can generate App Passwords and use this app password instead of your user password.

Next Section

At next section I will introduce how to send email without specified SMTP server.

Send Email directly without SMTP server(MX DNS lookup) in SQL Server Stored Procedure

In previous section, I introduced how to send email using Hotmail/MSN Live account. In this section, I will introduce how to use DNS lookup to send email without specified SMTP server in SQL stored procedure.

Introduction

In general, we send email via specified SMTP server. How does the specified SMTP server know what address this email should be sent to? The answer is… it queries MX record of recipient’s domain via DNS lookup. It then forwards this email to the SMTP server queried from DNS server. If recipient’s server doesn’t work fine, sender’s SMTP server will send a failure-delivery report to the sender telling it failed to send out the email.

How does EASendMail SMTP component work with “Send email directly”? Firstly, it queries MX record for recipient address from DNS, then sends email to recipient’s email server directly. In short, if no SMTP server is specified in the code, EASendMail will send email to recipient directly. Since querying DNS server consumes CPU time and networking resource, the performance of “Send email directly” is lower than sending email with specified SMTP server. Moreover, nowadays more and more SMTP servers block email sent from dynamic IP address, so we don’t recommend you to use “Direct Send Email” except you have a static IP address or you encounter problem with your ISP SMTP server.

Every recipient may have different SMTP server, if there are multiple recipients in one message and you want to send email directly, you should send the email to the recipients one by one.

To implement this feature, you just need to put nothing to SMTP server address.

Note

Remarks: All of samples in this section are based on first section: Send email in a simple SQL stored procedure. To run the following example codes successfully, please click here to learn how to create the test enivronment and use EASendMail in your project.

[SQL Stored Procedure Example - Send email without specified SMTP server (MX record DNS lookup)]

The following example codes demonstrate how to use EASendMail SMTP component to send email using DNS lookup.

Note

To get the full sample projects, please refer to Samples section.

/* Set SMTP server address to '' */
DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = ''

DECLARE @From nvarchar(128)
Set @From = 'test@emailarchitect.net'

DECLARE @To nvarchar(1024)
/*You can input multiple recipients and use comma (,) to separate multiple addresses */
Set @To = 'support@emailarchitect.net'

DECLARE @Subject nvarchar(256)
Set @Subject = 'simple email from SQL server'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server directly, do not reply.'

/* Do not set user authentication */
DECLARE @User nvarchar(128)
Set @User = ''
DECLARE @Password nvarchar(128)
Set @Password = ''

/* Do not set  SSL connection*/
DECLARE @SSL int
Set @SSL = 0

/* Set 25 default SMTP port */
DECLARE @Port int
Set @Port = 25

exec usp_SendTextEmail @ServerAddr, @From, @To, @Subject, @BodyText, @User, @Password, @SSL, @Port

With above code, if you get error like “5xx IP address rejected”, that means your IP address is blocked by the recipient’s SMTP server. You have to specify a SMTP server with user authentication to relay your email.

Remarks

In my solid experience, I don’t suggest that you send email directly.

  • If your IP address is dynamic, most SMTP servers reject your connection due to anti-spam policy. We always suggest that your send email by a SMTP server that has a static internet IP address. When you relay email by your SMTP server, because you do user authentication at first before you send email to your SMTP server, so your SMTP server doesn&#8217;t reject your connection even your IP address is dynamic. Finally your SMTP server sends email to remote SMTP server. Because your SMTP server has a static IP, the email won&#8217;t be rejected by remote SMTP server.

    Send email using DNS lookup in SQL Server
  • If you encountered a temporal SMTP error (4xx), you should retry to send email later. That means you have to write the code to handle retry. So if you have a static IP address, I suggest that you use EASendMail Component + EASendMail Service, EASendMail service can send email directly or send email with specified SMTP server in background and handle delivery retry automatically.

To learn more detail about EASendMail Serivce, please have a look at Work with EASendMail Service (Email Queuing).

Next Section

At next section I will introduce how to send multiple emails with cursor in SQL stored procedure.

Send Multiple Emails with Cursor in SQL Server Stored Procedure

In previous section, I introduced how to send email without specified SMTP server. In this section, I will introduce how to send multiple emails with cursor in SQL stored procedure.

Introduction

Most common email task in database is sending emails to a specified email list. To better understand the cursor, we need to create a simple table in your database like this:

CREATE TABLE [dbo].[rcpts](
    [uid] [bigint] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](50) NULL,
    [email] [nvarchar](128) NOT NULL,
 CONSTRAINT [PK_rcpts] PRIMARY KEY CLUSTERED
(
    [uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Then insert a record in this table like this:

SQL table sample

Note

Remarks: All of samples in this section are based on first section: Send email in a simple SQL stored procedure. To run the following example codes successfully, please click here to learn how to create the test enivronment and use EASendMail in your project.

[SQL Stored Procedure Example - Send multiple emails with cursor]

The following example codes demonstrate how to use EASendMail SMTP component to send multiple emails with cursor.

Note

To get the full sample projects, please refer to Samples section.

DECLARE @email nvarchar(128)
DECLARE rcpt_cursor CURSOR FOR
SELECT email
FROM rcpts
OPEN rcpt_cursor
/* select all records from rcpts table and send it one by one */
FETCH NEXT FROM rcpt_cursor
INTO @email

DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.emailarchitect.net'

DECLARE @From nvarchar(128)
Set @From = 'test@emailarchitect.net'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server, do not reply.'

/*User and password for ESMTP authentication, if your server doesn't require
User authentication, please set @User and @Password to '' */
DECLARE @User nvarchar(128)
Set @User = 'test@emailarchitect.net'
DECLARE @Password nvarchar(128)
Set @Password = 'testpassword'

/* If your smtp server requires SSL connection, please set @SSL = 1*/
DECLARE @SSL int
Set @SSL = 0

DECLARE @Port int
Set @Port = 25

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @email
    DECLARE @subject nvarchar(255)
    SELECT @Subject = 'test email for' + @email
    EXEC usp_SendTextEmail @ServerAddr,
            @from, @email, @subject, @BodyText, @User, @Password, @SSL, @Port
    FETCH NEXT FROM rcpt_cursor
    INTO @email
END
CLOSE rcpt_cursor
DEALLOCATE rcpt_cursor

Next Section

At next section I will introduce how to send mass emails with EASendMail Service Queue in SQL stored procedure.

Send Mass Emails with EASendMail Service Queue in SQL Server Stored Procedure

In previous section, I introduced how to send multiple emails with cursor. In this section, I will introduce how to send mass emails with EASendMail service queue.

Introduction

EASendMail Service is a light and fast email delivery service which works with EASendMail SMTP Component to enable your application to send mass emails in background queue service.

Along with its ability to picking recipients from database in background and sending email in specified datetime, it eases your task in developing featured email application such as newsletter application. We strongly recommend you to use EASendMail Service with your ASP.NET/Web Application.

Important

To work with EASendMail Service, please download EASendMail and EASendMail Service at first, and then install both on your machine. If you are using web hosting service and you don’t have permission to install service on that server, EASendMail service is not suitable for you.

send email using queue in sql server

With EASendMail email queue feature, you do not have to code for multiple threadings. EASendMail Service can send email in background with multiple threadings automatically. You just need to adjust the maximum worker threads in EASendMail Service Manager to increase the performance. Please click here to learn more detail about EASendMail Service.

If your networking connection to your SMTP server is not very fast, EASendMail Service is absolutely solution for you. You just need to submit the email to EASendMail service queue, it is very fast because EASendMail service uses shared memory to accept email from EASendMail component, and then the service will send email in background service.

Note

Remarks: All of samples in this section are based on first section: Send email in a simple SQL stored procedure. To run the following example codes successfully, please click here to learn how to create the test enivronment and use EASendMail in your project.

Basic SQL stored procedure

First of all, let us create a SQL stored procedure like this:

CREATE PROCEDURE [dbo].[usp_SendMailToQueue]  @ServerAddr nvarchar(128),
@From nvarchar(128),
@To nvarchar(1024),
@Subject nvarchar(256),
@Bodytext nvarchar(max) = 'This is a test text email from MS SQL server, do not reply.',
@User nvarchar(128) = '',
@Password nvarchar(128) = '',
@SSLConnection int = 0,
@ServerPort int = 25
AS
DECLARE @hr int
DECLARE @oSmtp int
DECLARE @result int
DECLARE @description nvarchar(255)
EXEC @hr = sp_OACreate 'EASendMailObj.Mail',@oSmtp OUT
If @hr <> 0
BEGIN
    PRINT 'Please make sure you have EASendMail Component installed!'
    EXEC @hr = sp_OAGetErrorInfo @oSmtp, NULL, @description OUT
    IF @hr = 0
    BEGIN
        PRINT @description
    END
    RETURN
End
EXEC @hr = sp_OASetProperty @oSmtp, 'LicenseCode', 'TryIt'
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', @ServerAddr
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', @ServerPort
EXEC @hr = sp_OASetProperty @oSmtp, 'UserName', @User
EXEC @hr = sp_OASetProperty @oSmtp, 'Password', @Password
EXEC @hr = sp_OASetProperty @oSmtp, 'FromAddr', @From
EXEC @hr = sp_OAMethod @oSmtp, 'AddRecipientEx', NULL,  @To, 0
EXEC @hr = sp_OASetProperty @oSmtp, 'Subject', @Subject
EXEC @hr = sp_OASetProperty @oSmtp, 'BodyText', @BodyText

/* Most mordern SMTP servers require SSL/TLS connection now*/
/* 1 means use SSL/TLS based on server port, 4 means if server supports SSL/TLS connection, SSL/TLS is used automatically */
If @SSLConnection > 0
    BEGIN
        EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 1
    END
ELSE
    BEGIN
        EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 4
    END

EXEC @hr = sp_OAMethod @oSmtp, 'SendMailToQueue', @result OUT
If @hr <> 0
BEGIN
    EXEC @hr = sp_OAGetErrorInfo @oSmtp, NULL, @description OUT
    IF @hr = 0
    BEGIN
        PRINT @description
    END
    RETURN
End
If @result <> 0
BEGIN
    EXEC @hr = sp_OAMethod @oSmtp, 'GetLastErrDescription', @description OUT
    PRINT @description
    PRINT 'Please make sure you have EASendMail Service installed'
END
ELSE
BEGIN
    PRINT 'Message submitted!'
END
EXEC @hr = sp_OADestroy @oSmtp
Go

Now we can use above stored procedure like this:

[SQL Stored Procedure Example - Send Mass Emails with EASendMail Service Queue]

The following example codes demonstrate how to use EASendMail SMTP component to send mass emails with EASendMail Service Queue.

Note

To get the full sample projects, please refer to Samples section.

DECLARE @email nvarchar(128)
DECLARE rcpt_cursor CURSOR FOR
SELECT email
FROM rcpts
OPEN rcpt_cursor
FETCH NEXT FROM rcpt_cursor
INTO @email

DECLARE @ServerAddr nvarchar(128)
Set @ServerAddr = 'smtp.emailarchitect.net'

DECLARE @From nvarchar(128)
Set @From = 'test@emailarchitect.net'

DECLARE @Bodytext nvarchar(512)
Set @BodyText = 'This is a test text email from MS SQL server, do not reply.'

/*User and password for ESMTP authentication, if your server doesn't require
User authentication, please set @User and @Password to '' */

DECLARE @User nvarchar(128)
Set @User = 'test@emailarchitect.net'
DECLARE @Password nvarchar(128)
Set @Password = 'testpassword'

/* If your smtp server requires SSL connection, please set @SSL = 1*/
DECLARE @SSL int
Set @SSL = 0

DECLARE @Port int
Set @Port = 25

WHILE @@FETCH_STATUS = 0
BEGIN
    PRINT @email
    DECLARE @subject nvarchar(255)
    SELECT @Subject = 'test email for ' + @email
    EXEC usp_SendMailToQueue @ServerAddr,
            @from, @email, @subject, @BodyText, @User, @Password, @SSL, @Port
    FETCH NEXT FROM rcpt_cursor
    INTO @email
END
CLOSE rcpt_cursor
DEALLOCATE rcpt_cursor

Next Section

At next section I will introduce how to Send email with advanced database queue.

Send Mass Emails with Advanced Database Queue in SQL Server Stored Procedure

In previous section, I introduced how to send email EASendMail Service Queue. In this section, I will introduce how to send mass emails with advanced database queue in SQL stored procedure.

Introduction

Although EASendMail service provides a faster way to send email in background, but there are thousands of emails in a task, the SendMailToQueue will be invoked for thousands times, obviously it is not effect way.

Therefore, EASendMail service provides a more effective way to send mass emails. In short, you just need to submit your database connection and record set once, EASendMail service will pick up the record set in background and send email to each record one by one.

send email using database queue in sql server

Create Database Table

To better understand the database queue, we need to create three tables in your database like this:

CREATE TABLE [dbo].[rcpts](
    [uid] [bigint] IDENTITY(1,1) NOT NULL,
    [name] [nvarchar](50) NULL,
    [email] [nvarchar](128) NOT NULL,
 CONSTRAINT [PK_rcpts] PRIMARY KEY CLUSTERED
(
    [uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[errorlog](
    [uid] [bigint] IDENTITY(1,1) NOT NULL,
    [email] [nvarchar](128) NULL,
    [server] [nvarchar](50) NULL,
    [errorcode] [nvarchar](50) NULL,
    [errordescription] [nvarchar](255) NULL,
 CONSTRAINT [PK_errorlog] PRIMARY KEY CLUSTERED
(
    [uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [dbo].[sentlog](
    [uid] [bigint] IDENTITY(1,1) NOT NULL,
    [server] [nvarchar](50) NULL,
    [email] [nvarchar](128) NULL,
 CONSTRAINT [PK_sentlog] PRIMARY KEY CLUSTERED
(
    [uid] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF,
    IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Then insert two records in table ‘rcpts’ like this:

SQL table sample

Note

Remarks: All of samples in this section are based on first section: Send email in a simple SQL stored procedure. To run the following example codes successfully, please click here to learn how to create the test enivronment and use EASendMail in your project.

[SQL Stored Procedure Example - Send mass emails with advanced database queue]

The following example codes demonstrate how to use EASendMail SMTP component to send email with advanced database queue.

Note

To get the full sample projects, please refer to Samples section.

/* change it to your server address */
DECLARE @ServerAddr nvarchar(128)
SET @ServerAddr = 'smtp.emailarchitect.net'

DECLARE @From nvarchar(128)
SET @From = 'Tester <test@adminsystem.com>'

/* change it to your sql server address, database, user and password */
/* The server/instance name syntax used in the server option is the same for all SQL Server connection strings.*/
/* e.g.: Server=serveraddress\instancename;*/
/* SQL 2005 */
DECLARE @DataConn nvarchar(255)
SET @DataConn = 'Driver={SQL Native Client};Server=serveraddress;Database=database;Uid=user;Pwd=password;'

/* MS SQL Server 2005 Native Provider */
/*SET @DataConn = 'Provider=SQLNCLI;Server=serveraddress;Database=database;Uid=user;Pwd=password;'*/
/* using SQL 2008 Driver*/
/*SET @DataConn = 'Driver={SQL Server Native Client 10.0};Server=serveraddress;Database=database;Uid=user;Pwd=password;'*/
/* MS SQL Server 2008 Native Provider */
/*SET @DataConn = 'Provider=SQLNCLI10;Server=serveraddress;Database=database;Uid=user;Pwd=password;'*/
/* using SQL 2005/2012 Driver*/
/*SET @DataConn = 'Driver={SQL Server Native Client 11.0};Server=serveraddress;Database=database;Uid=user;Pwd=password;'*/
/* MS SQL Server 2012 Native Provider */
/*SET @DataConn = 'Provider=SQLNCLI11;Server=serveraddress;Database=database;Uid=user;Pwd=password;'*/
/* select all records from this table */
DECLARE @SQLSelect nvarchar(255)
SET @SQLSelect = 'SELECT uid, name, email from rcpts'

/* insert all successful record to this table */
DECLARE @SQLSuccess nvarchar(255)
SET @SQLSuccess = 'INSERT INTO sentlog ( server, email )'
    + ' VALUES( ''{$var_server}'', ''{$var_rcptaddr}'' )'

/* insert all failure record to this table */
DECLARE @SQLError nvarchar(255)
SET @SQLError = 'INSERT INTO errorlog( email, server, errorcode, errordescription )' +
    ' VALUES( ''{$var_rcptaddr}'', ''{$var_server}'', ''{$var_errcode}'',  ''{$var_errdesc}'' )'

DECLARE @Subject nvarchar(256)
DECLARE @Bodytext nvarchar(max)
SET @Bodytext = ''

/*User and password for ESMTP authentication, if your server doesn't require
User authentication, please set @User and @Password to '' */
DECLARE @User nvarchar(128)
Set @User = 'test@emailarchitect.net'
DECLARE @Password nvarchar(128)
Set @Password = 'testpassword'

/* If your smtp server requires SSL connection, please set @SSL = 1*/
DECLARE @SSL int
Set @SSL = 0

DECLARE @Port int
Set @Port = 25

DECLARE @hr int
DECLARE @oSmtp int
DECLARE @result int
DECLARE @description nvarchar(255)
EXEC @hr = sp_OACreate 'EASendMailObj.Mail',@oSmtp OUT
If @hr <> 0
BEGIN
    PRINT 'Please make sure you have EASendMail Component installed!'
    EXEC @hr = sp_OAGetErrorInfo @oSmtp, NULL, @description OUT
    IF @hr = 0
    BEGIN
        PRINT @description
    END
    RETURN
End
EXEC @hr = sp_OASetProperty @oSmtp, 'LicenseCode', 'TryIt'
EXEC @hr = sp_OAMethod @oSmtp, 'AddHeader', NULL, 'X-Data-Connection', @DataConn
EXEC @hr = sp_OAMethod @oSmtp, 'AddHeader', NULL, 'X-Sql-Select', @SQLSelect
EXEC @hr = sp_OAMethod @oSmtp, 'AddHeader', NULL, 'X-Sql-OnSentSuccess', @SQLSuccess
EXEC @hr = sp_OAMethod @oSmtp, 'AddHeader', NULL, 'X-Sql-OnSentError', @SQLError
EXEC @hr = sp_OAMethod @oSmtp, 'AddHeader', NULL, 'X-Rcpt-To', '{$var_srecord:email}'
EXEC @hr = sp_OASetProperty @oSmtp, 'DisplayTo', '"{$var_srecord:name}" <{$var_srecord:email}>'

EXEC @hr = sp_OASetProperty @oSmtp, 'ServerAddr', @ServerAddr
EXEC @hr = sp_OASetProperty @oSmtp, 'ServerPort', @Port
EXEC @hr = sp_OASetProperty @oSmtp, 'UserName', @User
EXEC @hr = sp_OASetProperty @oSmtp, 'Password', @Password
EXEC @hr = sp_OASetProperty @oSmtp, 'FromAddr', @From
SET @Subject = 'test email with data pick'
EXEC @hr = sp_OASetProperty @oSmtp, 'Subject', @Subject
SET @BodyText = 'Test email, do not reply, your id in database is {$var_srecord:uid}.'
EXEC @hr = sp_OASetProperty @oSmtp, 'BodyText', @BodyText

/* Most mordern SMTP servers require SSL/TLS connection now*/
/* 1 means use SSL/TLS based on server port, 4 means if server supports SSL/TLS connection, SSL/TLS is used automatically */
If @SSL > 0
    BEGIN
        EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 1
    END
ELSE
    BEGIN
        EXEC @hr = sp_OASetProperty @oSmtp, 'ConnectType', 4
    END

EXEC @hr = sp_OAMethod @oSmtp, 'SendMailToQueue', @result OUT
If @hr <> 0
BEGIN
    EXEC @hr = sp_OAGetErrorInfo @oSmtp, NULL, @description OUT
    IF @hr = 0
    BEGIN
        PRINT @description
    END
    RETURN
End
If @result <> 0
BEGIN
    PRINT 'Please make sure you have EASendMail Service installed!'
    EXEC @hr = sp_OAMethod @oSmtp, 'GetLastErrDescription', @description OUT
    PRINT @description
END
ELSE
BEGIN
    PRINT 'Message has been submitted to EASendMail Service!'
END
EXEC @hr = sp_OADestroy @oSmtp
Go

With above SQL statement, no matter how many records in your table, SendMailToQueue is only invoked once and EASendMail service will pick up records in background and send the email based on each record to recipient one by one. It also inserts the results back to “errorlog” and “sentlog” tables automatically. You can open EASendMail Service Manager to monitor the queue and view Journal -> System Error to check if there is error with your database connection and SQL statement.

Database Server Driver

In X-Data-Connection header, you should specify a database driver to connect database. You can open “Control Panel” -> “Administrative Tools” - > “ODBC Data Sources” - “Drivers” to check current installed database drivers.

odbc drivers

Common SQL Driver Download

If SQL Server is installed on a remote server, and you don’t have SQL driver installed on local machine, then you need to download and install corresponding driver on local machine.

Next Section

Total sample projects in EASendMail SMTP Component installation package.

SQL Server - Sample Projects for SMTP, SSL, TLS, Cursor, Email Queue

After you downloaded the EASendMail SMTP Component Installer and install it on your machine, there are many samples in the installation path.

All the samples locate at EASendMail Installation Folder. Most of sample projects demonstrate file attachment, embedded images, S/MIME, user authentication, SSL/TLS connection and Dns lookup.

ActiveX Object Sample Projects

ASP Classic

VBScript, JScript\Simple Send a simple email from ASP Classic.
VBScript, JScript\SimpleQueue Send email from ASP Classic to EASendMail Service.
VBScript\GmailOauth Send email using Gmail OAUTH/XOAUTH2.
VBScript, JScript\AdvancedQueueWithDatabase Send email from ASP Classic to EASendMail Service, background service will select recipients from database and write result back to database.

Delphi

Simple Send a simple email from Delphi 7.
HtmlMail Send text/html email using Web Browser Control Editor
Mass Send mass emails using thread pool.
Oauth Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2.

MS SQL Server

SQL Send email from MS SQL Server stored procedure.

Script

VBScript/JScript/WScript Send a simple email from VBScript/JScript/WScript.

VB6

Simple Send a simple email from VB 6.0.
HtmlMail Send text/html email using Web Browser Control Editor
Mass Send mass emails using thread pool.
Oauth Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2.

VC++

Simple Send a simple email from VC++.
HtmlMail Send text/html email using Web Browser Control Editor
Mass Send mass emails using thread pool.
Oauth Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2.

.NET Framework Sample Projects

ASP.NET Form

C#, VB, JScript\Simple Send a simple email from ASP.NET form.
C#, VB, JScript\SimpleQueue Send email from ASP.NET to EASendMail Service.
C#, VB\GmailOauth Send email using Gmail OAUTH/XOAUTH2.
C#, VB, JScript\AdvancedQueueWithDatabase Send email from ASP.NET to EASendMail Service, background service will select recipients from database and write result back to database.

ASP.NET MVC

C#, VB\WebProject1\SimpleController Send a simple email from ASP.NET MVC by Form Post/Ajax Post.
C#, VB\WebProject1\GmailOauthController Send email using Gmail OAUTH/XOAUTH2.
C#, VB\WebProject1\MassController Send mass emails using background thread pool.
C#, VB\WebProject1\DbRecipientsController Send mass emails using background thread pool, select recipients from database and write result back to database.

.NET Desktop (Windows Form)

C#, VB\Simple Send a simple email from .NET Windows Form.
C#, VB\HtmlMail Send text/html email using Web Browser Control Editor
C#, VB\Mass Send mass emails using thread pool.
C#, VB\Oauth Send email using Gmail/Office365/Hotmail OAUTH/XOAUTH2.

Microsoft Store App (UAP)

C#, VB\Simple Send text/plain or html email from Microsoft Store App (UAP).
C#, VB\Mass Send mass emails using thread pool from Microsoft Store App (UAP).
C#, VB\GmailOauth Send email using Gmail OAUTH/XOAUTH2.

Windows CE/PocketPC

C#, VB\pocketpc.mobile Send a simple email from .NET Compact Framework.

PowerShell

PowerShell Tutorial and Sample

Free Email Support

Not enough? Please contact our technical support team.

Support@EmailArchitect.NET

Remarks

We usually reply emails in 24hours. The reason for getting no response is likely that your smtp server bounced our reply. In this case, please try to use another email address to contact us. Your Gmail, Hotmail email account is recommended.

Appendix

Comments

If you have any comments or questions about above example codes, please click here to add your comments.