Проблема с электронной почтой Powershell - PullRequest
0 голосов
/ 08 марта 2019

Я использую этот код, и он отлично работает на моем ПК. Работает точно так, как я хочу, но когда я попытался протестировать его на компьютере конечного пользователя (на самом деле 2 пользователя), я получил сообщение об ошибке почти во всем, что касается Outlook. Я не уверен, почему я получаю эту ошибку на ПК других пользователей, но не на своем собственном. Это моя первая программа в Powershell, и она очень простая. Код еще не был очищен. Сначала я заставляю их работать, а затем убираю их.

$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)

$USEmail = "Example@example.com"

#Enter who the email will be sent to
$Mail.To = "Example@example.com"
$Mail.CC = "Example@example.com"


#email will be sent to the two above email address, Please insert ( email; email; email; ) in that format when adding new email addresses to list



#Get the users IP Address
$HostIP = (
    Get-NetIPConfiguration |
    Where-Object {
        $_.IPv4DefaultGateway -ne $null -and
        $_.NetAdapter.Status -ne "Disconnected"
    }
).IPv4Address.IPAddress
#end of code for IP address. This code is currently not being used in the program, as the IP address is not as necessary for computers with Teamviewer


#Setting up the variables that will hold the information to be displayed for helpdesk and usa it at the end of the email
$computerOS = Get-CimInstance CIM_OperatingSystem
$computerCPU = Get-CimInstance CIM_Processor
$computerSystem = Get-CimInstance CIM_ComputerSystem
$computerBIOS = Get-CimInstance CIM_BIOSElement

$SerialNum = "Serial Number: " + $computerBIOS.SerialNumber


$computerHDD = Get-CimInstance Win32_LogicalDisk -Filter "DeviceID = 'C:'"
Clear-Host

#Get the computer model and display it back in the email
$CompModel = (Get-WmiObject -Class:Win32_ComputerSystem).Model
#Get the computer name
$CompName = hostname
# All variables are hosted above.


#Gather user information and add it back to the email for IT 
$CompCPU = "CPU: " + $computerCPU.Name
$CompCap = "HDD Capacity: "  + "{0:N2}" -f ($computerHDD.Size/1GB) + "GB"
$CompSpace = "HDD Space: " + "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size) + " Free (" + "{0:N2}" -f ($computerHDD.FreeSpace/1GB) + "GB)"
$RamPerc = "RAM: " + "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB) + "GB"
$CompOS = "Operating System: " + $computerOS.caption + ", Service Pack: " + $computerOS.ServicePackMajorVersion
$loggedIn =  $computerSystem.UserName
$LastReboot = "Last Reboot: " + $computerOS.LastBootUpTime
$CompDate = (Get-Date).ToString('MM/dd/yyyy hh:mm:ss tt')


#Add Subject to the email
$Mail.Subject = "$loggedIn  Date: $CompDate" 
#end subject to email


#Link For Teamviewer
$TeamV = "http://download.teamviewer.com/download/version_11x/TeamViewerQS.exe"



#Start to the Body of the email
$Mail.HTMLBody ="<h1>Frutarom IT Help Request Form</h1>
<br>
Printer Name: 

<br><br>


Teamviewer ID: 
<br>
Teamviewer Password:
<br><br>
<strong>Download Teamviewer Below:</strong>
<br>
$TeamV
<br><br>
Brief Description of Issue: 


<br><br><br>
<h2>---------------------------------------------------------------------------------------------------------------------</h2><br>

<h4>Information For IT:</h4>
<br><br>
Computer Model: <i>$CompModel</i><br>
Computer Name: <i>$CompName</i> <br>
RAM: $RamPerc<br>
$SerialNum<br>
$CompCPU<br>
$CompCap <br>
$CompSpace <br>
$CompOS <br>
User logged In: $loggedIn <br>
$LastReboot <br>

"
#end of body of code, and all HTML that will be displayed in the body of the email





#Save the mail and open it for the user to be able to review and edit
$mail.save()
$inspector = $mail.GetInspector
$inspector.Display()

#end of code

введите описание изображения здесь

1 Ответ

0 голосов
/ 08 марта 2019

Есть ли у других пользователей настройка профиля outlook?Если установлен только внешний вид, но профиль не настроен, ваша вторая строка выдаст ошибку.

$Mail = $Outlook.CreateItem(0)

Я полагаю, что ваш подход не позволяет автоматически отправлять электронную почту, поэтому немного не уверен в вашемпоследний комментарий к коду или действительно требуется обзор.

#Save the mail and open it for the user to be able to review and edit...

Если обзор не нужен, то было бы быстрее / удобнее использовать встроенный командлет PowerShell

$MailBody = "<h1>Frutarom IT Help Request Form</h1>..."
Send-MailMessage -From 'Example01 <Example@example.com>' -To 'Example02 <Example@example.com>' -Subject "$loggedIn  Date: $CompDate"  -Body $Mailbody -BodyAsHtml # other parameters

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-6

Большой +: меньше головной боли в конце, так как нет перспективы, нет требований к профилю, чтобы ваш скрипт работал на любом ПК.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...