IF EXISTS (SELECT * FROM sys.objects where object_id = OBJECT_ID(N'[dbo].[aps_Send_Mail_with_template]') AND OBJECTPROPERTY(object_id,N'IsProcedure') = 1)
DROP PROCEDURE [dbo].[aps_Send_Mail_with_template]
GO

SET ANSI_NULLS OFF
GO

SET QUOTED_IDENTIFIER OFF
GO

CREATE PROCEDURE [dbo].[aps_Send_Mail_with_template]
                 @in_job_type int = 1,
                 @in_param_sender varchar(8000)= null,
                 @in_param_sender_name varchar(8000) = null,
                 @in_param_recipient varchar(8000) = null,
                 @in_param_priority varchar(15) = null,
                 @in_param_subject varchar(8000) = null,
                 @in_param_message varchar(8000) = null,
                 @in_param_message_file varchar(8000) = null,
                 @in_param_attachments varchar(8000) = null,
                 @in_param_server varchar(255) = null,
                 @in_param_dbmail_profile_name varchar(255) = null,
                 @in_param_varchar_1 varchar (8000) = null,
                 @in_param_varchar_2 varchar (8000) = null,
                 @in_param_varchar_3 varchar (8000) = null
AS 
/*=========================================================================== 

  Procedure pour envoi d'un email 

  Parametres:

    @in_param_sender = adresse email de l'expediteur (ex: "cm@bmc.ch") (--> version SQL 2000 only)
    @in_param_sender_name (or NULL) = nom de l'expediteur (ex: "Christophe Marchand") (--> version SQL 2000 only)
    @in_param_recipient = adresse email du destinataire (ex: "info@bmc.ch")
    @in_param_priority (or NULL) = priorite (valeurs possibles: "LOW, NORMAL, HIGH")
    @in_param_subject (or NULL) = sujet du message
    @in_param_message (or NULL) = corps du message
    @in_param_message_file (or NULL) = corps du message contenu dans un fichier
    @in_param_attachments (or NULL) = pieces jointes (file1;file2;file3)
    @in_param_server = nom du serveur par lequel doit transiter l'email (--> version SQL 2000 only)
    @in_param_dbmail_profile_name = nom du profil de "Database Mail" a utiliser (--> version SQL 2005 only)
    @in_job_type = 0 -> envoi d'email sans template 
                   1/NULL -> envoi d'email pour echec de job 
                   2 -> envoi d'email pour succes de job
                   3 -> envoi d'email pour warning de job
                   4 -> envoi d'email pour message de job
                   10 -> envoi d'email pour infos du processus en cours
    @in_param_varchar_1 = contenu qui depend du template choisi ; nom du job SI job_type = 1 ou 2
    @in_param_varchar_2 = contenu qui depend du template choisi ; liste(s) de diffusion SI job_type = 1 ou 2
    @in_param_varchar_3 = contenu qui depend du template choisi ; ajout au corps du mail SI job_type = 1 ou 2
  Creation: 06.03.12 / PDE
 
  Modifications : 
    06.03.2012 / PDE : Creation
    13.07.2012 / PDE : Utilisation de la table DBA_Mailing_list
    03.12.2012 / PDE : modif liste emails de secours #pde01#
    13.12.2012 / PDE : Remplacement des ; par des , dans les destinataires, sinon ca echoue dans SQL 20005 #pde03#
    13.12.2012 / PDE : Debuggage de la modification precedente #pde04#
    22.08.2013 / PDE : #TFS19397# Ajout adresse IP dans le message #pde05#
    07.12.2013 / PDE : Mise en commentaire des TRY/CATCH, pour permettre l'appel depuis un trigger.
    07.12.2013 / PDE : Ajout job_type = 10 (mouchard)
    12.12.2013 / PDE : #TFS21035# Remise en place des TRY/CATCH, car sinon la SP echoue dans les environnements sans Arizona
    31.03.2015 / DVE : suppression du email de PDE  #dve01#
    15.07.2015 / FLA : correction bug quand un @DML_Code est identique à une adresse mail contenue dans @recipients #fla01#
    28.07.2015 / FLA : correction bug afin de pouvoir ajouter un _ devant l'adresse mail #fla02#
    01.12.2015 / FLA : modification de l'adresse d'envoi par défaut en _hci_dba@hcisolutions.ch #fla03#
    21.11.2016 / AFL : #TFS35792# Add cvSpecificCustomer 124 (coop)
    17.03.2020 / FLA : Suppression version SQL 2000
    09.02.2021 / SPE : #TFS62610# - Update all mail configurations to avoid SPAM
    16.03.2022 / FLA : Standardisation des mails
    13.07.2023 / SPE : OCTPDBA-690: Replace xp_cmdshell in [dbo].[aps_Send_Mail_with_template] stored procedure
    17.08.2023 / SPE : OCTPDBA-726: Replace mail profile name APSSQL_MAIL_PROFILE into AzureManagedInstance_dbmail_profile to be SQL managed instances compatible
============================================================================*/ 
 
