使用 "Send As" 发送邮件或更改发件人

Send mail with "Send As" or change sender

我正在制作一个脚本来自动化 Outlook 2016。我有一个帐户有两个来自客户的不同收件箱。

在脚本末尾,我需要使用脚本 运行 来自的收件箱名称发送一封电子邮件。我有权以两个收件箱的名义发送电子邮件,但我无法让脚本执行此操作。我post我的实际代码:

代码:

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 = client2@mail.com
$buzon = inbox1@mail.com
$inc = 000000001
$subject = "Automat request"
Send-Email -desde $desde -subject $asunto -buzon $Buzon1 -inc $inc

您的问题看起来是:

  1. 对象定义在它正在使用的函数之外:

    $Outlook = New-Object -ComObject Outlook.Application
    
  2. 变量中未加引号的字符串:

    $desde = client2@mail.com
    $buzon = inbox1@mail.com
    $inc = 000000001
    
  3. 单双引号混搭

    • 我建议阅读 about_quoting_rules 以了解差异,因为这在字符串中使用变量时非常重要。
  4. 函数参数 $inc 定义有数据但未用于任何用途?

    • 如果不使用,建议将其删除。

不是特别的问题,但我已将此处的字符串 (@" "@) 更改为带换行符的普通字符串 (`r`n`)


解决问题并整理代码后:

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.To = $desde
    $mail.Send()
    Start-Sleep 3
}

$desde = 'client2@mail.com'
$subject = 'Automat request'
$buzon = 'inbox1@mail.com'
$inc = '000000001'

Send-Email -desde $desde -subject $subject -buzon $buzon -inc $inc

我没有 Outlook 来测试代码,但通过 Outlook.Application 文档检查它现在似乎是有效的。

我终于使用了这条线并且效果很好:

$mail.SentOnBehalfOfName = "inbox1d@mail.com"
$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 = "inbox1d@mail.com"
    $mail.SendUsingAccount = $Outlook.Session.Accounts | where {$_.DisplayName -eq $FromMail}
    $mail.Send()
    Start-Sleep 3
}

$desde = 'client2@mail.com'
$subject = 'Automat request'
$buzon = 'inbox1@mail.com'
$inc = '000000001'

Send-Email -desde $desde -subject $subject -buzon $buzon -inc $inc