Powershell Send .csv files in a folder using Gmail

491 views Asked by At

I realize this question has been asked before, but I have not been able to find a solution using the related questions.

I am trying to send two .csv files using Powershell to a gmail account ([email protected]), using credentials from another gmail account([email protected]). I have turned on the Less Secure Apps feature for both accounts, but am getting the following error when trying to run my script:

> Exception calling "Send" with "1" argument(s): "The SMTP server
> requires a secure connection or the client was not  authenticated. The
> server response was: 5.7.0 Authentication Required. Learn more at" At
> C:\users\luke\downloads\EmailTest.ps1:37 char:1
> + $smtp.Send($msg)
>     + CategoryInfo: NotSpecified: (:) [], MethodInvocationException
>     + FullyQualifiedErrorId : SmtpException

My script:

#Connection Details
$username="[email protected]"
$password="senderpassword"
$smtpServer = “smtp.gmail.com”
$msg = new-object Net.Mail.MailMessage

#Change port number for SSL to 587

$smtp = New-Object Net.Mail.SmtpClient($smtpServer, 587) 

#Uncomment Next line for SSL  
$smtp.EnableSsl = $true

$smtp.Credentials = New-Object System.Net.NetworkCredential($username, $password)

#From Address
$msg.From = "[email protected]"
#To Address, Copy the below line for multiple recipients
$msg.To.Add(“[email protected]”)

#Message Body
$msg.Body=”Please See Attached Files”

#Message Subject
$msg.Subject = “Email with Multiple Attachments”

#your file location
$files=Get-ChildItem “C:\Users\luke\Daily Stats\”

Foreach($file in $files)
{
Write-Host “Attaching File :- ” $file
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList $file.FullName
$msg.Attachments.Add($attachment)

}
$smtp.Send($msg)
$attachment.Dispose();
$msg.Dispose();

All help is greatly appreciated!

0

There are 0 answers