viernes, 29 de marzo de 2019

sp_send_dbmail - Attachment File is invalid

Cuando ejecutamos dbo.sp_send_dbmail dentro de un bloque de control de errores, observamos que el siguiente error no es capturado dentro del CATCH:

Msg 22051, Level 16, State 1, Line 0
Attachment file C:\test.xls is invalid.  

Una posible solución a este problema es controlar la existencia de los archivos antes de enviar el correo con xp_fileexist 

Ejemplo de código:

DECLARE @Attachments VARCHAR(MAX)
DECLARE @Attachment VARCHAR(8000)
DECLARE @AttachmentValid INT
DECLARE @DetailError VARCHAR(MAX)

SET @Attachments = 'a;sdf;32;34;3434'
SET @DetailError = ''

WHILE len(@Attachments) > 0
BEGIN
     SET @Attachment = left(@Attachments, charindex(';', @Attachments+';')-1)
     EXEC master.dbo.xp_fileexist @Attachment, @AttachmentValid OUTPUT  
     IF @AttachmentValid = 0 SET @DetailError = @DetailError + '[' + @Attachment + '] no es válido. '
     SET @Attachments = stuff(@Attachments, 1, charindex(';', @Attachments+';'), '')
END

1 comentario: