Converting Body to HTML Not Working - html

I am trying to make my body of text convert to HTML so it does not show as plain text in my email.
Here is the code
$From = ""
$To = ""
$SMTPServer = ""
$SMTPPort = "587"
$Username = ""
$Password = ""
$subject = "Test Powershell"
$body = $htmlreport
$bodyAsHtml = $true
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.Send($From, $To, $subject, $body);
I cant see to get the report to send as HTML.

Instead of passing the individual strings to $smtp.Send(), you should create a MailMessage object and send that instead:
$msg = New-Object System.Net.Mail.MailMessage
$msg.From = $From
$msg.To = $To
$msg.Subject = $subject
$msg.Body = $body
$msg.IsBodyHtml = $true # this is where the magic happens
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort)
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password)
$smtp.Send($msg) # and then send the message we just composed above

$bodyAs contains `enter code here`. You should remove that. You also don't set it anywhere.
Maybe try the Send-MailMessage cmdlet instead:
Send-MailMessage -SmtpServer $SMTPServer -To $To -From $From -Subject $subject -Body $body -BodyAsHtml

Related

No mapping exists objecttype: Arraylist to native type

I have an arraylist filled with data from a cmdlet (from the BEMCLI module) and want to store the data in a database. Declaring every column is just to specify the error.
There are some questions about a similar error code but I don't know how to get the solution work for me.
Errorcode:
No mapping exists from object type System.Data.Arraylist to a known managed
provider native type
In C:\**\test.ps1:68 Zeichen:1
+ $SqlCmd.executenonquery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentException
Script:
$JobHistory = Invoke-Command -ComputerName $ServerName -ScriptBlock {
Import-Module BEMCLI;
Get-BEJobHistory -FromStartTime (Get-Date).AddDays(-1)
}
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
$SqlConnection.Open()
for ($i=0; $i -lt $JobHistory.Length; $i++) {
$SqlCmd.Parameters.Add("#Name", [System.Data.SqlDbType]::string).Value = $JobHistory[$i].Name
$SqlCmd.Parameters.Add("#ID", [System.Data.SqlDbType]::UniqueIdentifier).Value = $JobHistory[$i].ID
$SqlCmd.Parameters.Add("#JobName", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].JobName
$SqlCmd.Parameters.Add("#JobStatus", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].JobStatus
$SqlCmd.Parameters.Add("#Job", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].Job
$SqlCmd.Parameters.Add("#JobId", [System.Data.SqlDbType]::UniqueIdentifier).Value = $JobHistory[$i].JobId
$SqlCmd.Parameters.Add("#JobType", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].JobType
$SqlCmd.Parameters.Add("#StartTime", [System.Data.SqlDbType]::DateTime).Value = $JobHistory[$i].StartTime
$SqlCmd.Parameters.Add("#ElapsedTime", [System.Data.SqlDbType]::TimeSpan).Value = $JobHistory[$i].ElapsedTime
$SqlCmd.Parameters.Add("#EndTime", [System.Data.SqlDbType]::DateTime).Value = $JobHistory[$i].EndTime
$SqlCmd.Parameters.Add("#PercentComplete", [System.Data.SqlDbType]::Real).Value = $JobHistory[$i].PercentComplete
$SqlCmd.Parameters.Add("#AgentServer", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].AgentServer
$SqlCmd.Parameters.Add("#AgentServerIdList", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].AgentServerIdList
$SqlCmd.Parameters.Add("#BackupExecServerName", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].JobLogFilePath
$SqlCmd.Parameters.Add("#JobLogFilePath", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].JobLogFilePath
$SqlCmd.Parameters.Add("#DeduplicationRatio", [System.Data.SqlDbType]::Real).Value = $JobHistory[$i].DeduplicationRatio
$SqlCmd.Parameters.Add("#JobRateMBPerMinute", [System.Data.SqlDbType]::Real).Value = $JobHistory[$i].JobRateMBPerMinute
$SqlCmd.Parameters.Add("#StorageName", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].StorageName
$SqlCmd.Parameters.Add("#TotalDataSizeBytes", [System.Data.SqlDbType]::BigInt).Value = $JobHistory[$i].TotalDataSizeBytes
$SqlCmd.Parameters.Add("#ErrorCategory", [System.Data.SqlDbType]::Int).Value = $JobHistory[$i].ErrorCategory
$SqlCmd.Parameters.Add("#ErrorCode", [System.Data.SqlDbType]::Int).Value = $JobHistory[$i].ErrorCode
$SqlCmd.Parameters.Add("#ErrorCategory", [System.Data.SqlDbType]::String).Value = $JobHistory[$i].ErrorCategory
$SqlCmd.Parameters.Add("#ErrorMessage", [System.Data.SqlDbType]::Int).Value = $JobHistory[$i].ErrorMessage
$SqlQuery = "INSERT INTO JobHistory(Nr,Name,ID,JobName,JobStatus,Job,JobId,JobType,StartTime,ElapsedTime,EndTime,PercentComplete,AgentServer,AgentServerIdList,BackupExecServerName,JobLogFilePath,DeduplicationRatio,JobRateMBPerMinute,StorageName,TotalDataSizeBytes,ErrorCategory,ErrorCode,ErrorCategory,ErrorMessage) VALUES (#Nr,#Name,#ID,#JobName,#JobStatus,#Job,#JobId,#JobType,#StartTime,#ElapsedTime,#EndTime,#PercentComplete,#AgentServer,#AgentServerIdList,#BackupExecServerName,#JobLogFilePath,#DeduplicationRatio,#JobRateMBPerMinute,#StorageName,#TotalDataSizeBytes,#ErrorCategory,#ErrorCode,#ErrorCategory,#ErrorMessage)"
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlCmd.ExecuteNonQuery()
}
Thanks to Richard for giving the right hint.
Collections cause the problem (AgentServer and AgentServerIdList)
i fixed the code from above, adding $SqlCmd.Parameters.Clear() in the loop to clear the parameters in every loop. It was something like 'cannot declare #Variable twice'.
Commandline gave me another error - so i decided to switch to .Parameters.AddWithValue-Command.
Script works fine now. Thank you!
$JobHistory = invoke-command -ComputerName $ServerName -ScriptBlock { import-module BEMCLI; Get-BEJobHistory -FromStartTime (get-date).AddDays(-1) }
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"
$SqlCmd.Connection = $SqlConnection
$SqlConnection.Open()
for($i=0; $i -lt $JobHistory.Length; $i++){
$SqlCmd.Parameters.Clear()
$SqlCmd.Parameters.AddWithValue("#Nr", $JobHistory[$i].Nr)
$SqlCmd.Parameters.AddWithValue("#Name",$JobHistory[$i].Name)
$SqlCmd.Parameters.AddWithValue("#ID", $JobHistory[$i].ID)
$SqlCmd.Parameters.AddWithValue("#JobName", $JobHistory[$i].JobName)
$SqlCmd.Parameters.AddWithValue("#JobStatus", $JobHistory[$i].JobStatus)
$SqlCmd.Parameters.AddWithValue("#Job", $JobHistory[$i].Job)
$SqlCmd.Parameters.AddWithValue("#JobId", $JobHistory[$i].JobId)
$SqlCmd.Parameters.AddWithValue("#JobType", $JobHistory[$i].JobType)
$SqlCmd.Parameters.AddWithValue("#StartTime", $JobHistory[$i].StartTime)
$SqlCmd.Parameters.AddWithValue("#ElapsedTime", $JobHistory[$i].ElapsedTime)
$SqlCmd.Parameters.AddWithValue("#EndTime", $JobHistory[$i].EndTime)
$SqlCmd.Parameters.AddWithValue("#PercentComplete", $JobHistory[$i].PercentComplete)
$SqlCmd.Parameters.AddWithValue("#BackupExecServerName", $JobHistory[$i].BackupExecServerName)
$SqlCmd.Parameters.AddWithValue("#JobLogFilePath", $JobHistory[$i].JobLogFilePath)
$SqlCmd.Parameters.AddWithValue("#DeduplicationRatio", $JobHistory[$i].DeduplicationRatio)
$SqlCmd.Parameters.AddWithValue("#JobRateMBPerMinute", $JobHistory[$i].JobRateMBPerMinute)
$SqlCmd.Parameters.AddWithValue("#StorageName", $JobHistory[$i].StorageName)
$SqlCmd.Parameters.AddWithValue("#TotalDataSizeBytes", $JobHistory[$i].TotalDataSizeBytes)
$SqlCmd.Parameters.AddWithValue("#ErrorCode", $JobHistory[$i].ErrorCode)
$SqlCmd.Parameters.AddWithValue("#ErrorCategory", $JobHistory[$i].ErrorCategory)
$SqlCmd.Parameters.AddWithValue("#ErrorCategoryType", $JobHistory[$i].ErrorCategoryType)
$SqlCmd.Parameters.AddWithValue("#ErrorMessage", $ValueForJobHistory[$i].ErrorMessage)
$SqlQuery = "Insert into JobHistory(Nr,Name,ID,JobName,JobStatus,Job,JobId,JobType,StartTime,ElapsedTime,EndTime,PercentComplete,BackupExecServerName,JobLogFilePath,DeduplicationRatio,JobRateMBPerMinute,StorageName,TotalDataSizeBytes,ErrorCode,ErrorCategory,ErrorCategoryType) Values(#Nr,#Name,#ID,#JobName,#JobStatus,#Job,#JobId,#JobType,#StartTime,#ElapsedTime,#EndTime,#PercentComplete,#BackupExecServerName,#JobLogFilePath,#DeduplicationRatio,#JobRateMBPerMinute,#StorageName,#TotalDataSizeBytes,#ErrorCode,#ErrorCategoryType,#ErrorCategory)"
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.executenonquery()
}