SET NOCOUNT ON

DECLARE @result_sp               INT,
        @errno                   INT,
        @cpt_boucle              INT,
        @posPV_01                INT,
        @posPV_02                INT,
        @attachments             VARCHAR(MAX),
        @message_file            VARCHAR(MAX),
        @subject                 VARCHAR(MAX),
        @message                 VARCHAR(MAX),
        @recipients              VARCHAR(MAX),
        @recipients_temoin       VARCHAR(MAX),
        @DML_Recipients          VARCHAR(MAX),
        @EAD_email_address       VARCHAR(MAX),
        @cmd                     NVARCHAR(255),
        @job_name                VARCHAR(255),
        @DML_Code                VARCHAR(255),
        @errmsg                  VARCHAR(255),
        @dbmail_profile_name     VARCHAR(255),
        @priority                VARCHAR(30),
        @jobid                   UNIQUEIDENTIFIER

        
            

/* BUILD DETAILS OF THE EMAIL */

/* Get default mailbox profile name */
DECLARE @defaultprofilname varchar(100)
SELECT DISTINCT @defaultprofilname = p.name FROM msdb.dbo.sysmail_profile p JOIN msdb.dbo.sysmail_principalprofile pp ON pp.profile_id = p.profile_id AND pp.is_default = 1	

SET @in_param_dbmail_profile_name = @defaultprofilname

/* SET RECIPIENTS */
SELECT @recipients = isnull (@in_param_recipient, isnull (@in_param_varchar_2, ''))

IF EXISTS(SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DBA_Mailing_list]') AND OBJECTPROPERTY(object_id, N'IsUserTable') = 1)
BEGIN

  /* DECRYPTAGE DES DESTINATAIRES */
  SET @recipients_temoin = ''
  SET @cpt_boucle = 0

  WHILE @recipients_temoin <> @recipients and @cpt_boucle < 10
  BEGIN
    /* COMPTEUR DE BOUCLE, POUR COURT-CIRCUITER LES BOUCLES INFINIES */
    SET @cpt_boucle = @cpt_boucle + 1

    /* TEMOIN DU CHAMP DESTINATAIRE, POUR CONTINUER A FAIRE DES REMPLACEMENTS TANT QU'AU MOINS UN REMPLACEMENT A ETE EFFECTUE */
    SET @recipients_temoin = @recipients

    /* BOUCLE SUR LA TABLE DE CORRESPONDANCE DES LISTES DE DIFFUSION */
    DECLARE c_DML CURSOR LOCAL FORWARD_ONLY STATIC FOR
      SELECT DML_Code, isnull(DML_Recipients, '') + ';' /*#pde04#*/
        FROM DBA_Mailing_list with (nolock)
    OPEN c_DML
    FETCH NEXT FROM c_DML
      INTO @DML_Code, @DML_Recipients
    WHILE @@fetch_status <> -1
    BEGIN
      IF @@fetch_status <> -2
      BEGIN
        /*#fla01# */
        IF(CHARINDEX (@DML_Code,@recipients) <> 0)
          IF(SUBSTRING (@recipients,CHARINDEX (@DML_Code,@recipients)+LEN(@DML_Code),1) <> '@')
            SET @recipients = replace (@recipients, @DML_Code, @DML_Recipients)
            SET @recipients = replace (@recipients, ',', ';') /*#pde04#*/
            SET @recipients = replace (@recipients, ';;', ';')
            SET @recipients = replace (@recipients, ' ', '')
      END  /* if @@fetch_status <> -2 */

      FETCH NEXT FROM c_DML
        INTO @DML_Code, @DML_Recipients

    END /* while @@fetch_status <> -1 */ 

    CLOSE c_DML
    DEALLOCATE c_DML

  END /* @recipients_temoin <> @recipients and @@cpt_boucle < 10 */
END /* If exists (DBA_Mailing_list) */

