I am trying to send a mail using powershell by making use of gmail smtp server. Here's my code snippet.
$sender = "user1#domain.com"
$recipient = "user2#domain.com"
$subject = "test"
$body = "test text"
$username = "user1#domain.com"
$password = "password"
$sc = new-object Net.Mail.SmtpClient("smtp.gmail.com", 465);
$sc.EnableSsl = $true;
$cred = New-Object System.Net.NetworkCredential($username,$password);
$sc.Credentials = $cred;
$emsg = new-Object System.Net.Mail.MailMessage($sender, $recipient, $subject, $body);
$sc.Timeout = 180000
$sc.Send($emsg);
Everytime I recieve a timeout, even if I have fixed the timeout value to 3 minutes(180 seconds). To be more precise, the error is
Exception calling "Send" with "1" argument(s): "The operation has timed out."
At line:15 char:1
+ $sc.Send($emsg);
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
Have anyone experienced this issue before? Any suggestions or ideas would be really appreciated.
Posting that it could save someone's time too..
$param = #{
SmtpServer = 'smtp.gmail.com'
Port = 587
UseSsl = $true
Credential = 'user1#domain.com'
From = 'user1#domain.com'
To = 'user2#domain.com'
Subject = 'test'
Body = "testtext"
}
Send-MailMessage #param
PS here.
Related
I have a powershell script send email to the users will expire the password soon in AD, but when it send the first email fail, and the rest emails send good.
The fail I receive is this one:
Excepción al llamar a "Send" con los argumentos "1": "Error al enviar correo."
En C:\Users\XXXXXXXX\Desktop\script.ps1: 22 Carácter: 1
+ $smtp.Send($MailMessage)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
The script mail I have this information:
{
$subject="Aviso caducidad contraseña"
$smtpServer = "smtp.office365.com"
$emailFrom = "XXXXXX#XXXXXXX"
$smtp = new-object Net.Mail.SmtpClient($smtpServer,587)
$mailAuthentication = new-object
System.Net.NetworkCredential("XXXXXXXXX#XXXXXXX", XXXXXXXX)
$smtp.UseDefaultCredentials = $False
$smtp.EnableSsl = $True
$smtp.Credentials =$mailAuthentication
$MailMessage = new-object Net.Mail.MailMessage($emailFrom, $mail, $subject, $body)
$MailMessage.IsBodyHtml = $true
$smtp.Send($MailMessage)
$Smtp.EnableSsl = $true
$TLS12Protocol = [System.Net.SecurityProtocolType] 'Ssl3 , Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $TLS12Protocol
}
Anyone can help me?
Thanks in advance,
I created a function for PowerShell using the old skool method of sending email via PowerShell using Net.Mail.MailMessage. It works fine, however, I know there are other ways of doing this in a simpler format using Send-MailMessage. I pieced together a Send-MailMessage function but I am getting an error when running it. Thoughts on either fixing the error or modifying the code to make it a little simpler? Note that the password.txt file that the script is pointing to is an encrypted password text file created from PowerShell.
Working Function
function sendMail ($message)
{
"Sending Email"
#SMTP server name
$smtpServer = "smtp.office365.com"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
$emailPassword = Get-Content "C:\scriptfolder\password.txt" | ConvertTo-SecureString
$emailCredential = New-Object System.Net.NetworkCredential("sender#domain.com", $emailPassword)
#Add Attachment
$Attachments = "attached file"
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Port = 587
$smtp.EnableSSl = $true
$smtp.Credentials = $emailCredential
#Email structure
$msg.From = "sender#domain.com"
$msg.To.add("user1#domain.com")
$msg.CC.Add("user2#domain.com")
$msg.CC.Add("user3#domain.com")
$msg.subject = "***TEST***"
$msg.body = "***TEST****"
$msg.Attachments.Add($Attachments)
#Sending email
$smtp.Send($msg)
"Email Sent"
};
Sendmail
Send-MailMessage that doesnt work
workflow SendEmail {
$emailPassword = Get-Content "C:\password.txt" | ConvertTo-SecureString
$emailCredential = New-Object System.Net.NetworkCredential("sender#domain.com", $emailPassword)
InlineScript {
Send-MailMessage -From 'Sender <sender#domain.com>' -To 'User1 <user1#domain.com>', 'User2 <user2#domain.com>' -Subject 'Sending the Attachment' -Body "Forgot to send the attachment. Sending now." Attachments "attached file" -DeliveryNotificationOption OnSuccess, OnFailure -SmtpServer 'smtp.office365.com' -Port '587' -Credential $using:emailCredential
}
}
SendMail
Error from Send-MailMessage
Cannot process argument transformation on parameter 'Credential'. userName
+ CategoryInfo : InvalidData: (:) [Send-MailMessage], ParameterBindin...mationException
+ FullyQualifiedErrorId : ParameterArgumentTransformationError,Microsoft.PowerShell.Commands.SendMailMessage
+ PSComputerName : [localhost]
New error after code changes
Send-MailMessage : Error in processing. The server response was: 5.7.3 STARTTLS is required to send mail [SA0PR13CA0028.namprd13.prod.outlook.com]
At SendEmail:9 char:9
+
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
+ PSComputerName : [localhost]
My code previously did not encounter any problem.
The error I get is
Exception calling "Send" with "1" argument(s): "The SMTP server
requires a secure con nection or the client was not authenticated. The
server response was: 5.7.57 SMTP; Cl ient was not authenticated to
send anonymous mail during MAIL FROM [HK2PR02CA0168.apc
prd02.prod.outlook.com]" At
File Path:15 char:17
$SMTPClient.Send <<<< ($SMTPMessage)
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : DotNetMethodException
I searched online and was only given this.
Here's my code
$Username = "myemail#outlook.com"
$EmailPassword = "password"
$Attachment= "File path"
$EmailTo = "sendto#gmail.com"
$EmailFrom = "myemail#outlook.com"
$Subject = "Subject"
$Body= "Body"
$SMTPServer = "smtp.outlook.com"
$SMTPMessage = New-Object System.Net.Mail.MailMessage($EmailFrom, $EmailTo, $Subject, $Body)
$Attachment = New-Object System.Net.Mail.Attachment($Attachment)
$SMTPMessage.Attachments.Add($Attachment)
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential($Username, $EmailPassword)
$SMTPClient.Send($SMTPMessage)
ii "another File Path that will be opened"
Your credentials are probably wrong.
Check it again.
I messed up there.
I am trying to send an email, but I am getting syntax errors:
$fromaddress = "abc#a.com"
$toaddress = #('def#a.com>', 'ghi#a.com>')
$bccaddress = #('sl#a.com')
#$CCaddress = #('la#a.com>')
$Subject = "BAKUP REPORT FOR Instances "
$body = get-content C:\body.txt
$attachment = #("C:\result.text", "C:\result.csv", "C:\object.text", "C:\object.csv")
$smtpserver = "smtp.a.com"
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
#$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
I am getting the below errors.
new-object : Cannot find an overload for "Attachment" and the argument count: "4".
At line:18 char:11
+ $attach = new-object Net.Mail.Attachment($attachment)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
Exception calling "Add" with "1" argument(s): "Value cannot be null.
Parameter name: item"
At line:19 char:1
+ $message.Attachments.Add($attach)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
Exception calling "Send" with "1" argument(s): "Failure sending mail."
At line:22 char:1
+ $smtp.Send($message)
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SmtpException
I prefer to use Send-MailMessage as it has a nicer syntax the Net.Mail, you can also use Splatting to make it even easier to read:
$messageParameters = #{
From = "abc#a.com"
To = "def#a.com>", "ghi#a.com>"
Bcc = "sl#a.com"
#Cc = "la#a.com>"
Subject = "BAKUP REPORT FOR Instances"
Body = Get-Content C:\body.txt
Attachments = "C:\result.text", "C:\result.csv", "C:\object.text", "C:\object.csv"
SmtpServer = "smtp.a.com"
}
Send-MailMessage #messageParameters -BodyAsHtml
Depending on your SMTP Server, you might also need to specify Credentials for authentication and/or SSL as well.
What about:
$fromaddress = "abc#a.com"
$toaddress = #('def#a.com>', 'ghi#a.com>')
$bccaddress = #('sl#a.com')
#$CCaddress = #('la#a.com>')
$Subject = "BAKUP REPORT FOR Instances "
$body = get-content C:\body.txt
$attachment1 = #("C:\result.text")
$attachment2 = #("C:\result.csv",)
$attachment3 = #("C:\object.text")
$attachment4 = #("C:\object.csv")
$smtpserver = "smtp.a.com"
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress)
#$message.CC.Add($CCaddress)
$message.Bcc.Add($bccaddress)
$message.IsBodyHtml = $True
$message.Subject = $Subject
$attach = new-object Net.Mail.Attachment($attachment1)
$message.Attachments.Add($attach)
$attach = new-object Net.Mail.Attachment($attachment2)
$message.Attachments.Add($attach)
$attach = new-object Net.Mail.Attachment($attachment3)
$message.Attachments.Add($attach)
$attach = new-object Net.Mail.Attachment($attachment4)
$message.Attachments.Add($attach)
$message.body = $body
$smtp = new-object Net.Mail.SmtpClient($smtpserver)
$smtp.Send($message)
Your last error may be related to authentication. Best to search for "send email by telnet" to do a quick test. use How to send email using simple SMTP commands via Gmail? as reference.
Attached the code to include authentication:
----> ADD AFTER >> $smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username,
$Password);
PFE: https://community.spiceworks.com/topic/621669-powershell-mail-script
I've been trying to debug this for a couple of days now and I'm at my wits end. Here's the code:
$gmailPwd = 'password'
$gmailUser = 'my.email#gmail.com'
$cred = New-Object System.Management.Automation.PSCredential ($gmailUser,$gmailPwd)
$param = #{
SmtpServer = 'smtp.gmail.com'
Port = 587
UseSsl = $true
Credential = $cred
From = $gmailUser
To = $gmailUser
Subject = 'Test'
Body = "Test"
}
Send-MailMessage #param
I keep getting the following error message:
New-Object : Cannot convert argument "1", with value: "Password1234", for "PSCredential" to type "System.Security.SecureString": "Cannot convert the "Password1234" value of type "System.String" to type
"System.Security.SecureString"."
At line:4 char:9
+ $cred = New-Object System.Management.Automation.PSCredential ($gmailUser,$gmailP ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
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 line:15 char:1
+ Send-MailMessage #param
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.Mail.SmtpClient:SmtpClient) [Send-MailMessage], SmtpException
+ FullyQualifiedErrorId : SmtpException,Microsoft.PowerShell.Commands.SendMailMessage
I'm just not really sure what the error message is getting at. And, for the record, no Password1234 is not really the password, but it is analogous to the real thing.
A [PSCredential]'s constructor doesn't accept plain text passwords. It has to be a secure string.
From How to create a PSCredential object:
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)