PowerShell and MySQL - Leave connection open for multiple queries?

I am using the MySQL connector with PowerShell and I have the need to do a query, then scrub the data a little bit and then dump the remainder to another table on the same MySQL DB. How could I leave the connection open to make this all run a bit faster?
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")
return $DataSet.Tables[0]
Create the connection object in the function that calls this function. The called function will inherit whatever objects the calling function is maintaining, so $Connection will be valid in the called function.
function RunMe(){
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()
# Call the function that executes the MySQL code
ExecuteMySQL
# If needed, call another function that executes the MySQL code
ExecuteSomeOtherMySQL
# Close the connection after all MySQL operations are complete
$Connection.Close()
}
function ExecuteMySQL(){
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($Query, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")
return $DataSet.Tables[0]
}

How to Apply Formatting to my Table?

I'm trying to apply a table formatting to my table when it is emailed out, but cannot seem to figure how to do so. I'm pretty sure the problem is related to how the $html variable is set, or maybe when I try to set $EmailTable to $html with $a as the table formatting. Any help is appreciated!
$ProgramA = "A-1"
$MonikerA = "A-2"
$CountA = "1"
$ProgramB = "B-1"
$MonikerB = "B-2"
$CountB = "2"
$ProgramC = "C-1"
$MonikerC = "C-2"
$CountC = "3"
# Create a DataTable
$table = New-Object system.Data.DataTable "TestTable"
$col1 = New-Object system.Data.DataColumn Program,([string])
$col2 = New-Object system.Data.DataColumn Moniker,([string])
$col3 = New-Object system.Data.DataColumn Cases,([string])
$table.columns.add($col1)
$table.columns.add($col2)
$table.columns.add($col3)
# Add content to the DataTable
$row = $table.NewRow()
$row.Program = $ProgramA
$row.Moniker = $MonikerA
$row.Cases = $CountA
$table.Rows.Add($row)
$row = $table.NewRow()
$row.Program = $ProgramB
$row.Moniker = $MonikerB
$row.Cases = $CountB
$table.Rows.Add($row)
$row = $table.NewRow()
$row.Program = $ProgramC
$row.Moniker = $MonikerC
$row.Cases = $CountC
$table.Rows.Add($row)
$row = $table.NewRow()
# Create an HTML version of the DataTable
$html = "<table><tr><td>Program</td><td>Moniker</td><td>Cases</td></tr>"
foreach ($row in $table.Rows)
{
$html += "<tr><td>" + $row[0] + "</td><td>" + $row[1] + "</td><td>" + $row[2] + "</td></tr>"
}
$html += "</table>"
# Here is the formatting I'm trying to apply (which doesn't work)
$a = "<style>BODY{font-family: Verdana; font-size: 9pt;}"
$a = $a + "BODY{background-color:white;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse; }"
$a = $a + "TH{border-width: 2px;padding: 7px;border-style: solid;border-color: black;background-color:lightblue;padding-right: 2px;}"
$a = $a + "TD{border-width: 2px;padding: 5px;border-style: solid;border-color: black;background-color:white; padding-right: 2px;}"
$a = $a + "</style>"
$EmailTable = $html ConvertTo-HTML -head $a
$EmailTable = $html ConvertTo-HTML -head $a
This is not how ConvertTo-Html works. Not only is the statement missing a | before ConvertTo-Html, but $html already contains a (manually constructed) HTML table. The purpose of ConvertTo-Html is to do the conversion of a list of objects into an HTML table for you. Change the above to this:
$EmailTable = $table | ConvertTo-Html -Head $a

Problems with sending HTML Email with PDF attachment using PHPMailer

Please help me, i'm trying to send an email with an HTML body and a PDF-file attached. I'm using PHPMailer. I tried a lot but all I get in my mail is this:
--b1_422917e00bd74f108a49b5d3d858e74d Content-Type: text/html; charset = "iso-8859-1" Content-Transfer-Encoding: 8bit Hello World --b1_422917e00bd74f108a49b5d3d858e74d Content-Type: application/pdf; name="factuur.pdf" Content-Transfer-Encoding: base64 Content-Disposition: attachment; filename="factuur.pdf" JVBERi0xLjQKJcfsj6IKMTEgMCBvYmoKPDwvTGVuZ3RoIDEyIDAgUi9GaWx0ZXIgL0ZsYXRlRGVj b2RlPj4Kc3RyZWFtCnic7VtZs9zEFa5A2CYpQyALSUiiNyQqI3pfeGOrOECgMJc8BPJg38Xbta8x NqbyL/Jn85yvF6mPpNbMXMoPVCrlskvT6j59+izfWdT+pmG9UA0Lf4aH43ubt69x2dz8dsOb8Ofh zY2zrGfeNU7yXmvf3Ns4wXrDxDhiHes50431vGdGlt8K741pjjfDiMEMbZuBgNHhp2qGLYbfxxvP fa+9Gke8CTOG9flXoT8MZAaG1QOD8yMcb87e2sieCwXST3DUj/D3Tj7ytb/8bx751uaLzTcNV1r3 0kVtcy5Vr3ijmeqNwFzfc+51tgLVfHCx+XwT7SMIRbMgsUAZkzkPlFygBCq2V83D00jfOZAUJtE3 eHamwSoBJhvJlOidzfR1or97iXAWm/i8xBy0xHLZDytsfYXoPV2hNes9z0tcWgKxKq5NMA8RVJCn QVzO6UjKaJxb6XTyJCa4yzcb1XNjjI0D9Pn4XvPeUdjBQ3Y9k841R2cb7OydlyJx1kBtTirbWA19 YuHRvc1X7U+6LYxJYR5vn+m2CprG6vbZbivCI7PtT8MM47znrn2uc2CTG9s+3215mKAUBiMJZYxv X+gkJoSnFzsMYnPVvtSJXjGtbfv1/W4re8cEF+3POg6FCWfan3cKTwxrvn4YqFrGNMd7Ft5z314Z 17+cGBROta9gI4ktOZ7+efQRzi5gN5CshLTL2fX87Er3GvYYz34NNITygrfXw3G5sKq9EQ6jpZRK thfkmY6X2ffJ6N2Os17ClNsmjAqDc6j2S+zhlJKifRSY98wb1z4Mj5Jr355CoFYLjB0noo6Z9lai et cetera..
I'm using this code:
$message = "<b>Hello World</b>";
$fromname = "Tester";
$subject = "Test - 3";
$headers = "Content-Type:text/html\n";
$to = "test#test.nl";
$attachment = $_SERVER['DOCUMENT_ROOT'] . "/facturen/test.pdf";
$mail = new PHPMailer();
$body = preg_replace('/\[\]/',"",$message);
$mail->IsSMTP();
$mail->Host = "smtp.test.nl";
$mail->SMTPAuth = true;
$mail->Host = "smtp.test.nl";
$mail->Port = 25;
$mail->Username = $user;
$mail->Password = $pass;
$mail->IsHTML(true);
$mail->SetFrom($user, $user);
$mail->FromName = $fromname;
$mail->Subject = $subject;
$mail->Body = $body;
$mail->addCustomHeader($headers);
$address = $to;
$mail->AddAddress($address, $address);
$mail->AddAttachment($attachment, "factuur.pdf", $encoding = 'base64', $type = 'application/pdf');
if(!$mail->Send()) {
echo "Fout";
} else {
echo "Goed";
}
Anyone an idea how to resolve this?
try removing:
$body = preg_replace('/\[\]/',"",$message);
and
$headers = "Content-Type:text/html\n";

How to format my email php mailer

When I send the email with html tags.Gmail shows the tags also.Why is that? any solution?how to ad images bold text colored text according to my code?
here is my email content code
smtpmailer("$email", 'website#yahoo.com', '<html><body>website.lk Password recovery', 'Password recovery','Dear "'.$name."\"\n\nUse your new password to login and reset your password as you wish.\nTo reset password go to your \"My Account\" page and click \"Change my password\"\n\n"."Here is your new password:\n\n"."Password: "."$password"."\n\nBack to get bump: www.website.lk\n\nRegards,\n website.lk Admin\n</body></html>");
$reset_msg="Recovery completed. Check your e-mail !";
}else{
$reset_msg="Error in sending email.Try again !";
}
By including the below headers
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'To: Mary <mary#example.com>, Kelly <kelly#example.com>' . "\r\n";
$headers .= 'From: Birthday Reminder <birthday#example.com>' . "\r\n";
$headers .= 'Cc: birthdayarchive#example.com' . "\r\n";
$headers .= 'Bcc: birthdaycheck#example.com' . "\r\n";
mail($to, $subject, $message, $headers);
Source,
http://php.net/manual/en/function.mail.php
if you are using PHP Mailer,
$mail->MsgHTML($body);
$mail->AddAttachment("images/image1.gif");
$mail->AddAttachment("images/image2.gif");
if you are using this function:
function smtpmailer($to, $from, $from_name, $subject, $body) {
global $error;
$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 0; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}
Then change the line of $mail->Body = $body; to code blow:
$mail->MsgHTML($body);
This change will allow you to send HTML emails via PHPMailer, You can also add $mail->CharSet = 'UTF-8'; to avoid future problems with special characters ...
Use $mail->IsHTML(ture);
If on phpmailer..