Send-MailMessage: отправка почты из PowerShell
Для отправки писем через smtp сервер в PowerSHell можно использовать командлет Send-MailMessage. Данный встроенный командлет доступен для отправки почтовых email сообщений в PowerShell начиная с версии 2.0 (командлет применяется вместо класса .Net System.Net.Mail). В этой статье мы рассмотрим, как использовать Send-MailMessage для отправки писем из скриптов PowerShell.
Для получения базовой информации о синтаксисе командлета, выполните команду:
- From – адрес отправителя (не обязательно указывать реально существующий адрес. Если SMTP сервер не проверяет адрес отправителя, то можно отправить письмо от имени любого email адреса);
- To – email адрес получателя;
- SMTPServer – адрес SMTP сервера , через который нужно выполнить отправку письма
Следующая простейшая команда PowerShell отправит письмо с указанной темой (Subject) и содержимым (Body) нескольким получателям.
Send-MailMessage -From ‘server@winitpro.ru’ -To ‘admin@winitpro.ru’,’manager@winitpro.ru’ -Subject «Alert from Server1» -Body «It is email body» –SmtpServer ‘smtp.winitpro.ru’
Для удобства редактирования эту команду отправки можно представить так:
Send-MailMessage `
-SmtpServer smtp.winitpro.ru `
-To ‘admin@winitpro.ru’,’manager@winitpro.ru’ `
-From ‘server@winitpro.ru’ `
-Subject «test» `
-Body «Тема письма на русском» `
-Encoding ‘UTF8’
Обратите, что в последней команде мы дополнительно указали, что нужно использовать для письма кодировку UTF8. Иначе, если тема или текст письма будут содержать русские буквы, то они будут отображены знаками вопроса.
По умолчанию командлет Send-MailMessage пытается выполнить отправку письма через стандартный SMTP порт TCP 25. Если ваш smtp сервер позволяет отправить письмо только по шифрованному протоколу, можно указать номер порта (чаще всего это 465 или 587) и опцию UseSsl:
-SmtpServer ‘smtp.winitpro.ru’ -Port 465 –UseSsl
Название | Адрес SMTP сервера | Порт | Тип шифрования |
Yandex | smtp.yandex.ru | 465 | TLS/SSL |
Mail.ru | smtp.mail.ru | 465 | TLS/SSL |
Gmail | smtp.gmail.com | 587 SSL | |
Office 365 | smtp.office365.com | 587 | TLS |
Outlook.com | smtp-mail.outlook.com | 587 | TLS |
Если SMTP сервер запрещает анонимную отправку (запрещен relay), то при попытке отправить письмо вы получите ошибку: 5.7.1 Client was not authenticated .
В этом случае вы можете аутентифицироваться на SMTP сервере с помощью параметра –Credential.
Можно запросить данные пользователядля аутентификации интерактивно:
Send-MailMessage …… -Credential (Get-Credential)
Можно указать учетную запись для авторизации через переменную:
$cred = Get-Credential
Send-MailMessage . -Credential $cred
Если же вам нужно сохранить пароль для подключения к smtp серверу непосредственно в коде скрипта PowerShell, используйте такую конструкцию:
$mypasswd = ConvertTo-SecureString «$trongPass1» -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential («username», $mypasswd)
Send-MailMessage . –Credential $mycreds
Если нужно добавить в письмо вложение, используйте параметр –Attachments. В следующем примере мы отправим письмо в формате HTML и прикрепим к письму файлы report1.txt и report2.txt с локального диска:
$MailMessage = @<
To = «admin@winitpro.ru
Bcc = «manager@winitpro.ru», «manager2@winitpro.ru»
From = «DC server «
Subject = «Отчет с сервера DC»
Body = «
Добро пожаловать!
Сформировано: $(Get-Date -Format g)
”
Smtpserver = «smtp.winitpro.ru»
Port = 25
UseSsl = $false
BodyAsHtml = $true
Encoding = “UTF8”
Attachment = “C:\ps\report1.txt”, “C:\ps\report2.txt”
>
Send-MailMessage @MailMessage -Credential $cred
Вот как выглядит это письмо с HTML форматированием и вложениями в интерфейсе Outlook.
Можно настроить для письма уведомление о доставке с помощью параметра
-DeliveryNotificationOption . Возможные значения:
- OnSuccess (отчет при удачной доставке);
- OnFailure (отчет если доставка не выполнена);
- Delay (оповестить, если доставка отложена).
Send-Mail Message
Sends an email message.
Syntax
Description
The Send-MailMessage cmdlet sends an email message from within PowerShell.
You must specify a Simple Mail Transfer Protocol (SMTP) server or the Send-MailMessage command fails. Use the SmtpServer parameter or set the $PSEmailServer variable to a valid SMTP server. The value assigned to $PSEmailServer is the default SMTP setting for PowerShell. For more information, see about_Preference_Variables.
The Send-MailMessage cmdlet is obsolete. This cmdlet does not guarantee secure connections to SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do not use Send-MailMessage . For more information, see Platform Compatibility note DE0005.
Examples
Example 1: Send an email from one person to another person
This example sends an email message from one person to another person.
The From, To, and Subject parameters are required by Send-MailMessage . This example uses the default $PSEmailServer variable for the SMTP server, so the SmtpServer parameter is not needed.
The Send-MailMessage cmdlet uses the From parameter to specify the message’s sender. The To parameter specifies the message’s recipient. The Subject parameter uses the text string Test mail as the message because the optional Body parameter is not included.
Example 2: Send an attachment
This example sends an email message with an attachment.
The Send-MailMessage cmdlet uses the From parameter to specify the message’s sender. The To parameter specifies the message’s recipients. The Subject parameter describes the content of the message. The Body parameter is the content of the message.
The Attachments parameter specifies the file in the current directory that is attached to the email message. The Priority parameter sets the message to High priority. The -DeliveryNotificationOption parameter specifies two values, OnSuccess and OnFailure. The sender will receive email notifications to confirm the success or failure of the message delivery. The SmtpServer parameter sets the SMTP server to smtp.fabrikam.com.
Example 3: Send email to a mailing list
This example sends an email message to a mailing list.
The Send-MailMessage cmdlet uses the From parameter to specify the message’s sender. The To parameter specifies the message’s recipients. The Cc parameter sends a copy of the message to the specified recipient. The Bcc parameter sends a blind copy of the message. A blind copy is an email address that is hidden from the other recipients. The Subject parameter is the message because the optional Body parameter is not included.
The Credential parameter specifies a domain administrator’s credentials are used to send the message. The UseSsl parameter specifies that Secure Socket Layer (SSL) creates a secure connection.
Parameters
Specifies the path and file names of files to be attached to the email message. You can use this parameter or pipe the paths and file names to Send-MailMessage .
Type: | String [ ] |
Aliases: | PsPath |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the email addresses that receive a copy of the mail but are not listed as recipients of the message. Enter names (optional) and the email address, such as Name .
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the content of the email message.
Type: | String |
Position: | 2 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies that the value of the Body parameter contains HTML.
Type: | SwitchParameter |
Aliases: | BAH |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the email addresses to which a carbon copy (CC) of the email message is sent. Enter names (optional) and the email address, such as Name .
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies a user account that has permission to perform this action. The default is the current user.
Type a user name, such as User01 or Domain01\User01. Or, enter a PSCredential object, such as one from the Get-Credential cmdlet.
Credentials are stored in a PSCredential object and the password is stored as a SecureString.
For more information about SecureString data protection, see How secure is SecureString?.
Type: | PSCredential |
Position: | Named |
Default value: | Current user |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the delivery notification options for the email message. You can specify multiple values. None is the default value. The alias for this parameter is DNO.
The delivery notifications are sent to the address in the From parameter.
The acceptable values for this parameter are as follows:
- None : No notification.
- OnSuccess : Notify if the delivery is successful.
- OnFailure : Notify if the delivery is unsuccessful.
- Delay : Notify if the delivery is delayed.
- Never : Never notify.
These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the DeliveryNotification parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values.
Type: | DeliveryNotificationOptions |
Aliases: | DNO |
Accepted values: | None, OnSuccess, OnFailure, Delay, Never |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the type of encoding for the target file. The default value is utf8NoBOM .
The acceptable values for this parameter are as follows:
- ascii : Uses the encoding for the ASCII (7-bit) character set.
- bigendianunicode : Encodes in UTF-16 format using the big-endian byte order.
- oem : Uses the default encoding for MS-DOS and console programs.
- unicode : Encodes in UTF-16 format using the little-endian byte order.
- utf7 : Encodes in UTF-7 format.
- utf8 : Encodes in UTF-8 format.
- utf8BOM : Encodes in UTF-8 format with Byte Order Mark (BOM)
- utf8NoBOM : Encodes in UTF-8 format without Byte Order Mark (BOM)
- utf32 : Encodes in UTF-32 format.
Beginning with PowerShell 6.2, the Encoding parameter also allows numeric IDs of registered code pages (like -Encoding 1251 ) or string names of registered code pages (like -Encoding «windows-1251» ). For more information, see the .NET documentation for Encoding.CodePage.
Type: | Encoding |
Aliases: | BE |
Accepted values: | ASCII, BigEndianUnicode, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 |
Position: | Named |
Default value: | UTF8NoBOM |
Accept pipeline input: | True |
Accept wildcard characters: | False |
The From parameter is required. This parameter specifies the sender’s email address. Enter a name (optional) and email address, such as Name .
Type: | String |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies an alternate port on the SMTP server. The default value is 25, which is the default SMTP port.
Type: | Int32 |
Position: | Named |
Default value: | 25 |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the priority of the email message. Normal is the default. The acceptable values for this parameter are Normal, High, and Low.
Type: | MailPriority |
Accepted values: | Normal, High, Low |
Position: | Named |
Default value: | Normal |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies additional email addresses (other than the From address) to use to reply to this message. Enter names (optional) and the email address, such as Name .
This parameter was introduced in PowerShell 6.2.
Type: | String [ ] |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Specifies the name of the SMTP server that sends the email message.
The default value is the value of the $PSEmailServer preference variable. If the preference variable is not set and this parameter is not used, the Send-MailMessage command fails.
Type: | String |
Aliases: | ComputerName |
Position: | 3 |
Default value: | $PSEmailServer |
Accept pipeline input: | True |
Accept wildcard characters: | False |
The Subject parameter isn’t required. This parameter specifies the subject of the email message.
Type: | String |
Aliases: | sub |
Position: | 1 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
The To parameter is required. This parameter specifies the recipient’s email address. If there are multiple recipients, separate their addresses with a comma ( , ). Enter names (optional) and the email address, such as Name .
Type: | String [ ] |
Position: | 0 |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
The Secure Sockets Layer (SSL) protocol is used to establish a secure connection to the remote computer to send mail. By default, SSL is not used.
Type: | SwitchParameter |
Position: | Named |
Default value: | None |
Accept pipeline input: | True |
Accept wildcard characters: | False |
Inputs
You can pipe the path and file names of attachments to Send-MailMessage .