因此,如果我手动将电子邮件地址添加到$Mail.To = ("XYZ@xxx.com")
,则下面的代码可以正常工作,但是一旦我将其禁用,然后从excel列( mgremail )中提取,它就会出现此错误< / p>
There must be at least one name or contact group in the To, Cc, or Bcc box.At C:\Users\pshivam\Desktop\Scripts\test.ps1:60 char:5
+ $Mail.Send()
+ ~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
我的代码:
Import-Module ac*
$csv = Import-Csv C:\Users\pshivam\Desktop\Scripts\User.csv
$password = ConvertTo-SecureString -String “Newuser1” -AsPlainText -Force
foreach($item in $csv){
$mgrmail = $item.mgremail
$sam =$item.Username
$displayname = (Get-ADUser $sam -Properties displayname).displayname
##name
$nameTitle = "Name: "
$Name = (Get-ADUser $sam -Properties cn).name
#upn
$upnTitle = "User Logon: "
$UPN = (Get-ADUser $sam -Properties userprincipalname).userprincipalname
$ol = New-Object -comObject Outlook.Application
$mail = $ol.createItem(0)
$Mail.To=($mgrmail)
#$Mail.To=("XYZ@xxx.com")
$Mail.Subject="TEST"
$Mail.Body = "Hi,
"+ $nameTitle, $displayname, "
" + $upnTitle, $upn + "
TEST
"
$Mail.Send()
}
答案 0 :(得分:2)
我曾经写过一个脚本,这个脚本被一级团队用来在他们帮助最终用户时为他们生成电子邮件。它没有发送电子邮件(出于工作流程的原因),但它很容易发送。这至少应该为您提供一些可以自动添加收件人到电子邮件的内容。
$Outlook = New-Object -ComObject Outlook.Application
$MailItem = $Outlook.CreateItem(0)
$MailItem.GetInspector.Activate()|Out-Null
$Signature = $MailItem.HTMLBody
$CCAddr = $MailItem.Recipients.add($User.email)
$CCAddr.Type = 2
$CCAddr.Resolve()|Out-Null
$MailItem.Recipients|?{$_.Type -eq 1}|%{$_.Delete()}
$ToAddr = $MailItem.Recipients.add($Item.MgrEmail)
$ToAddr.Resolve()|Out-Null
$MailItem.Subject="Task description"
$MailItem.SentOnBehalfOfName='Team DL'
$MailItem.HTMLBody = $HTMLBody + $Signature
$MailItem.GetInspector.Activate()|Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($Outlook) | Out-Null
Remove-Variable Outlook,MailItem
我已在此处定义了一个字符串,其中包含以前在脚本中$HTMLBody
的电子邮件正文的HTML。这将打开一封新电子邮件,初始化它,将团队的分发列表添加到CC行,将用户添加到收件人行(更新以反映您的$Item.MgrEmail
),设置电子邮件的发送者身份所以它来自团队的DL,并保留用户的签名。它工作得很好,除了GUI中的“发送为”选项没有准确反映我设置要发送的电子邮件的值(它仍然正常发送,从他们的DL,它只是在GUI中显示他们的个人别名)。
你显然可以省略一些东西,但我想我会提供这个,因为我使用它并知道它有效。
答案 1 :(得分:0)
非常复杂的代码示例。这里更简单:
code
答案 2 :(得分:0)
尝试使用简单的SMTP发送:
$smtpserver="smtp server"
$from = "email address"
$to = "email address"
$subject = "subject"
$body = "What ever you want...."
$secpasswd = ConvertTo-SecureString “password” -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ($from, $secpasswd)
Send-MailMessage -smtpServer $smtpserver -Credential $creds -Usessl true -from $from -to $to -subject $subject -attachment $body