DECLARE @Command VARCHAR(MAX) = 'ALTER AUTHORIZATION ON DATABASE::[<<DatabaseName>>] TO [<<LoginName>>]'
SELECT @Command = REPLACE(REPLACE(@Command 
            , '<<DatabaseName>>', SD.Name)
            , '<<LoginName>>', SL.Name)
FROM master..sysdatabases SD 
JOIN master..syslogins SL ON  SD.SID = SL.SID
WHERE  SD.Name = DB_NAME()

--PRINT @Command
EXEC(@Command)
GO
DECLARE 
    @SQL varchar(200)

SELECT @SQL = 'ALTER DATABASE ['+DB_NAME()+'] SET TRUSTWORTHY ON;'
EXEC(@SQL)
GO
sp_configure 'clr enabled', 1;  
GO  
RECONFIGURE;  
GO
IF OBJECT_ID (N'dbo.SendSMTP') IS NOT NULL
  DROP FUNCTION dbo.SendSMTP
GO
IF EXISTS(SELECT name FROM SYS.assemblies WHERE name = 'SMTPCLR')
	DROP ASSEMBLY [SMTPCLR]
GO
CREATE ASSEMBLY [SMTPCLR]
AUTHORIZATION [dbo]
FROM 0x[encoded data, 76800 characters]
WITH PERMISSION_SET = UNSAFE 
GO
CREATE FUNCTION dbo.SendSMTP(
	@server			nvarchar(MAX),
	@port			nvarchar(MAX),
	@usermail		nvarchar(MAX),
	@password		nvarchar(MAX),
	@emailTo		nvarchar(MAX),
	@subject		nvarchar(MAX),
	@body			nvarchar(MAX),
	@copyTo			nvarchar(MAX),
	@files			nvarchar(MAX),
	@attach_name_1	nvarchar(max),
	@attach_file_1	varbinary(max),
	@attach_name_2	nvarchar(max),
	@attach_file_2	varbinary(max),
	@attach_name_3	nvarchar(max),
	@attach_file_3	varbinary(max),
	@attach_name_4	nvarchar(max),
	@attach_file_4	varbinary(max),
	@attach_name_5	nvarchar(max),
	@attach_file_5	varbinary(max)
)
RETURNS TABLE(Ok nvarchar(max), OkRef nvarchar(max))
AS EXTERNAL NAME SMTPCLR.SMTPCLR.EnvioMAIL
GO

