i use the script below to send emails from a powershell script.
$smtpServer = "mail.company.com"
$smtpFrom = "Check <check#company.com>"
$smtpTo = "user1#company.com"
$messageSubject = "Daily Check from $thedate"
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$message.Subject = $messageSubject
$message.IsBodyHTML = $true
$message.Body = $Body | ConvertTo-HTML -head $style -body $Body
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($message)
It works fine untill i add more reciepients like this...
$smtpTo = "user1#company.com", "user2#company.com"
I also tried putting it inside an array like this....
$smtpTo = #("user1#company.com", "user2#company.com")
None of them work for me. Hope someone can help
The .To property of System.Mail.MailMessage is a collection that you can add emails to.
$message = New-Object System.Net.Mail.MailMessage $smtpfrom, $smtpto
$Message.to.add('myotheremail#mydomain.net')
$message.Subject = $messageSubject
$message.IsBodyHTML = $true
Related
I'm trying to figure out how to best use Powershell to send email. I've been struggling with single quote ' and dashes - turning into question marks ? in the sent email and wondering if someone can help. This is what I have:
##############################################################################
$Letter = Get-Content .\Letter.htm
$From = "Myaddress#email.com"
$To = address#email.com
$Cc = "MyOtherAddress#email.com"
$Subject = "Subject"
$Body = #"$Name,
$Letter
"#
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -to $To -Cc $Cc -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl -BodyAsHtml -Credential $Credential
##############################################################################
I have also tried:
$Letter = Get-Content .\Letter.htm -Raw
Seems to be working for me.
$From = "Myaddress#email.com"
$To = "address#email.com"
$Cc = "MyOtherAddress#email.com"
$Subject = "Subject"
$Body = Get-Content "C:\Users\TestUser\Downloads\StackOverflow.html"
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
Send-MailMessage -From $From -To $To -Cc $Cc -Subject $Subject -Body "$Body" -BodyAsHtml -Priority High -DeliveryNotificationOption OnFailure -SmtpServer 'smtp.gmail.com' -port $SMTPPort -UseSsl -BodyAsHtml -Credential $Credential
I have one HTML file which contains css and HTML code as shown below.
I want this content to be embedded in email body using Powershell script.
Below is my Powershell script for Email.
$toUsers = #('xxxx#microsoft.com','xxxx#microsoft.com')
$fromUser = "xxxx#microsoft.com"
$smtpServer = "xxx.XXX.corp.xxxx.com"
#$ccUsers = "xxxx#microsoft.com"
$msg = New-Object Net.Mail.MailMessage
$smtp = New-Object Net.Mail.SmtpClient($smtpServer)
$smtp.UseDefaultCredentials = $true
#$msg.Body = $html
$msg.Subject="c360 UX test run report" -f (Get-Date -format "yyyy-MM-dd")
foreach($toUser in $toUsers)
{
$msg.To.Add($toUser)
write-host $toUser
}
$body = "<b>Build Number:- $(Build.BuildNumber)<br>"
$body += "Branch Name:- $(Build.SourceBranch) </b> <br>"
$body += "Product Name:- $env:PRODUCT_NAME <br>"
$body +='Click here'
$msg.From = $fromUser
#$msg.CC.Add($ccUsers)
$msg.IsBodyHTML = $true
$msg.Body = $body
$attachmentObject = new-object Net.Mail.Attachment($(Get-ChildItem -Recurse -Path $(System.ArtifactsDirectory) -Filter 'Report.zip').FullName)
$msg.Attachments.Add($attachmentObject)
$msg.Priority="High"
$smtp.Send($msg)
$smtp.Dispose()
$msg.Dispose()
#Wait for a sec to let dispose complete.
sleep 2`enter code here`
Iam looking for a Powershell script to attach the html file in the body of email.Please help me by providing a sample script .My current script is not working .Iam not able to get the html file content in the body of email.Name of the html file changes every time.
i used 2 scripts but i suppose you could use one
Make the html file
$FILENAME = HTMLfilename
$head = #'
<title>page title</title>
<style> maybe some css</style>
'#
$title01 = #'
<h1>some text above html file</h1>
'#
$body = #"
<a href='$FILENAME.html'>filename</a>
'#
$x = some code
$x | Select-object Name | ConvertTo-HTML -head $head -PreContent $title01 -PostContent "some text" -body $body | Out-File "PATH\TO\HTML\FILE\$FILENAME.html"
Send the email
$Credential = New-Object System.Management.Automation.PsCredential($EmailUsername, $Emailpassword)
$EmailFrom = "from#domain.com"
$EmailTo = #("<to#domain.com>")
#$EmailCc = #("<EMAIL>")
$EmailSubject = "email subject"
$EmailBody = "a link to html file"
#OR maybe Attach it
#$EmailAttachments = "PATH\TO\HTML\FILE\$FILENAME.html"
$SMTPServer = "smtp.#domain.com"
$SMTPPort = ####
$SMTPSsl = $True
$param = #{
SmtpServer = $SMTPServer
Port = $SMTPPort
UseSsl = $SMTPSsl
Credential = $Credential
From = $EmailFrom
To = $EmailTo
#Cc = $EmailCc
Subject = $EmailSubject
Body = $EmailBody
#Attachments = $EmailAttachments
}
Send-MailMessage #param
Can some one help me with the powershell v2 version of the below cmdlet.
$body =
"<wInput>
<uInputValues>
<uInputEntry value='$arg' key='stringArgument'/>
</uInputValues>
<eDateAndTime></eDateAndTime>
<comments></comments>
</wInput>"
$password = ConvertTo-SecureString $wpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wusername, $password)
$output = Invoke-WebRequest -Uri $URI1 -Credential $credential -Method Post -ContentType application/xml -Body $body
$URI1 = "<your uri>"
$password = ConvertTo-SecureString $wpassword -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($wusername, $password)
$request = [System.Net.WebRequest]::Create($URI1)
$request.ContentType = "application/xml"
$request.Method = "POST"
$request.Credentials = $credential
# $request | Get-Member for a list of methods and properties
try
{
$requestStream = $request.GetRequestStream()
$streamWriter = New-Object System.IO.StreamWriter($requestStream)
$streamWriter.Write($body)
}
finally
{
if ($null -ne $streamWriter) { $streamWriter.Dispose() }
if ($null -ne $requestStream) { $requestStream.Dispose() }
}
$res = $request.GetResponse()
Here, give this a shot. I provided some in-line comments. Bottom line, you're going to want to use the HttpWebRequest class from the .NET Base Class Library (BCL) to achieve what you're after.
$Body = #"
<wInput>
<uInputValues>
<uInputEntry value='$arg' key='stringArgument'/>
</uInputValues>
<eDateAndTime></eDateAndTime>
<comments></comments>
</wInput>
"#;
# Convert the message body to a byte array
$BodyBytes = [System.Text.Encoding]::UTF8.GetBytes($Body);
# Set the URI of the web service
$URI = [System.Uri]'http://www.google.com';
# Create a new web request
$WebRequest = [System.Net.HttpWebRequest]::CreateHttp($URI);
# Set the HTTP method
$WebRequest.Method = 'POST';
# Set the MIME type
$WebRequest.ContentType = 'application/xml';
# Set the credential for the web service
$WebRequest.Credentials = Get-Credential;
# Write the message body to the request stream
$WebRequest.GetRequestStream().Write($BodyBytes, 0, $BodyBytes.Length);
This method downloads binary content:
# PowerShell 2 version
$WebRequest=New-Object System.Net.WebClient
$WebRequest.UseDefaultCredentials=$true
#$WebRequest.Credentials=(Get-Credential)
$Data=$WebRequest.DownloadData("http://<url>")
[System.IO.File]::WriteAllBytes("<full path of file>",$Data)
# PowerShell 5 version
Invoke-WebRequest -Uri "http://<url>" -OutFile "<full path of file>" -UseDefaultCredentials -ContentType
I'm aware of a simple pop-up function for PowerShell, e.g.:
function popUp($text,$title) {
$a = new-object -comobject wscript.shell
$b = $a.popup($text,0,$title,0)
}
popUp "Enter your demographics" "Demographics"
But I am unable to find an equivalent for getting a pop-up to ask for input.
Sure, there is Read-Line, but it prompts from the console.
And then there is this complex function, which seems overkill for a script that will ask for input once or twice:
function getValues($formTitle, $textTitle){
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
$objForm = New-Object System.Windows.Forms.Form
$objForm.Text = $formTitle
$objForm.Size = New-Object System.Drawing.Size(300,200)
$objForm.StartPosition = "CenterScreen"
$objForm.KeyPreview = $True
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter") {$x=$objTextBox.Text;$objForm.Close()}})
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape") {$objForm.Close()}})
$OKButton = New-Object System.Windows.Forms.Button
$OKButton.Location = New-Object System.Drawing.Size(75,120)
$OKButton.Size = New-Object System.Drawing.Size(75,23)
$OKButton.Text = "OK"
$OKButton.Add_Click({$Script:userInput=$objTextBox.Text;$objForm.Close()})
$objForm.Controls.Add($OKButton)
$CANCELButton = New-Object System.Windows.Forms.Button
$CANCELButton.Location = New-Object System.Drawing.Size(150,120)
$CANCELButton.Size = New-Object System.Drawing.Size(75,23)
$CANCELButton.Text = "CANCEL"
$CANCELButton.Add_Click({$objForm.Close()})
$objForm.Controls.Add($CANCELButton)
$objLabel = New-Object System.Windows.Forms.Label
$objLabel.Location = New-Object System.Drawing.Size(10,20)
$objLabel.Size = New-Object System.Drawing.Size(280,30)
$objLabel.Text = $textTitle
$objForm.Controls.Add($objLabel)
$objTextBox = New-Object System.Windows.Forms.TextBox
$objTextBox.Location = New-Object System.Drawing.Size(10,50)
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
$objForm.Controls.Add($objTextBox)
$objForm.Topmost = $True
$objForm.Add_Shown({$objForm.Activate()})
[void] $objForm.ShowDialog()
return $userInput
}
$schema = getValues "Database Schema" "Enter database schema"
Probably the simplest way is to use the InputBox method of the Microsoft.VisualBasic.Interaction class:
[void][Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic')
$title = 'Demographics'
$msg = 'Enter your demographics:'
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title)
The simplest way to get an input box is with the Read-Host cmdlet and -AsSecureString parameter.
$us = Read-Host 'Enter Your User Name:' -AsSecureString
$pw = Read-Host 'Enter Your Password:' -AsSecureString
This is especially useful if you are gathering login info like my example above. If you prefer to keep the variables obfuscated as SecureString objects you can convert the variables on the fly like this:
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
[Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pw))
If the info does not need to be secure at all you can convert it to plain text:
$user = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($us))
Read-Host and -AsSecureString appear to have been included in all PowerShell versions (1-6) but I do not have PowerShell 1 or 2 to ensure the commands work identically.
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/read-host?view=powershell-3.0
It would be something like this
function CustomInputBox([string] $title, [string] $message, [string] $defaultText)
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript"
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" )
$_userInput = $inputObject.eval("getInput")
return $_userInput
}
Then you can call the function similar to this.
$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null )
{
echo "Input was [$userInput]"
}
else
{
echo "User cancelled the form!"
}
This is the most simple way to do this that I can think of.