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 (externalexample#gmail.com), using credentials from another gmail account(senderexample#gmail.com). 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="senderexample#gmail.com"
$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 = "senderexample#gmail.com"
#To Address, Copy the below line for multiple recipients
$msg.To.Add(“externalexample#gmail.com”)
#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!
Related
I tried to send an email with attachement to outlook (365) via powershell, like posted in this scriptlet:
$SmtpServer = "smtp.office365.com"
$SmtpPort = 587
$smtp = New-Object System.Net.Mail.SmtpClient($SmtpServer,$SmtpPort)
$MailMessage = New-Object system.net.mail.mailmessage
$attfile = "C:\temp\test.txt"
$attatchment = New-Object System.Net.Mail.Attachment($attfile)
$smtp.Host = "smtp.office365.com" #DNS oder IP
$MailMessage.From = "test***#outlook.de"
$MailMessage.To.Add("test***#outlook.de")
$MailMessage.Subject = "PowerShell Email with attatchemnt"
$MailMessage.Body ="This is a email from powershell with attatchments"
$MailMessage.IsBodyHtml = $false
$MailMessage.Attachments.Add($attatchment)
#mit Authentifizierung beim Mail Server (ohne einfach weglassen)
$SmtpUser = New-Object System.Net.NetworkCredential
$SmtpUser.UserName = "test***"
$SmtpUser.Password = "*****"
$smtp.Credentials = $SmtpUser
$smtp.Send($MailMessage)
Completed with the according real credentials,
I got the followin error message:
Ausnahme beim Aufrufen von "Send" mit 1 Argument(en): "Fehler beim Senden von Mail."
In Zeile:1 Zeichen:1
$smtp.Send($MailMessage)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
Any Hints, how I can get it run and send mails with attachement via a powershell script?
Kind regards,
Oliver
try this:
# Get the credential
$credential = Get-Credential
## Define the Send-MailMessage parameters
$mailParams = #{
SmtpServer = 'smtp.office365.com'
Port = '587'
UseSSL = $true
Credential = $credential
From = 'sender#yourdomain.com'
To = 'recipient#yourdomain.com', 'recipient#NotYourDomain.com'
Subject = "SMTP Client Submission - $(Get-Date -Format g)"
Body = 'This is a test email using SMTP Client Submission'
Attachment = 'C:\Test.txt' # Here you can change your attachment
DeliveryNotificationOption = 'OnFailure', 'OnSuccess'
}
## Send the message
Send-MailMessage #mailParams
Your code worked for me, except that I had to enable ssl.
Maybe add $smtp.EnableSsl = $true
Can someone please help me figure this part out.
#Mail Configuration
$smtpUser = "email#domain.com"
$smtppass = ConvertTo-SecureString "PasswordAsPlainText" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential -ArgumentList ($smtpuser, $smtppass)
$ToAddress = "toaddress#domain.com"
$FromAddress = "send#domain.com"
$SMTPSERVER = "smtp.office365.com"
$SMTPPORT = "587"
$MailParam = #{
To = $ToAddress
From = $FromAddress
Subject = $subject
Body = $Mail
SMTPServer = $SMTPServer
Port = $SMTPPORT
Credential = $pscred
}
#Send Email
$GetChildItem = Get-ChildItem -Path C:\Temp
if ($GetChildItem -ne $Null)
{
Write-Host "Backup Success"
$subject = "$env:COMPUTERNAME SQL Backup Success"
$Mail = "SQL Backup Succeded on the server, please see the attached report for more details"
$attachment = $reportfile
Send-MailMessage #MailParam -BodyAsHtml -usessl
#Exit
}
if ($GetChildItem -eq $Null)
{
Write-Host "Backup Failed"
$subject = "$env:COMPUTERNAME SQL Backup Failed"
$Mail = "SQL Backup Failed on the server, please see the attached report for more details"
$attachment = $reportfile, $debuglog
Send-MailMessage #MailParam -usessl -BodyAsHtml
#Exit
}
Now I don't think anything is wrong with the code above, I am no expert coder but I can pretty much copy and paste :) and take stuff from there to get it working for me.
The issue with the above code is that when run it, it doesn't work for the 1st time but when you run it again it works fine. The error you get the first time is
Send-MailMessage : Cannot validate argument on parameter 'Body'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At C:\Users\Aasim\Desktop\Untitled1.ps1:29 char:26
+ Send-MailMessage #MailParam -BodyAsHtml -usessl
+ ~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.SendMailMessage
I am not sure what the issue is and why it doesn't work only the first time but works every other subsequent time until you close and reopen the script.
Basically I am creating a SQL backup script that backs up databases to our Network Share and then emails me whether it was successful or not. so far the rest of the script works just fine.
In your If and Else blocks, instead of creating a variable $subject, or $Mail, update the hashtable, $MailParam. Also, you seem to be missing the Attachment variable in your Send-MailMessage
if ($GetChildItem -eq $Null)
{
Write-Host "Backup Failed"
$MailParam.Subject = "$env:COMPUTERNAME SQL Backup Failed"
$MailParam.Body = "SQL Backup Failed on the server, please see the attached report for more details"
$attachment = $reportfile, $debuglog
Send-MailMessage #MailParam -usessl -BodyAsHtml -Attachments $attachment
#Exit
}
I did turn on my less secure app in Gmail, I think the problem is SSL.
$time = get-date
$smtpServer = “smtp.gmail.com”
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential(“user”, “password”)
$smtp = new-object Net.Mail.SmtpClient($smtpServer,587) **587 to 465**
$msg = new-object Net.Mail.MailMessage
$msg.From = (“myemail#gmail.com”)
$msg.To.Add(“myemail#gmail.com”)
$body=”Your message Body”
$msg.Subject = “Mail From Gmail ” + $time
#your file location
$files=Get-ChildItem “C:\Users\Public\Pictures\LINE”
Foreach($file in $files)
{
Write-Host “Attaching File :- ” $file
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList
C:\Users\Public\Pictures\LINE\$file
$msg.Attachments.Add($attachment)
}
$smtp.Send($msg)
$attachment.Dispose()
$msg.Dispose()
Have you tried to change the port?
It looks to me that you're still using 587 which is expecting TLS/SSL or STARTTLS.
Is there a reason you're not authenticating and using SSL/TLS ?
I've read that Google does not fall back to plaintext SMTP if STARTTLS is not supported. If you've explicitly selected the "Unsecured" option when configuring the server I believe you need to use a different port. 25(maybe).
Edit: It looks like you're missing arguments on the send method. Try this code.
Alternatively try changing for the much easier looking Send-MailMessage cmdlet
https://learn.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/Send-MailMessage?view=powershell-5.1
$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)
I had a similar problem at one point with a script of mine. On mobile right now, but if I remember right, I ended up making an app password for the use and turned off the Less secure app option.
https://support.google.com/accounts/answer/185833?hl=en
I can create an email and display it with my script, but for some reason it doesn't send and I receive the following error. Am I missing something, maybe there's a permissions issue?
Exception calling "Send" with "0" argument(s): "Operation aborted (Exception from HRESULT: 0x80004004 (E_ABORT))"At C:\TEMP\Scripts\PowerShell\Outlook EMail Creation\TestEMailSend.ps1:27 char:5
+ $mail.Send()
+ ~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
My code:
$global:UserReportsToEmail = "my.email#domain.com"
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$mail.To = "$global:UserReportsToEmail"
$mail.cc = "EMAIL#domain.com"
$mail.Subject = "mySubject"
$mail.HTMLBody =
"<font color ='blue'><b>TESTING STUFFFF!</b></font><br>
Text on a new line $UserID"
$mail.Send()
$inspector = $mail.GetInspector
$inspector.Display()
According to a few of the Microsoft sites (e.g. https://social.msdn.microsoft.com/Forums/en-US/80c66a08-66ee-4ab6-b629-6b1e70143eb0/operation-aborted-exception-from-hresult-0x80004004-eabort-outlook-appointment?forum=outlookdev ) this is due to 'object model guard'. A security feature to prevent automated programs from doing stuff like auto-emailing out viruses and stuff from the background.
You probably already worked this out. Posting this here so that others like myself can more quickly and easily understand why its not working.
you can use the Send-MailMessage CmdLets : https://technet.microsoft.com/en-us/library/hh849925.aspx
then when i need more controls and dispose functionnality i use System.Net.Mail.SmtpClient
try
{
$emailCredentials = Import-Clixml "C:\testMail\credentials.clixml"
$recipients = #("user#mail.com", "user2#mail.com", "user3#mail.com")
$attachments = #("C:\testMail\file.txt", ""C:\testMail\file2.txt", "C:\testMail\file3.txt")
# create mail and server objects
$message = New-Object -TypeName System.Net.Mail.MailMessage
$smtp = New-Object -TypeName System.Net.Mail.SmtpClient($buildInfoData.BuildReports.Mail.Server)
# build message
$recipients | % { $message.To.Add($_) }
$message.Subject = $subject
$message.From = New-Object System.Net.Mail.MailAddress($emailCredentials.UserName)
$message.Body = $mailHtml
$message.IsBodyHtml = $true
$attachments | % { $message.Attachments.Add($(New-Object System.Net.Mail.Attachment $_)) }
# build SMTP server
$smtp = New-Object -TypeName System.Net.Mail.SmtpClient(smtp.googlemail.com)
$smtp.Port = 572
$smtp.Credentials = [System.Net.ICredentialsByHost]$emailCredentials
$smtp.EnableSsl = $true
# send message
$smtp.Send($message)
Write-Host "Email message sent"
}
catch
{
Write-Warning "$($_.Exception | Select Message, Source, ErrorCode, InnerException, StackTrace | Format-List | Out-String)"
}
finally
{
Write-Verbose "Disposing Smtp Object"
$message.Dispose()
$smtp.Dispose()
}
I have a script that goes into SCSM, gets the relevant files from the IR and downloads them properly onto the user's computer.
Next, I need the script to create an email from the client's outlook application and display it on their screen before sending the email..
Here is the part of the script that does that:
$GetFiles = Get-ChildItem "$ArchiveRootPath\$IRID\"
$ol = New-Object -comObject Outlook.Application #| New-Object Net.Mail.MailMessage
$mail = $ol.CreateItem(0)
$mail.To = "johndoe#contoso.com"
$mail.Subject = "This is a test [$IRID]"
Foreach($GetFile in $GetFiles)
{
Write-Host “Attaching File :- ” $GetFile
$attachment = New-Object System.Net.Mail.Attachment –ArgumentList C:\Temp\SCSM_Archive\$IRID\$GetFile
$mail.Attachments.Add($attachment)
}
$inspector = $mail.GetInspector
$inspector.Display()
However, when I run the script, I get this error:
Attaching File :- email.eml
Exception calling "Add" with "1" argument(s): "Value does not fall within the expected range."
At C:\Temp\SSWireless Script.ps1:99 char:2
+ $mail.Attachments.Add($attachment)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
All the variables are checked from the previous part of the script that downloads the files. PS is able to see the files, but cannot attach them to the email.
I don't want to use the send-message function due to the fact that we will be moving to a cross domain email account and would rather use outlook to create the email itself.
Here is a reference for Microsoft.Office.Interop.Outlook Attachments.Add method . This confirms that the first parameter (and the only parameter in your case) needs to be a full path to file.
There is no point passing [System.Net.Mail.Attachment] .NET objects to COM interface.
Your code should look something like this:
$GetFiles = Get-ChildItem "$ArchiveRootPath\$IRID\"
$ol = New-Object -comObject Outlook.Application
$mail = $ol.CreateItem(0)
$mail.To = "johndoe#contoso.com"
$mail.Subject = "This is a test [$IRID]"
Foreach($GetFile in $GetFiles)
{
Write-Host “Attaching File :- $GetFile.Name"
$mail.Attachments.Add($GetFile.FullName)
}