用于在powershell代码中从gmail帐户发送邮件的SSL凭据

时间:2015-07-17 07:36:50

标签: email powershell ssl

 $smtpServer = "smtp.gmail.com"
    $smtpport = "465"
    $username = "gmailid@gmail.com"
    $password = "gmailpassword"
    $smtp.EnableSSL = $true
    $smtp.credentials = New-Object System.Net.NetworkCredential($Username, $Password);
    $smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
    $msg = New-Object Net.Mail.MailMessage
    $msg.To.Add($user)
    $msg.From = "gmailid@gmail.com"
    $msg.Subject = "Local Environment DiskSpace Report for $titledate"
    $msg.IsBodyHTML = $true
    $msg.Body = get-content $diskReport
    $smtp.Send($msg)
    $body = ""

此处用户必须以其他方式定义,如

    $users = "scondgmailid@gmail.com"

但是当PowerShell bat文件的运行文件出错时:

    $smtp.EnableSSL = $true

    CategoryInfo : InvalidOperation:<:>[],RuntimeException 
    FullyQualifiedErrorId : PropertyNotFound 

同样的错误:

    $smtp.credentials = New-Object System.Net.NetworkCredential($Username, $Password);

请解决此问题。

1 个答案:

答案 0 :(得分:2)

首先新建对象,然后设置属性:

$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);

$smtp.EnableSSL = $true $smtp.credentials = New-Object System.Net.NetworkCredential($Username, $Password);
     $smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);