Search code examples
powershellpowershell-4.0outlook-2016email-address

Send mail with "Send As" or change sender


I'm making a script to automate Outlook 2016. I have one account with two different inboxes from clients.

At the end of the script, I need to send an email from the name of the inbox the script is run from. I'm authorized to send email in the name of both inboxes, but I can't get the script to do it. I post my actual code:

The code:

Function Send-Email {
    param ([String]$desde,[String]$subject,[String]$buzon,[String]$inc)


$mail = $Outlook.CreateItem(0)
$firma ="
Textplan
"

$mail.subject = "Closed Ticket "+$subject
[String]$cuerpo =@"
Dear colleague,

bla bla bla

Thank you.
"@

$mail.sender = $buzon
$mail.body = $cuerpo+" "+$firma 
$mail.To = $desde
$mail.Send()
Start-Sleep 3

}

$Outlook = New-Object -ComObject Outlook.Application
$desde = [email protected]
$buzon = [email protected]
$inc = 000000001
$subject = "Automat request"
Send-Email -desde $desde -subject $asunto -buzon $Buzon1 -inc $inc

Solution

  • I finally used this lines and work well:

    $mail.SentOnBehalfOfName = "[email protected]"
    $mail.SendUsingAccount = $Outlook.Session.Accounts | where {$_.DisplayName -eq $FromMail}
    
    Function Send-Email {
        param (
            [String]$desde,
            [String]$subject,
            [String]$buzon,
            [String]$inc
        )
    
        $firma = 'Textplan'
        $cuerpo = "Dear colleague,`r`nbla bla bla`r`nThank you."
    
        $Outlook = New-Object -ComObject Outlook.Application
        $mail = $Outlook.CreateItem(0)
        $mail.subject = 'Closed Ticket ' + $subject
        $mail.sender = $buzon
        $mail.body = "$cuerpo $firma"
        $mail.SentOnBehalfOfName = "[email protected]"
        $mail.SendUsingAccount = $Outlook.Session.Accounts | where {$_.DisplayName -eq $FromMail}
        $mail.Send()
        Start-Sleep 3
    }
    
    $desde = '[email protected]'
    $subject = 'Automat request'
    $buzon = '[email protected]'
    $inc = '000000001'
    
    Send-Email -desde $desde -subject $subject -buzon $buzon -inc $inc