【问题标题】:Sending email through powershell issue通过PowerShell问题发送电子邮件
【发布时间】:2020-06-02 16:04:57
【问题描述】:

当我尝试通过 powershell 发送电子邮件时,我面临以下问题 1.我无法将发件人更改为群组邮箱 2.它不会读取我添加的附件,但会发送邮件。

代码即时使用:

    $Outlook = New-Object -ComObject Outlook.Application
    $Mail = $Outlook.CreateItem(0)
    $Mail.To = "xyz@outlook.com"
    $Mail.Subject = "sql"
    $mail.attachments = 'C:\Users\desktop.ini'
    $Mail.Body = ""
    $Mail.Send()

我收到错误:

     Property is read-only.
     At C:\Users\Documents\sending email.ps1:5 char:1
     + $mail.attachments = 'C:\Users\desktop.ini'
     + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     + CategoryInfo          : OperationStopped: (:) [], COMException
     + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

但是文件在我的本地

【问题讨论】:

  • 是否有理由使用 Outlook COM 对象而不是 Send-MailMessage?
  • 当我添加 smtp 和端口详细信息时,我的 Outlook 不允许我发送电子邮件。所以尝试了像这样的替代方法

标签: powershell email outlook


【解决方案1】:

您缺少一个附加参数

您的脚本应如下所示:

$attachment = "C:\Users\YourUser\Documents\test.txt"    
$mail.attachments.add($attachment)

或者,如果没有变量

$mail.attachments.add("C:\Users\YourUser\Documents\test.txt")

对于群邮箱,邮箱应该是可以控制的

$mail.sendusingaccount = "mailbox@company.com"

至于添加多个附件,您必须将它们放在一个目录中:

$getfiles = Get-ChildItem "C:\Users\YourUser\Attachmentfolder\"
Foreach ($getfile in $getfiles) {
$mail.attachments.add($getfile.FullName)
}

【讨论】:

  • 那么它的价值是什么,我尝试了它,但遗憾的是无法让它为自己工作。但是,稍后进行一些研究,我建议您一般使用以下内容:send-mailmessage -smtpServer(服务器名或 IP)-来自 sender.name@domain.com -to @(recipient1@domain.com, recipient2@domain. com) -subject "Email Subject" -body "Email Body" 与普通的 Outlook 项目请求相比,SMTP 的工作方式就像一个魅力。 - 那也是我可以让它工作的方法。
  • 我很快就会给你添加另一个stackoverflow帖子:stackoverflow.com/questions/41149684/…你可以尝试第一个答案推荐的outlook-item脚本,但它对我不起作用。不过,这可能是我这边的其他问题。
  • 如何添加多个附件?
  • $mailobject.attachment.add 支持数组,所以做类似 $mail.attachments.add("C:Users\YourUser\Documents\test.txt","C:Users\YourUser\ Documents\test2.txt","C:Users\YourUser\Documents\test3.txt") 理论上应该可以工作。
  • 所以我研究了一下,发现只有 send-mailmessage cmdlet 接受其 -attachment 参数的数组。对此感到抱歉。但是,当然,我为您找到了一种解决方法,如您所见,我添加了该方法以使我的初始答案更加清晰。我希望这对你有用,因为它对我来说就像一种魅力。祝你好运!编辑:您需要从 foreach 循环之外删除 $mail.attachments.add($attachments)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-25
  • 2020-11-05
  • 2018-11-01
  • 2013-11-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多