Send mail via Gmail with PowerShell V2's Send-MailMessage

前端 未结 13 2048
一生所求
一生所求 2020-11-30 21:07

I\'m trying to figure out how to use PowerShell V2\'s Send-MailMessage with Gmail.

Here\'s what I have so far.

$ss = New-Object Security         


        
13条回答
  •  萌比男神i
    2020-11-30 21:31

    I am really new to PowerShell, and I was searching about gmailing from PowerShell. I took what you folks did in previous answers, and modified it a bit and have come up with a script which will check for attachments before adding them, and also to take an array of recipients.

    ## Send-Gmail.ps1 - Send a gmail message
    ## By Rodney Fisk - xizdaqrian@gmail.com
    ## 2 / 13 / 2011
    
    # Get command line arguments to fill in the fields
    # Must be the first statement in the script
    param(
        [Parameter(Mandatory = $true,
                   Position = 0,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('From')] # This is the name of the parameter e.g. -From user@mail.com
        [String]$EmailFrom, # This is the value [Don't forget the comma at the end!]
    
        [Parameter(Mandatory = $true,
                   Position = 1,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('To')]
        [String[]]$Arry_EmailTo,
    
        [Parameter(Mandatory = $true,
                   Position = 2,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('Subj')]
        [String]$EmailSubj,
    
        [Parameter(Mandatory = $true,
                   Position = 3,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('Body')]
        [String]$EmailBody,
    
        [Parameter(Mandatory = $false,
                   Position = 4,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('Attachment')]
        [String[]]$Arry_EmailAttachments
    )
    
    # From Christian @ stackoverflow.com
    $SMTPServer = "smtp.gmail.com"
    $SMTPClient = New-Object Net.Mail.SMTPClient($SmtpServer, 587)
    $SMTPClient.EnableSSL = $true
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("GMAIL_USERNAME", "GMAIL_PASSWORD");
    
    # From Core @ stackoverflow.com
    $emailMessage = New-Object System.Net.Mail.MailMessage
    $emailMessage.From = $EmailFrom
    foreach ($recipient in $Arry_EmailTo)
    {
        $emailMessage.To.Add($recipient)
    }
    $emailMessage.Subject = $EmailSubj
    $emailMessage.Body = $EmailBody
    # Do we have any attachments?
    # If yes, then add them, if not, do nothing
    if ($Arry_EmailAttachments.Count -ne $NULL)
    {
        $emailMessage.Attachments.Add()
    }
    $SMTPClient.Send($emailMessage)
    

    Of course, change the GMAIL_USERNAME and GMAIL_PASSWORD values to your particular user and password.

提交回复
热议问题