Solved

Power Shell - SendEmail function

Posted on 2013-05-16
9
263 Views
Last Modified: 2014-06-24
Hi,

I am running another PS script (not listed here) and the output of that script I need to email to myself. Below is what I would like to use but can not figure out which fields need to be entered with my organisations details. Can someone please mark what and where I need to put my company's details below so this will work.




Function sendEmail  
{ param($from,$to,$subject,$smtphost,$htmlFileName)  
$body = Get-Content $htmlFileName  
$smtp= New-Object System.Net.Mail.SmtpClient $smtphost  
$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body  
$msg.isBodyhtml = $true  
$smtp.send($msg)  
}  
 
writehtmlheader $fileName  
writetableheader $fileName  
get-DBInfo  
writehtmlfooter $fileName  
 
sendEmail User@Domain.com User@DOMAIN.com "Database Report" server1 $fileName
0
Comment
Question by:Agilityapps
  • 5
  • 4
9 Comments
 
LVL 39

Accepted Solution

by:
footech earned 500 total points
ID: 39173958
What isn't working?
I'm guessing you might have a problem with the body.  You might try one of the following:
$body = Get-Content $htmlFileName | Out-String
$body = (Get-Content $htmlFileName) -join "`r`n"


BTW, I'm not sure what the function is getting you.  Unless you needed to authenticate or use a port other than 25 I would just use Send-MailMessage.
Send-MailMessage `
    -from User@Domain.com `
    -to User@DOMAIN.com `
    -subject "Database Report" `
    -smtpserver server1 `
    -body ((Get-Content $FileName) -join "`r`n") `
    -bodyAsHtml

Open in new window

0
 

Author Comment

by:Agilityapps
ID: 39182882
I am very new to PS scripts, the previous response did not seem to work. I have attached the whole script so you can see what I am trying to do. This script needs to be run from  a remote server (our Task Server) and run on our Exchange server. The output of this script is then needed to be emailed out. Please help!!
0
 
LVL 39

Assisted Solution

by:footech
footech earned 500 total points
ID: 39182936
Script was not attached.
0
 

Author Comment

by:Agilityapps
ID: 39182942
Sorry, try again.
Exchange-TEST-Report.txt
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 39

Assisted Solution

by:footech
footech earned 500 total points
ID: 39183662
I generated an html file that just had the html header, table headers, and html footer from your script, saved it as "DBReport.html", and tested with the below code which works just fine.
Function sendEmail
{
param($from,$to,$subject,$smtphost,$htmlFileName) 
$body = Get-Content $htmlFileName
$smtp = New-Object System.Net.Mail.SmtpClient $smtphost  
$msg = New-Object System.Net.Mail.MailMessage $from, $to, $subject, $body  
$msg.isBodyhtml = $true  
$smtp.send($msg)  
}

$emailFrom = "ps-test@company.com"
$emailto = "someone@company.com"
$subject = "TEST_Report" 
$smtpserver = "mail.company.com"
sendEmail $emailFrom $emailTo $subject $smtpserver $fileName

Open in new window


The below also works.
$emailFrom = "ps-test@company.com"
$emailto = "someone@company.com"
$subject = "TEST_Report" 
$smtpserver = "mail.company.com"
Send-MailMessage `
    -from $emailFrom `
    -to $emailTo `
    -subject $subject `
    -smtpserver $smtpserver `
    -body ((Get-Content $fileName) -join "`r`n") `
    -bodyAsHtml

Open in new window


Work on one thing at a time.  Get the script portions working locally before worrying about remote function.  It appears that file generation is working just fine - just make sure you know where the file is going to be created and that permissions won't be an issue.  Both the samples I posted above work fine for sending the email.  Then you can work on the remote function.

I'm assuming from the script you posted, that the first command (line 2), is actually the command you use to call the script, and that everything else is actually the code for "myscript.ps1" that you want to run remotely.  I can't troubleshoot the whole thing, but here are some things I noticed.
 - There's a disconnect between lines 5 and 10 - are you meaning for $filename to be the file that you create in line 5?  Pay attention to what I said about file location and permissions.
 - The WriteData function doesn't have a closing brace (there is an opening brace at the end of the function)
 - This is more just code optimization since what you have will work, but instead of having dozens of Add-Content commands you can just construct a single Here-String, and then write that to a file.  This avoids having to open and close the file repeatedly, which is an expensive operation, and can also make for more readable code.  An example is below.
Function writeHtmlHeader  
{  
param($fileName)  
$date = ( Get-Date ).ToString('yyyy/MM/dd')  
$style = @"
<html>
<head>  
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>  
<title>myExchangeWorld.COM Database Report</title>
<STYLE TYPE=text/css>
 <!--  
 td {  
 font-family: Tahoma;  
 font-size: 11px;  
 border-top: 1px solid #999999;  
 border-right: 1px solid #999999;  
 border-bottom: 1px solid #999999;  
 border-left: 1px solid #999999;  
 padding-top: 0px;  
 padding-right: 0px;  
 padding-bottom: 0px;  
 padding-left: 0px;  
 }  
 body {  
 margin-left: 5px;  
 margin-top: 5px;  
 margin-right: 0px;  
 margin-bottom: 10px;  
   
 table {  
 border: thin solid #000000;  
 }  
 -->  
 </style>  
</head>  
<body>  
 <table width='100%'>  
 <tr bgcolor='#CCCCCC'>  
 <td colspan='7' height='25' align='center'>  
 <font face='tahoma' color='#003399' size='4'><strong>myExchangeWorld.COM Database Report - $date</strong></font>  
 </td>  
 </tr>  
 </table>
"@
 Add-Content $fileName $style

Open in new window

0
 

Author Comment

by:Agilityapps
ID: 39186319
Thanks, I have tried using your first option in your post from yesterday. I have filled out with my company's details. Now Im getting the below message; Should there be a '{' at the end of line 15?

Missing closing '}' in statement block.
At H:\Exchange_TEST_Report.ps1:243 char:62
+ sendEmail $emailFrom $emailTo $subject $smtpserver $fileName> <<<<
    + CategoryInfo          : ParserError: (CloseBraceToken:TokenId) [], ParseException
    + FullyQualifiedErrorId : MissingEndCurlyBrace
0
 
LVL 39

Assisted Solution

by:footech
footech earned 500 total points
ID: 39186638
No.  There's probably a mismatch between opening and closing braces elsewhere in the script like the one I pointed out for the Write-Data function.  Did you correct that?
I noticed that my copy-paste of the code I posted for the writeHtmlHeader function didn't include it's closing brace if you decide to use it.

The ISE w/ PowerShell 3.0 includes brace matching which makes finding problems like that much easier. I believe Power GUI does as well, but I haven't used it.
0
 

Author Comment

by:Agilityapps
ID: 39189367
Thanks for that, that part now works.

Next issue: the script seems to run fine now, no error occurs. But now there is no output, the file gets create from line 3, but no info in getting pulled from the Exchange server into the report. Does line 147 to 157 (in particular lines 147 to 149) need to have our company's details entered in. ie; server name, edb file path.

I have attached the update script in text format for you.

Below is what Im getting when the script completes;

Mode                LastWriteTime                     Length              Name
----                     -------------                               ------                   ----
-a---                   23/05/2013  8:12 AM           0                      Exchange_Test_Report.html
Exchange-TEST-Report.txt
0
 
LVL 39

Assisted Solution

by:footech
footech earned 500 total points
ID: 39189509
That is the output from line 3.  Are you running the script from c:\temp?  If I were you I would move line 8 up and insert it at line 3, and make changes like below.
$fileName = "c:\temp\Exchange_Test_Report.html"
New-Item -ItemType file -Path $fileName -force

Open in new window


Your code still has problems with brace matching.  Remove the closing brace from line 173 and insert one at line 168.

I really can't advise you on the Exchange cmdlets.  But if you were to run 144-167 do you get expected output?
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In this previous article (https://oddytee.wordpress.com/2016/05/05/provision-new-office-365-user-and-mailbox-from-exchange-hybrid-via-powershell/), we made basic license assignments to users in O365. When I say basic, the method is the simplest way …
"Migrate" an SMTP relay receive connector to a new server using info from an old server.
Learn several ways to interact with files and get file information from the bash shell. ls lists the contents of a directory: Using the -a flag displays hidden files: Using the -l flag formats the output in a long list: The file command gives us mor…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.

706 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now