/* EN CAS D'ABSENCE DE DESTINATAIRE, OU EN CAS D'ABSENCE DE CARACTERE @, ECRITURE D'ADRESSES EN DUR */
IF charindex ('@', @recipients) = 0
BEGIN
  SET @recipients = 'Gal_SE_DBA@galenica.com' /*#pde01#, #dve01# #fla03#*/
END

IF @in_job_type in (1, 2, 3, 4)
BEGIN
  /* EMAIL D'ECHEC/SUCCES DE JOB */
  IF @in_param_varchar_1 is not null
    SET @job_name = @in_param_varchar_1
  ELSE
  BEGIN
    SET @cmd = 'set @guid = cast(' + isnull (substring(app_name(), 30, 34), '') + ' as uniqueidentifier)'

    /* ATTENTION, CETTE LIGNE DE CODE PEUT GENERER UN WARNING QUAND ELLE N'EST PAS EXECUTEE PAR UN JOB */
    /* ERREUR TYPIQUE DANS UN LANCEMENT AVEC SQL STUDIO : Incorrect syntax near 'Studio'. */
    EXEC sp_executesql @cmd, N'@guid uniqueidentifier out', @guid = @jobid OUT

    IF @jobid is not null
    BEGIN
      SELECT @job_name = name
        FROM msdb..sysjobs
       WHERE job_id = @jobid
    END
    ELSE
      SET @job_name = 'job inconnu ou appel hors d''un job'
  END
END

/* JOB FAILURE */
IF @in_job_type = 1
BEGIN
  SELECT @priority = isnull (@in_param_priority, 'HIGH'),
         @subject = isnull (@in_param_subject, 'Job ' + isnull (@job_name, '') + ' has failed.'),
        @message = isnull (@in_param_message, 'Job ' + isnull (@job_name, '') + ' has failed.')
END

/* JOB SUCCESS */
ELSE IF @in_job_type = 2
BEGIN
  SELECT @priority = isnull (@in_param_priority, 'LOW'),
         @subject = isnull (@in_param_subject, 'Job ' + isnull (@job_name, '') + ' successfull.'),
         @message = isnull (@in_param_message, 'Job ' + isnull (@job_name, '') + ' has succeeded.')
END

/* JOB WARNING */
ELSE IF @in_job_type = 3
BEGIN
  SELECT @priority = isnull (@in_param_priority, 'HIGH'),
         @subject = isnull (@in_param_subject, 'Job ' + isnull (@job_name, '') + ' : warning.'),
         @message = isnull (@in_param_message, 'Job ' + isnull (@job_name, '') + ' has sent a warning.')
END 

/* JOB MESSAGE */
ELSE IF @in_job_type = 4
BEGIN
  SELECT @priority = isnull (@in_param_priority, 'LOW'),
         @subject = isnull (@in_param_subject, 'Job ' + isnull (@job_name, '') + ' : message.'),
         @message = isnull (@in_param_message, 'Job ' + isnull (@job_name, '') + '.')
END

/* SPY MESSAGE */
ELSE IF @in_job_type = 10
BEGIN
  SELECT @subject = isnull (@in_param_subject,'Spy message')
  SELECT @message = 'This email is being sent by ' + char(10) + char(13) + 'the SPID ['
             + convert (varchar (10), isnull(p.session_id, 'NULL'))
             + '], ' + char(10) + char(13) + 'of the instance ['
             + @@SERVERNAME
             + '], ' + char(10) + char(13) + 'run by the program ['
             + ltrim(rtrim(isnull(p.program_name, 'NULL')))
             + '] ' + char(10) + char(13) + 'on the host ['
             + ltrim(rtrim(isnull(p.host_name, 'NULL')))
             + '] ' + char(10) + char(13) + 'as user ['
             + ltrim(rtrim(isnull(p.login_name, 'NULL')))
             + '] ' + char(10) + char(13) + 'on the database ['
             + ltrim(rtrim(isnull(db.name, 'NULL')))
             + '].'
   from master.sys.dm_exec_sessions p with (nolock)
   left join sysdatabases db with (nolock)
      on db.dbid = p.database_id
       where p.session_id = @@spid
END
ELSE /* UNKNOWN JOB TYPE */
BEGIN
  SELECT @priority = isnull (@in_param_priority, 'NORMAL'),
         @subject = isnull (@in_param_subject, 'Message'),
         @message = isnull (@in_param_message, 'Message sent by [' + @@SERVERNAME + '].')
END

