Skip to content

Instantly share code, notes, and snippets.

@lumodino
Last active May 11, 2020 09:07
Show Gist options
  • Save lumodino/ded980af4e6aeedd6e855e6cde7a670b to your computer and use it in GitHub Desktop.
Save lumodino/ded980af4e6aeedd6e855e6cde7a670b to your computer and use it in GitHub Desktop.
Envío de correos múltiples personalizados con origen de datos de Active Directory (Get-ADUser) o CSV.
<#
.Synopsis
Envío de correos multiples personalizados con datos del usuario desde Active Directory
.DESCRIPTION
Permite enviar correos personalizados con datos del usuario desde una plantilla HTML previamente creada, incluyendo imágenes incrustadas.
Hace uso de la tubería de entrada desde cmdlet de AD Get-ADUser que tiene que suministrar todos los parámetros adicionales OtherMailBox y Mail para el envío de correo
"user1","user2" | Get-ADUser -properties Mail, Otermailbox
.EXAMPLE
"user1","user2" | get-aduser -Properties mail,othermailbox | Send-Mailing -HTMLTemplateFile "c:\PLANTILLASMAILINGPOWERSHELL\CONTENIDO DEL ASUNTO NOMBREDEPILA- APELLIDOUSUARIO - DIRECCIONDEEMAIL - DIRECCIONPRIVADADEEMAIL - SAMACCOUNTNAME.html" -ExternalMailCopy
.EXAMPLE
get-aduser -filter * | Send-Mailing -HTMLTemplateFile "c:\PLANTILLASMAILINGPOWERSHELL\Mensaje para todos los usuarios.html"
.EXAMPLE
get-adgroupmember vigilantes | get-aduser -Properties mail, othermailbox | send-mailing -HTMLTemplateFile "c:\PLANTILLASMAILINGPOWERSHELL\Envio a grupo vigilantes.html"
.EXAMPLE
get-adgroupmember vigilantes | OUT-GRIDVIEW -OUTPUT Multiple -Title "SELECCIONAR USUARIOS DEL GRUPO" | get-aduser -Properties mail,othermailbox | Send-Mailing -HTMLTemplateFile "\\ulagares.unirioja.loc\helpdesk\GUICAUR\PLANTILLASMAILINGPOWERSHELL\CONTENIDO DEL ASUNTO NOMBREDEPILA- APELLIDOUSUARIO - DIRECCIONDEEMAIL - DIRECCIONPRIVADADEEMAIL - SAMACCOUNTNAME.html"
.EXAMPLE
Import-Csv \\SERVIDOR\PLANTILLAS\CSVMANUAL.txt -Delimiter ";" | Send-Mailing -HTMLTemplateFile "\\SERVIDOR\PLANTILLAS\ENVIO DE DESTINATARIOS ARCHIVO CSV.html"
.EXAMPLE
get-aduser user1 -Properties mail, othermailbox | Send-Mailing -HTMLTemplateFile (Get-ChildItem \\servidor\PLANTILLASTHUNDERBIRD | Out-GridView -Title "SELECCIONA LA PLANTILLA DE CORREO A USAR" -OutputMode Single).FULLNAME
#>
Function Send-Mailing {
[CmdletBinding()]
Param(
[Parameter(ValueFromPipelineByPropertyName,Mandatory=$true)]
$samaccountname,
[Parameter(ValueFromPipelineByPropertyName,Mandatory=$false)]
$mail,
[Parameter(ValueFromPipelineByPropertyName,Mandatory=$false)]
$othermailbox,
[Parameter(ValueFromPipelineByPropertyName,Mandatory=$false)]
$givenname,
[Parameter(ValueFromPipelineByPropertyName,Mandatory=$true)]
$surname,
[Parameter(Mandatory=$true)]
[string]$HTMLTemplateFile,
[Parameter(Mandatory=$false)]
[switch]$SendMails,
[Parameter(Mandatory=$false)]
[switch]$ExternalMailCopy
)
begin {
Write-Output "INICIO DE FUNCION"
$LOG_DE_ENVIO = @()
if($SendMails){
$credencial_mailing = Get-Credential -Message "LOGIN OFFICE365 CON @dominio.xxx"
$mail365 = "smtp.office365.com"
$puerto365 = 587
$remitente = "soporte@soporte.com"
}
if(Test-Path $HTMLTemplateFile){
$ArchivoPlantilla = Get-ChildItem $HTMLTemplateFile
$AsuntoPlantilla = $ArchivoPlantilla.BaseName
Write-Output "ASUNTO: $AsuntoPlantilla"
[string]$cuerpohtmlPlantilla = Get-Content $ArchivoPlantilla.FullName
#write-output "ARCHIVO: $($ArchivoPlantilla.FullName)"
}
Write-Output " "
}
process {
Write-Output "PROCESO DE LA FUNCION POR CADA ELEMENTO..."
###################################
#SUSTITUCION DE CAMPOS EN PLANTILLA
###################################
#DIRECCIONDEEMAIL = MAIL
#SAMACOUNTNAME = SAMACCOUNTNAME
#DIRECCIONPRIVADADEEMAIL = OTHERMAILBOX
#NOMBREDEPILA = GIVENNAME
#APELLIDOSUSUARIO = SURNAME
###################################
$Asunto = $AsuntoPlantilla.replace("DIRECCIONDEEMAIL","$mail").replace("SAMACCOUNTNAME","$samaccountname").replace("DIRECCIONPRIVADADEEMAIL","$othermailbox").replace("NOMBREDEPILA","$givenname").replace("APELLIDOUSUARIO","$surname")
$Cuerpo = $cuerpohtmlPlantilla.replace("DIRECCIONDEEMAIL","$mail").replace("SAMACCOUNTNAME","$samaccountname").replace("DIRECCIONPRIVADADEEMAIL","$othermailbox").replace("NOMBREDEPILA","$givenname").replace("APELLIDOUSUARIO","$surname")
$destinatarios = @($mail)
#SI SE ACTIVA EL PARAMETRO DE COPIA EN CORREO EXTERNO
if($ExternalMailCopy){
#COMPROBAR SI HAY CORREO EXTERNO
if($null -eq $othermailbox){
#NO HAY CUENTA EXTERNA DONDE ENVIAR CORREO
Write-Output "NO HAY CUENTA EXTERNA PARA $givenname $surname $samaccountname"
$othermailbox = ""
$LOG_DE_ENVIO += "--ERROR-- NO HAY CUENTA EXTERNA PARA $givenname $surname $samaccountname"
}else{
#AÑADIDO SEGUNDO DESTINATARIO
$LOG_DE_ENVIO += "SEGUNDO DESTINATARIO $OTHERMAILBOX PARA $givenname $surname $samaccountname"
$destinatarios += $othermailbox
}
}
Write-Output "NOMBRE: $givenname $surname $samaccountname $mail $othermailbox"
Write-Output " "
IF($SendMails){
try{
Write-Output "ENVIANDO CORREO PARA $givenname $surname $samaccountname $destinatarios..."
$LOG_DE_ENVIO += "ENVIANDO CORREO PARA $givenname $surname $samaccountname $destinatarios..."
Send-MailMessage -From $remitente -To $destinatarios -Body $Cuerpo -Subject $Asunto -Credential $credencial_mailing -useSSL -smtpServer $mail365 -port $puerto365 -BodyAsHtml -Encoding UTF8
}
catch{
Write-Output "ERROR ENVIO CORREO PARA $givenname $surname $samaccountname $destinatarios"
$LOG_DE_ENVIO += "--ERROR-- ERROR ENVIO CORREO $givenname $surname $samaccountname $destinatarios"
}
}
}
end {
Set-Content -value $LOG_DE_ENVIO -path $env:HOMEPATH\Desktop\LOG-ENVIO.txt
Write-Output "ESCRITO LOG EN $env:HOMEPATH\Desktop\LOG-ENVIO.txt"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment