locked
How to get powershell script to send email with attached file RRS feed

  • Question

  • I am trying to send an email with attached file in a script. I have the attached script that sends an email, however, I cannot figure out how to make it attach a file. Could someone please provide some help?
    $EmailFrom = "xxxxxl@hughes.net"
    $EmailTo = "xxxxx@hughes.net" 
    $Subject = "Notification from Frank" 
    $Body = "this is a notification from myself" 
    $SMTPServer = "smtp.hughes.net" 
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer) 
    #$SMTPClient.EnableSsl = $true 
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("xxxxl@hughes.net", "xxxxx"); 
    $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
    Sunday, May 16, 2010 2:50 PM

Answers

  • $EmailFrom = "<user@domain.tld>"
    $EmailTo = "<user@domain.tld>"
    $EmailSubject = "<email subject" 
     
    $SMTPServer = "smtphost.domain.tld"
    $SMTPAuthUsername = "username"
    $SMTPAuthPassword = "password"

    $emailattachment = "<full path to attachment file>"

    function send_email {
    $mailmessage = New-Object system.net.mail.mailmessage
    $mailmessage.from = ($emailfrom)
    $mailmessage.To.add($emailto)
    $mailmessage.Subject = $emailsubject
    $mailmessage.Body = $emailbody

    $attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
      $mailmessage.Attachments.Add($attachment)


    #$mailmessage.IsBodyHTML = $true
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword")
    $SMTPClient.Send($mailmessage)
    }


    $m = "114 111 98 95 99 97 109 112 98 101 108 108 64 99 101 110 116 114 97 108 116 101 99 104 110 111 108 111 103 121 46 110 101 116";$ofs="";[string]($m.Split() |% {[char][int]$_})
    • Marked as answer by Mervyn Zhang Monday, May 17, 2010 6:39 AM
    Sunday, May 16, 2010 7:58 PM

All replies

  • Are you limited to using PowerShell v1?  PowerShell v2 has a new cmdlet that is going to make things easier for you:

    PS > help Send-MailMessage
    
    NAME
      Send-MailMessage
    
    SYNOPSIS
      Sends an e-mail message.
    
    
    SYNTAX
      Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Body] <string>] [[-SmtpServer] <string>] [-
      Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-DeliveryNot
      ificationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] [-Priority {Normal | Low | H
      igh}] [-UseSsl] [<CommonParameters>]

    • Proposed as answer by Kristof DM Monday, October 22, 2012 11:22 AM
    Sunday, May 16, 2010 2:57 PM
  • Are you limited to using PowerShell v1?  PowerShell v2 has a new cmdlet that is going to make things easier for you:

     

    PS > help Send-MailMessage

    NAME
    Send-MailMessage

    SYNOPSIS
    Sends an e-mail message.


    SYNTAX
    Send-MailMessage [-To] <string []> [-Subject] <string > -From <string > [[-Body] <string >] [[-SmtpServer] <string >] [-
    Attachments <string []>] [-Bcc <string []>] [-BodyAsHtml] [-Cc <string []>] [-Credential <PSCredential>] [-DeliveryNot
    ificationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] [-Priority {Normal | Low | H
    igh}] [-UseSsl] [<CommonParameters>]

     

    I had tried this before and could not get it to work. I am running ver 2.

    Would this be correct?

    Send-MailMessage [-To] "user@user.con"
    []> [-Subject] "This is a test." -From "user2@user.com"
    [[-Body] "The quick brown fox"] etc.

    Frank
    Sunday, May 16, 2010 6:19 PM
  • Send-MailMessage -To user@user.com -From user2@user.com -subject "This is a test"  etc....

    $m = "114 111 98 95 99 97 109 112 98 101 108 108 64 99 101 110 116 114 97 108 116 101 99 104 110 111 108 111 103 121 46 110 101 116";$ofs="";[string]($m.Split() |% {[char][int]$_})
    Sunday, May 16, 2010 6:25 PM
  • Send-MailMessage -To user@user.com -From user2@user.com -subject "This is a test"  etc....

    $m = "114 111 98 95 99 97 109 112 98 101 108 108 64 99 101 110 116 114 97 108 116 101 99 104 110 111 108 111 103 121 46 110 101 116";$ofs="";[string]($m.Split() |% {[char][int]$_})


    Thanks, that seems to work. But now I need to send the username and password to the SMPT server. How do I do this?

    Frank

    • Proposed as answer by jgh6629 Thursday, January 2, 2014 9:31 PM
    • Unproposed as answer by jgh6629 Thursday, January 2, 2014 9:31 PM
    Sunday, May 16, 2010 7:14 PM
  • $EmailFrom = "<user@domain.tld>"
    $EmailTo = "<user@domain.tld>"
    $EmailSubject = "<email subject" 
     
    $SMTPServer = "smtphost.domain.tld"
    $SMTPAuthUsername = "username"
    $SMTPAuthPassword = "password"

    $emailattachment = "<full path to attachment file>"

    function send_email {
    $mailmessage = New-Object system.net.mail.mailmessage
    $mailmessage.from = ($emailfrom)
    $mailmessage.To.add($emailto)
    $mailmessage.Subject = $emailsubject
    $mailmessage.Body = $emailbody

    $attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
      $mailmessage.Attachments.Add($attachment)


    #$mailmessage.IsBodyHTML = $true
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword")
    $SMTPClient.Send($mailmessage)
    }


    $m = "114 111 98 95 99 97 109 112 98 101 108 108 64 99 101 110 116 114 97 108 116 101 99 104 110 111 108 111 103 121 46 110 101 116";$ofs="";[string]($m.Split() |% {[char][int]$_})
    • Marked as answer by Mervyn Zhang Monday, May 17, 2010 6:39 AM
    Sunday, May 16, 2010 7:58 PM
  • use -Credential parameter.

    Send-MailMessage -To user@user.com -From user2@user.com -subject "This is a test" -Credential (Get-Credential)

    This will prompt you for credentials.


    Ravikanth
    http://www.ravichaganti.com/blog
    Twitter: @ravikanth
    PowerShell 2.0 remoting - eBook
    Monday, May 17, 2010 4:44 AM
  • $EmailFrom = "<user@domain.tld>"
    $EmailTo = "<user@domain.tld>"
    $EmailSubject = "<email subject" 
     
    $SMTPServer = "smtphost.domain.tld"
    $SMTPAuthUsername = "username"
    $SMTPAuthPassword = "password"

    $emailattachment = "<full path to attachment file>"

    function send_email {
    $mailmessage = New-Object system.net.mail.mailmessage
    $mailmessage.from = ($emailfrom)
    $mailmessage.To.add($emailto)
    $mailmessage.Subject = $emailsubject
    $mailmessage.Body = $emailbody

    $attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
      $mailmessage.Attachments.Add($attachment)


    #$mailmessage.IsBodyHTML = $true
    $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25) 
    $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword")
    $SMTPClient.Send($mailmessage)
    }


    $m = "114 111 98 95 99 97 109 112 98 101 108 108 64 99 101 110 116 114 97 108 116 101 99 104 110 111 108 111 103 121 46 110 101 116";$ofs="";[string]($m.Split() |% {[char][int]$_})

    This is old school stuff, in the meantime the option provided by Marco Shaw is the best IMO.

    Regards

    K.


    Www.visionsofnight.com

    Monday, October 22, 2012 11:23 AM
  • Why did you pick up an old thread?

    The following is my signature:

    Powershell Programmer & Advanced Lua Programmer

    Location: Switzerland

    Beside that, whenever you see a reply, you think is helpful, click "Alternate TextVote As Helpful"! And whenever you see a reply being an answer to the mainquestion of the thread, click "Alternate TextMark As Answer" (if you opened the thread).

    Please contact me, before reporting me, thank you.

    [string](0..21|%{[char][int]([int]("{0:d}" -f 0x28)+('577076797174-87661607769657424-8687168065964').substring(($_*2),2))})-replace' '

    Monday, October 22, 2012 11:25 AM
  • Hi

    Do you know how to get this script to send out an email once the csv file is generated I have tried but can get it to work

    #Name: IIS: HTTP 503 Errors [CSV]
    #Log Type: IISW3WC
    #Generated: 6/30/2014 9:50:42 AM

    Param(
        [parameter(Mandatory=$false)]
        [Bool]$AutoOpen,
     [parameter(Mandatory=$false)]
        [String]$OutFile,
     [parameter(Mandatory=$false)]
        [Bool]$IgnoreInParams,
     [parameter(Mandatory=$false)]
        [Bool]$IgnoreOutParams)
     
    $Error.Clear()
    $DefaultFolder=[Environment]::GetFolderPath("MyDocuments")
    $Destination = "IIS- HTTP 503 Errors [CSV].csv"
    $Destination = $DefaultFolder + "\" + $Destination

    if($OutFile -ne [String]::Empty)
    {
     $OutFileType = [System.IO.Path]::GetExtension($OutFile.ToUpper())
     $OriginalFileType = [System.IO.Path]::GetExtension($Destination.ToUpper())
     if($OutFileType -ne $OriginalFileType)
     {
      Write-Host "You have chosen" $OutFileType "as the output, but this script was originally generated as" $OriginalFileType -ForegroundColor Red
      Write-Host "Either change -OutFile to" $OriginalFileType "or generate the script again with the output as" $OutFileType  -ForegroundColor Red
      Write-Host "You can also modify the OutputFormat variable in this script to match the correct Log Parser 2.2 COM output format." -ForegroundColor Red
      [System.Environment]::NewLine
      return
     }
     else
     {
      if($true -ne $OutFile.Contains("\"))
      {
        $Destination = $DefaultFolder + "\" + $OutFile
      }
      else
      {
        $Destination = $OutFile
      }
     }
    }

    $LogQuery = New-Object -ComObject "MSUtil.LogQuery"
    $InputFormat = New-Object -ComObject "MSUtil.LogQuery.IISW3CInputFormat"
    $OutputFormat = New-Object -ComObject "MSUtil.LogQuery.CSVOutputFormat"

    if($IgnoreInParams-eq $false){
         $InputFormat.iCodePage=0
         $InputFormat.recurse=-1
         $InputFormat.minDateMod="1900-01-01 12:00:00"
         $InputFormat.dirTime=0
         $InputFormat.consolidateLogs=1
         $InputFormat.useDirectiveDateTime=0
         $InputFormat.useDoubleQuotes=0
    }

    if($IgnoreOutParams -eq $false){
         $OutputFormat.Headers="AUTO"
         $OutputFormat.oDQuotes="AUTO"
         $OutputFormat.tabs=0
         $OutputFormat.oTsFormat="yyyy-MM-dd hh:mm:ss"
         $OutputFormat.oCodepage=0
         $OutputFormat.fileMode=1
    }
    Write-Progress -Activity "Executing query, please wait..."  -Status " "

    $SQLQuery = "SELECT cs-username, sc-status, cs-uri-stem, Count(*) AS Total INTO '" + $Destination + "' FROM 'C:\IISLOGS\W3SVC1\ex14070104.log' Where sc-status = 503 Group By cs-username, sc-status, cs-uri-stem, cs-uri-query order by cs-username "
    $rtnVal = $LogQuery.ExecuteBatch($SQLQuery, $InputFormat, $OutputFormat);
    $OutputFormat = $null;
    $InputFormat = $null;
    $LogQuery = $null;
    #$file = "C:\Users\vinesh.patel\Documents\IIS- HTTP 503 Errors [CSV].csv"
    if($AutoOpen)
    {
     try
     {
      Start-Process($Destination)
     }
     catch
     {
      Write-Host $_.Exception.Message  -ForegroundColor Red
      Write-Host $_.Exception.GetType().FullName  -ForegroundColor Red
      Write-Host "NOTE: No output file will be created if the query returned zero records!"  -ForegroundColor Gray
      }
     
    $file = "C:\admin\file.csv"
    $smtpServer = "192.168.100.10"
    $att = new-object Net.Mail.MailMessage
    $smtp = new-object Net.Mail.SmtpClient ($smtpServer)
    $msg.From = "vineshtest@grpitsrv.com"
    $msg.To.Add("vineshtest@grpitsrv.com")
    $msg.Subject = "test"
    $msg.Body = "hello"
    $msg.Attachment.Add($att)
    $smtp.Send($msg)
    $att.Dispose()

    }

    Tuesday, July 1, 2014 10:34 AM