/* ADDITIONAL INFO FOR EMAIL MESSAGE */
IF ISNULL(@in_param_varchar_3, '') <> ''
BEGIN
  SET @message = isnull (@message , '') + char(13) + char(13) + isnull (@in_param_varchar_3, '')
END

SET @message = isnull (@message, '') + '


/*------------------------- */
Destinataires de l''email : 
' + replace (isnull (@recipients, ''), ';', '  ' + CHAR(13)) +
'
'

/* SEND EMAIL */
SELECT @recipients = isnull (@in_param_recipient, @recipients),
       @priority = isnull (@in_param_priority, @priority),
       @subject = isnull (@in_param_subject, @subject),
       @message_file = isnull (@in_param_message_file, @message_file),
       @attachments = isnull (@in_param_attachments, @attachments),
       @dbmail_profile_name = isnull (@in_param_dbmail_profile_name, @dbmail_profile_name)

SET @recipients = REPLACE(@recipients, ',', ';') /*#pde04#*/
SET @recipients = REPLACE(@recipients, ' ', '') /*#pde04#*/

/* Nettoyage de liste d'emails */
BEGIN /*#pde04#*/
  DECLARE @Email_address TABLE
          (
             Email_address_id int identity,
             EAD_email_address varchar (1000)
          )

  SET @posPV_01 = 0
  SET @posPV_02 = 0

  WHILE @recipients is not null 
    AND @posPV_02 < LEN (@recipients)
  BEGIN
    SET @posPV_01 = @posPV_02
    SET @posPV_02 = charindex (';',@recipients, @posPV_02+1)
    
    IF @posPV_02 is null OR @posPV_02 = 0
      SET @posPV_02 = LEN (@recipients)

    INSERT INTO @Email_address 
    VALUES(substring(@recipients, @posPV_01+1, @posPV_02-@posPV_01))
  END /*while*/

  /* NETTOYAGE */
  UPDATE @Email_address
     SET EAD_email_address = replace (EAD_email_address, ';', '')

  /* #fla02# */
  DELETE @Email_address
   WHERE EAD_email_address not like '[_a-z0-9]%[a-z0-9]@[a-z0-9]%[a-z0-9].[a-z09]%[a-z0-9]'

  UPDATE @Email_address
     SET EAD_email_address = EAD_email_address + ';'

  /* CONSTRUCTION DE LA CHAINE DE CARACTERES AVEC LES ADRESSES EMAILS */
  SET @recipients = ''

  DECLARE c_EAD CURSOR LOCAL FORWARD_ONLY STATIC FOR
    SELECT EAD_email_address
      FROM @Email_address
  ORDER BY Email_address_id
  OPEN c_EAD
  FETCH NEXT FROM c_EAD
    INTO @EAD_email_address
  WHILE @@fetch_status <> -1
  BEGIN
    IF @@fetch_status <> -2
    BEGIN
      SET @recipients = @recipients + @EAD_email_address
    END  /* if @@fetch_status <> -2 */

    FETCH NEXT FROM c_EAD
      INTO @EAD_email_address

  END /* while @@fetch_status <> -1 */ 

  CLOSE c_EAD
  DEALLOCATE c_EAD

END

SET @message = isnull (@in_param_message, @message)

BEGIN TRY
      EXEC @result_sp = aps_Send_Mail
            @in_recipient = @recipients,
            @in_priority = @priority,
            @in_subject = @subject,
            @in_message = @message,
            @in_message_file = @message_file,
            @in_attachments = @attachments,
            @in_dbmail_profile_name = @dbmail_profile_name

END TRY
BEGIN CATCH
  SET @result_sp = -1
END CATCH

/* ---- VERSION LA PLUS SIMPLE POUR L'ENVOI DE MAIL ---- */
IF @result_sp <> 0
BEGIN
      SET @subject = @subject + ' - [' + @@SERVERNAME + ']'
      EXEC @result_sp = msdb.dbo.sp_send_dbmail
              @profile_name = @dbmail_profile_name,
              @recipients = @recipients,
              @subject = @subject,
              @body = @message,
              @importance = @priority,
              @file_attachments = @attachments
END

IF @result_sp <> 0
BEGIN
      SET @errno = 70003
      SET @errmsg = '(APS) Error executing aps_Send_Mail in aps_Send_Mail_with_template.'
      GOTO error_99 
END


/*------------------------- Retour a la SP appelante ------------------------*/
RETURN(@@error)

/*-------------------------- Traitement des erreurs -------------------------*/ 
error_99: 
  RAISERROR (@errno, -1, -1, @errmsg);
  RETURN(@errno)

GO
