作为一个Exchange管理员,我们可能需要使用PowerShell脚本自动化的发送电子邮件。下面一起学习下如何使用PowerShell脚本在你的组织中发送SMTP电子邮件信息。

怎么做到这点呢?

PowerShell V2以及后续版本都提供了核心命令可以通过SMTP发送电子邮件信息。使用下面的语法可以发送一份电子邮件信息:

Send-MailMessage -To san.zhang@robin.com `

-From administrator@robin.com `

-Subject "Test E-mail" `

-Body "This is just a test" `

-SmtpServer mail.corp.robin.com

wKioL1TVkb3Rkin5AAD9XHwpUak140.jpg

使用张三的账号登陆OWA看看邮件信息:

wKiom1TVkM-SkRY7AAJ7Kryk4yQ080.jpg

那么脚本是如何执行的呢?

PowerShell V1Send-MailMessage命令是不存在的。在早期Exchange 2007 SP2PowerShell V2支持之前,我们需要引用.Net Framework里的System.Net.Mail类库去发送SMTP邮件信息。对于一般的管理员,因为没有编程经验,在使用.Net类还是比较困难的。好消息就是Send-MailMessage命令利用了这些相同的.Net类库,允许我们创建丰富的电子邮件,可以包含一个或多个附件,使用HTML格式化消息体,支持消息优先等级等等。下面列一下这些有用的参数:

可以使用帮助系统查看帮助信息:

Get-Help Send-MailMessage -full

参数

    -Attachments <String[]>

        Specifies the path and file names of files to be attached to the e-mail message. You can use this parameter or pipe the paths and file names to Send-MailMessage.

是否必需?                    False

位置?                        named

默认值               

是否接受管道输入?            true (ByValue)

是否接受通配符?              False

    -Bcc <String[]>

        Specifies the e-mail addresses that receive a copy of the mail but are not listed as recipients of the message.

         Enter names (optional) and the e-mail address, such as "Name <someone@example.com>".

是否必需?                    False

位置?                        named

默认值                None

是否接受管道输入?            false

是否接受通配符?              False

    -Body <String>

        Specifies the body (content) of the e-mail message.

是否必需?                    False

位置?                        3

默认值                None

是否接受管道输入?            false

是否接受通配符?              False

    -BodyAsHtml [<SwitchParameter>]

        Indicates that the value of the Body parameter contains HTML.

是否必需?                    False

位置?                        named

默认值                False

是否接受管道输入?            false

是否接受通配符?              False

    -Cc <String[]>

        Specifies the e-mail addresses to which a carbon copy (CC) of the e-mail message is sent. Enter names (optional

        ) and the e-mail address, such as "Name <someone@example.com>".

是否必需?                    False

位置?                        named

默认值                None

是否接受管道输入?            false

是否接受通配符?              False

    -Credential <PSCredential>

        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.

是否必需?                    False

位置?                        named

默认值                Current user

是否接受管道输入?            false

是否接受通配符?              False

    -DeliveryNotificationOption <DeliveryNotificationOptions>

        Specifies the delivery notification options for the e-mail message. You can specify multiple values. "None" is

        the default value.  The alias for this parameter is "dno".

        The delivery notifications are sent in an e-mail message to the address specified in the value of the To parame

        ter.

        Valid values are:

        -- 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.

是否必需?                    False

位置?                        named

默认值                "None"

是否接受管道输入?            false

是否接受通配符?              False

    -Encoding <Encoding>

        Specifies the encoding used for the body and subject. Valid values are ASCII, UTF8, UTF7, UTF32, Unicode, BigEn

        dianUnicode, Default, and OEM. ASCII is the default.

是否必需?                    False

位置?                        named

默认值                ASCII

是否接受管道输入?            false

是否接受通配符?              False

    -From <String>

        Specifies the address from which the mail is sent. Enter a name (optional) and e-mail address, such as "Name <s

        omeone@example.com>". This parameter is required.

        是否必需?                    True

位置?                        named

默认值                None

是否接受管道输入?            false

是否接受通配符?              False

    -Port <Int32>

        Specifies an alternate port on the SMTP server. The default value is 25, which is the default SMTP port. This p

        arameter is available in Windows PowerShell 3.0 and newer releases.

是否必需?                    False

位置?                        named

默认值                25

是否接受管道输入?            false

是否接受通配符?              False

    -Priority <MailPriority>

        Specifies the priority of the e-mail message. The valid values for this are Normal, High, and Low. Normal is th

        e default.

是否必需?                    False

位置?                        named

