简体   繁体   中英

Email sending in powershell

For some reason this function works fine on one computer but throws an error when copy/pasted on another computer

error

Exception calling "Send" with "1" argument(s): "Failure sending mail."
At line:21 char:5
+     $smtp.send($message)
+     ~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SmtpException

function

function Send-ToEmail([string]$email, [string]$attachmentpath, [string]$subject, [string]$body){

    $message = new-object Net.Mail.MailMessage
    $message.From = "alerts@somedomain.com"
    $message.To.Add($email)
    $message.Subject = $subject
    $message.Body = $body
    
    $attachment = New-Object Net.Mail.Attachment($attachmentpath)
    $message.Attachments.Add($attachment)
    
    $smtp = new-object Net.Mail.SmtpClient("smtp.somedomain.com", "587")
    $smtp.EnableSSL = $true
    $smtp.Credentials = New-Object System.Net.NetworkCredential("alerts@somedomain.com", "passwordhere")
    $smtp.send($message)
    
    $attachment.Dispose()
    }

Send-ToEmail  -email "recepient@somedomain.com" -attachmentpath "c:\temp\transfer.log" -subject "[SUCCESS] Data extracts" -body "Extracts were uploaded successfully!"

Try this:

function Send-ToEmail([string]$email, [string]$attachmentpath, [string]$subject, [string]$body){

    $fromaddress = "alerts@somedomain.com" 
    $smtpserver = "smtp.somedomain.com" 

    $message = New-Object System.Net.Mail.MailMessage 
    $message.From = $fromaddress
    $message.To.Add($email)
    $message.IsBodyHtml = $True
    $message.Subject = $Subject 
    $attach = New-Object Net.Mail.Attachment($attachmentpath) 
    $message.Attachments.Add($attach) 
    $message.body = $body 
    $smtp = New-Object Net.Mail.SmtpClient($smtpserver) 
    $smtp.Send($message)
}

Send-ToEmail  -email "recepient@somedomain.com" -attachmentpath "c:\temp\transfer.log" -subject "[SUCCESS] Data extracts" -body "Extracts were uploaded successfully!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM