I have the following function to send e-mails in powershell with attachments:
param
(
[parameter(Mandatory = $false)]
[string]$l
)
function SendMail(){
if($e -ine '')
{
$mail = New-Object System.Net.Mail.MailMessage
$mail.From = $f;
$mail.To.Add($t);
$mail.Subject = $s;
$att = New-Object System.Net.Mail.Attachment –ArgumentList $l
$mail.Attachments.Add($att)
$mail.Body = $b;
$smtp = New-Object System.Net.Mail.SmtpClient($serv);
$smtp.Send($mail);
}
}
When I try to send a .txt file attachment it seems to strip out all of the information from within the text file. Any suggestions as to what's going wrong?
I basically used your same code - and a great variety of attachments all came through just fine. I am fairly confident your problem is outside of PowerShell - do you have a SPAM or other filter setup on the SMTP server you are communicating with? is there another SMTP server you can talk to that is clean?
For reference, here is the sample code I was tweaking parameters to test with:
You can significantly shorten the code by using Send-MailMessage (the V2 cmdlet for emailing). This might also solve your problem, because of a couple of things:
An example that uses Send-MailMessage is below. In it, a hashtable of parameters is created and, by using the @ instead of $ in front of the variable name, each of the parameters becomes a parameter to Send-MailMessage.
For more examples, see: Sending Automated Emails with Send-MailMessage, ConvertTo-HTML, and the PowerShell Pack's Task Scheduler Module
I believe this is a much more "PowerShell" way to do things, and I hope it gets rid of your issue.
Hope this helps,
James
if($e -ine '') -ine seems to be a typo?
you really should include the values... When you create the attachment, maxybe there is a problem with the path or filename? Try to use the "FullName"(path+filename) of the File.