默认值                Normal.

是否接受管道输入?            false

是否接受通配符?              False

    -SmtpServer <String>

        Specifies the name of the SMTP server that sends the e-mail message.

        The default value is the value of the $PSEmailServer preference variable. If the preference variable is not set

         and this parameter is omitted, the command fails.

是否必需?                    False

位置?                        4

默认值                $PSEmailServer

是否接受管道输入?            false

是否接受通配符?              False

    -Subject <String>

        Specifies the subject of the e-mail message. This parameter is required.

是否必需?                    True

位置?                        2

默认值                None

是否接受管道输入?            false

是否接受通配符?              False

    -To <String[]>

        Specifies the addresses to which the mail is sent. Enter names (optional) and the e-mail address, such as "Name

         <someone@example.com>". This parameter is required.

是否必需?                    True

位置?                        1

默认值                None

是否接受管道输入?            false

是否接受通配符?              False

    -UseSsl [<SwitchParameter>]

        Uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer to send mail. By

        default, SSL is not used.

是否必需?                    False

位置?                        named

默认值                False

是否接受管道输入?            false

是否接受通配符?              False

更多示例参考如下:

当使用PowerShell发送电子邮件消息时,我们需要指定一个SMTP服务器以提交消息。除非在你的环境中使用恶劣某种类型的邮件中继服务器,那么你会希望使用你Exchange组织中的集线器传输服务器。但是,Exchange服务器时不允许工作站和不受信任的服务器中继邮箱消息。那么我们可以使用脚本让机器传递邮件。

PowerShell V2及后续版本中,提供了变量$PSEmailServer,可以分配一个SMTP服务器的名称或地址。当你定义这个变量,那么你在使用Send-MailMessage命令发送邮件时不需要使用SmtpServer参数,当然我们可以把变量赋值并加入到我们的配置文件中,那么将会持续保存在所有的Shell会话中。

发送带有附件的邮件

也许,你想编写一个脚本生成一个文本文件或CSV文件的报告通过电子邮件进行发送。那么我们可以结合使用Send-MailMessage命令,并加参数-Attachment指定附件。例如,我们先来看看怎么发送一个现有的文件作为邮件附件,然后再来看如何生成一个文件并通过邮件附件进行发送,先来看看怎么发送一个附件:

Send-MailMessage -To san.zhang@robin.com `

-From administrator@robin.com `

-Subject "Mailbox Report for $((Get-Date).ToShortDateString())" `

-Body "Please review the attached mailbox report." `

-Attachments c:\report01.csv `

-SmtpServer mail.corp.robin.com

wKioL1TVkb7zX3xcAADPr7hKJV4596.jpg

回到收件人邮箱查看信息,可以看到邮件中有了附件:

wKioL1TVkzmwCo1GAAHBq_VCB3A194.jpg

我们应该注意到,需要提供附件的路径和文件名到-Attachment参数。我们可以用逗号分隔文件发送多个文件:

wKiom1TVkM-BvGoaAAE5m5_YRko763.jpg

回到OWA看看信息,有三个附件:

wKioL1TVkb6jwkjYAAOoi0L8ESM909.jpg

发送命令输出信息到消息体中

上面的例子中,我们是先导出输出信息到一个文件,然后再把这个文件附加到邮件附件中进行发送。下面我们看一个例子如何将这些信息添加到电子邮件体中。在这个命令中,我们将发送组织架构中邮箱使用前10的信息。命令如下:

[string]$report = Get-MailboxDatabase |

Get-MailboxStatistics| ?{!$_.DisconnectDate} |

Sort-Object TotalItemSize -Desc |

Select-Object DisplayName,Database,TotalItemSize -First 10 |

ConvertTo-Html

Send-MailMessage -To san.zhang@robin.com `

-From administrator@robin.com `

-Subject "Mailbox Report for $((Get-Date).ToShortDateString())" `

-Body $report `

-BodyAsHtml `

-SmtpServer mail.corp.robin.com

wKiom1TVkM_ze_yWAAGlIgUjeYM095.jpg

看看邮件体:

wKioL1TVkb-gQT-rAAPgdy42CM8264.jpg

在这个例子中,我们应该注意到,我们将报告输出到一个变量$report中,而且将$report的类型强制为String类型,因为我们后续我们需要使用-body参数将这些信息附加到有邮件体中。你应该注意到这里使用了ConvertTo-Html命令将对象转换为一个HTML文档,我们可以将这些信息通过-BodyAsHtml开关参数发送这些报告信息到一个HMTL格式的邮件消息中。