Send mail via gmail with PowerShell V2's Send-

2019-01-10 06:19发布

问题:

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.SecureString
foreach ($ch in "password".ToCharArray())
{
    $ss.AppendChar($ch)
}
$cred = new-object Management.Automation.PSCredential "uid@domain.com", $ss
Send-MailMessage    -SmtpServer smtp.gmail.com -UseSsl -Credential $cred -Body...

I get the following error

Send-MailMessage : The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn
 more at                              
At foo.ps1:18 char:21
+     Send-MailMessage <<<<      `
    + CategoryInfo          : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
    + FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage

Am I doing something wrong, or is Send-MailMessage not fully baked yet (I'm on CTP 3)?

Some additional restrictions

  1. I want this to be non-interactive, so get-credential won't work
  2. The user account isn't on the gmail domain, but an google apps registered domain
  3. For this question, I'm only interested in the Send-MailMessage cmdlet, sending mail via the normal .Net API is well understood.

回答1:

Just found this question .. here's my PowerShell Send-MailMessage Sample for Gmail.. Tested and working solution:

$EmailFrom = "notifications@somedomain.com"
$EmailTo = "me@earth.com" 
$Subject = "Notification from XYZ" 
$Body = "this is a notification from XYZ Notifications.." 
$SMTPServer = "smtp.gmail.com" 
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
$SMTPClient.EnableSsl = $true 
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("username", "password"); 
$SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)

Just change $EmailTo, and username/password in $SMTPClient.Credentials.. do not include @gmail.com in your username..

maybe this is a help for other coming across this question ..



回答2:

This should fix your problem

$credentials = new-object Management.Automation.PSCredential “mailserver@yourcompany.com”, (“password” | ConvertTo-SecureString -AsPlainText -Force)

Then use the credential in you call to Send-MailMessage -From $From -To $To -Body $Body $Body -SmtpServer {$smtpServer URI} -Credential $credentials -Verbose -UseSsl



回答3:

i just had the same problem and run into this post. It actually helped me to get it running with the native Send-MailMessage command-let and here is my code:

$cred = Get-Credential
Send-MailMessage ....... -SmtpServer "smtp.gmail.com" -UseSsl -Credential $cred -Port 587 

However, in order to have Gmail allowing me to use the SMTP server, i had to login into my gmail account and under this link https://www.google.com/settings/security set the "Access for less secure apps" to "Enabled". Then finally it did work!!

ciao marco



回答4:

I'm not sure you can change port numbers with Send-MailMessage since gmail works on port 587. Anyway, here's how to send email through gmail with .NET SmtpClient:

$smtpClient = new-object system.net.mail.smtpClient 
$smtpClient.Host = 'smtp.gmail.com'
$smtpClient.Port = 587
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = [Net.NetworkCredential](Get-Credential GmailUserID) 
$smtpClient.Send('GmailUserID@gmail.com','yourself@somewhere.com','test subject', 'test message')


回答5:

I used Christian's Feb 12 solution and I'm also just beginning to learn PowerShell. As far as attachments, I was poking around with Get-Member learning how it works and noticed that Send() has two definitions... the second definition takes a System.Net.Mail.MailMessage object which allows for Attachments and many more powerful and useful features like Cc and Bcc. Here's an example that has attachments (to be mixed with his above example):

# append to Christian's code above --^
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = $EmailFrom
$emailMessage.To.Add($EmailTo)
$emailMessage.Subject = $Subject
$emailMessage.Body = $Body
$emailMessage.Attachments.Add("C:\Test.txt")
$SMTPClient.Send($emailMessage)

Enjoy!



回答6:

This is a really late date in which to chime in here, but maybe this can help someone else.

I am really new to powershell and I was searching about gmailing from PS. I took what you folks did above, 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. I'm going to add some more error checking and stuff later, but I thought it might be good enough (and basic enough) to post here.

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



回答7:

After many tests and a long search for solutions. I found a functional and interesting script codes at http://www.powershellmagazine.com/2012/10/25/pstip-sending-emails-using-your-gmail-account/.

$param = @{
    SmtpServer = 'smtp.gmail.com'
    Port = 587
    UseSsl = $true
    Credential  = 'you@gmail.com'
    From = 'you@gmail.com'
    To = 'someone@somewhere.com'
    Subject = 'Sending emails through Gmail with Send-MailMessage'
    Body = "Check out the PowerShellMagazine.com website!"
    Attachments = 'D:\articles.csv'
}

Send-MailMessage @param

Enjoy



回答8:

On a Windows 8.1 Machine I got Send-MailMessage to send an email with an attachment through GMail using the following script:

$EmFrom = "user@gmail.com"    
$username = "user@gmail.com"    
$pwd = "YOURPASSWORD"    
$EmTo = "recipient@theiremail.com"    
$Server = "smtp.gmail.com"    
$port = 587    
$Subj = "Test"    
$Bod = "Test 123"    
$Att = "c:\Filename.FileType"    
$securepwd = ConvertTo-SecureString $pwd -AsPlainText -Force    
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $securepwd    
Send-MailMessage -To $EmTo -From $EmFrom -Body $Bod -Subject $Subj -Attachments $Att -SmtpServer $Server -port $port -UseSsl  -Credential $cred


回答9:

Send email with attachment using powershell -

      $EmailTo = "udit043.ur@gmail.com"  // abc@domain.com
      $EmailFrom = "udit821@gmail.com"  //xyz@gmail.com
      $Subject = "zx"  //subject
      $Body = "Test Body"  //body of message
      $SMTPServer = "smtp.gmail.com" 
      $filenameAndPath = "G:\abc.jpg"  //attachment
      $SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom,$EmailTo,$Subject,$Body)
      $attachment = New-Object System.Net.Mail.Attachment($filenameAndPath)
      $SMTPMessage.Attachments.Add($attachment)
      $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587) 
      $SMTPClient.EnableSsl = $true 
      $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("udit821@gmail.com", "xxxxxxxx");    // xxxxxx-password
      $SMTPClient.Send($SMTPMessage)


回答10:

Here it is

$filename = “c:\scripts_scott\test9999.xls”
$smtpserver = “smtp.gmail.com”
$msg = new-object Net.Mail.MailMessage
$att = new-object Net.Mail.Attachment($filename)
$smtp = new-object Net.Mail.SmtpClient($smtpServer )
$smtp.EnableSsl = $True
$smtp.Credentials = New-Object System.Net.NetworkCredential(“username”, “password_here”); # Put username without the @GMAIL.com or – @gmail.com
$msg.From = “username@gmail.com”
$msg.To.Add(”boss@job.com”)
$msg.Subject = “Monthly Report”
$msg.Body = “Good MorningATTACHED”
$msg.Attachments.Add($att)
$smtp.Send($msg)

Let me know if it helps you San also use the send-mailmessage also at Www.techjunkie.tv For that way also that I think is way better and pure to use



回答11:

I haven't used PowerShell V2 send-mailmessage, but I have used System.Net.Mail.SMTPClient class in V1 to send messages to a gmail account for demo purposes. This might be overkill but run an smtp server on my Vista laptop see this link, if you're in an enterprise you will already have a mail rely server and this step isn't necessary. Having an smtp server I'm able to send email to my gmail account with the following code:

$smtpmail = [System.Net.Mail.SMTPClient]("127.0.0.1")
$smtpmail.Send("myacct@gmail.com", "myacct@gmail.com", "Test Message", "Message via local smtp")


回答12:

I agree with Christian Muggli's solution, although at first I still got the error that Scott Weinstein reported. How you get past that is:

EITHER first login to gmail from the machine this will run on, using the account specified. (It is NOT necessary to add any google sites to Trusted Sites zone, even if Internet Explorer Enhanced Security Configuration is enabled.)

OR, on your first attempt, you will get the error, and your gmail acct will get a notice about suspicious login, so follow their instructions to allow future logins from the machine this will run on.



回答13:

check out this post for the way to send attachments with gmail Powershell Examples so that you can see how to send attachments using gmail Let me know if it helps you out Scott A www.techjunkie.tv