Adam
Adam

Reputation: 243

Unable to embedded image in email using Send-Mailmessage

I am a PowerShell novice and am having issues with embedding an image in an automated email. I am using a modified version of Robert Pearman's script from Technet. The email itself is sent to any user who's password will expire in the next 14 days.

The script scans AD for the accounts, retrieves all the details and sends them an email individualized to them.

Everything I've read on embedding the image with HTML into the email fails. It appears so simple however the email always displays the red X HTML placeholder image when the email arrives.

$smtpServer= "SMTP.company.biz" 
$expireindays = 14
$from = "Helpdesk <[email protected]>"
$logging = "Disabled" # Set to Disabled to Disable Logging
$logFile = "<log file path>" # ie. c:\mylog.csv
$testing = "Enabled" # Set to Disabled to Email Users
$testRecipient = "[email protected]"
$date = Get-Date -format dd-MM-yyyy
#$images = @{image1='D:\Script_Folder\Overwatch_images\FFPasswordChange.jpg'}
$AttachmentPath = "D:\Script_Folder\Overwatch_Images\FFPasswordChange.jpg"
$Attachment = New-Object System.Net.Mail.Attachment($AttachmentPath)
$Attachment.ContentID = "image1"

# Check Logging Settings
if (($logging) -eq "Enabled")
{
# Test Log File Path
$logfilePath = (Test-Path $logFile)
if (($logFilePath) -ne "True")
{
    # Create CSV File and Headers
    New-Item $logfile -ItemType File
    Add-Content $logfile "Date,Name,EmailAddress,DaystoExpire,ExpiresOn"
}
} # End Logging Check

# Get Users From AD who are Enabled, Passwords Expire and are Not   Currently Expired
Import-Module ActiveDirectory
$users = get-aduser -filter {MemberOf -eq "Group1,OU=Groups,OU=Group   Companies,DC=Company,DC=Biz"} -searchbase "OU=Users,OU=Group Companies,DC=Company,DC=Biz"   -properties Name, PasswordNeverExpires, PasswordExpired, PasswordLastSet,   EmailAddress, samaccountname | where {$_.Enabled -eq "True"} | where {   $_.PasswordNeverExpires -eq $false } | where { $_.passwordexpired -eq $false   }
$DefaultmaxPasswordAge = (Get-  ADDefaultDomainPasswordPolicy).MaxPasswordAge


# Process Each User for Password Expiry
foreach ($user in $users)
{
$Name = $user.Name
$emailaddress = $user.emailaddress
$passwordSetDate = $user.PasswordLastSet
$samaccountname = $user.samaccountname
$PasswordPol = (Get-AduserResultantPasswordPolicy $user)
# Check for Fine Grained Password
if (($PasswordPol) -ne $null)
{
    $maxPasswordAge = ($PasswordPol).MaxPasswordAge
}
else
{
    # No FGP set to Domain Default
    $maxPasswordAge = $DefaultmaxPasswordAge
}


$expireson = $passwordsetdate + $maxPasswordAge
$today = (get-date)
$daystoexpire = (New-TimeSpan -Start $today -End $Expireson).Days

# Set Greeting based on Number of Days to Expiry.

# Check Number of Days to Expiry
$messageDays = $daystoexpire

if (($messageDays) -ge "1")
{
    $messageDays = "in " + "$daystoexpire" + " Tagen"
}
else
{
    $messageDays = "heute."
}

# Email Subject Set Here
$subject="Ihr eIPN Passwort endet $messageDays"


$body = "
<HTML>
<BODY>
Sehr geehrter Comany User,
<p> Ihr eIPN Passwort f&uuml;r den Account $samaccountname l&auml;uft  $messageDays ab.<br>
<p> Damit Sie sicher und problemlos weiterarbeiten k&ouml;nnen, bitten wir Sie Ihr Passwort schnellstm&ouml;glich zu &auml;ndern.<br>
<p> Um Ihr eIPN Passwort zu &auml;ndern, dr&uuml;cken Sie bitte STRG-ALT- ENTF und w&auml;hlen Sie 'Kennwort &auml;ndern...' aus.<br>
<br>
<img src='CID:image1'>
<br>
<p> Sollten Sie sich im Au&szlig;endienst oder nicht im B&uuml;ro befinden, stellen Sie bitte vorher eine aktive VPN-Verbindung her.<br>
<p> Bei Problemen oder Fragen wenden Sie sich bitte an die Helpdesk unter der +49 9999 999999.<br>
<p> Mit freundlichen Gr&uuml;&szlig;en, <br>
Deutschland Helpdesk <br> 
</P>
</body>
</HTML>"


# If Testing Is Enabled - Email Administrator
if (($testing) -eq "Enabled")
{
    $emailaddress = $testRecipient
} # End Testing

# If a user has no email address listed
if (($emailaddress) -eq $null)
{
    $emailaddress = $testRecipient    
}# End No Valid Email

# Send Email Message
if (($daystoexpire -ge "0") -and ($daystoexpire -lt $expireindays))
{
     # If Logging is Enabled Log Details
    if (($logging) -eq "Enabled")
    {
        Add-Content $logfile    "$date,$Name,$emailaddress,$daystoExpire,$expireson" 
    }

    # Set Parameters
    $params = @{
    #InlineAttachements = $Images
    #Attachments = 'D:\Script_Folder\Overwatch-  Images\FFPasswordChange.jpg'
    Body = $body
    BodyasHTML = $true
    Subject = $subject
    From = $from
    To = $emailaddress
    SMTPServer = $smtpServer
    }

    # Send Email Message
    Send-Mailmessage @params -Priority High

    # -smtpServer $smtpServer -from $from -to $emailaddress -subject   $subject -body $body -bodyasHTML -InlineAttachments $images -priority High  


} # End Send Message

} # End User Processing



# End

I still have some of my earlier attempts hashed out within the code. I feel like I was on the right path but it never executed correctly.

If anyone can see where I am going wrong or point me in the right direction, that would be most appreciated!

Upvotes: 1

Views: 6669

Answers (1)

Matt
Matt

Reputation: 46690

If you have PowerShell v4 then this would work using splatting and Send-MailMessage.

$attachment = Get-Item C:\temp\WhiteLogo.png

$params = @{
    To = "address"
    From = "address"
    SMTPServer = "theIP"
    Subject = "Stuff"
    BodyAsHTML = $true
    Body = 'Testing Inline <br /><img src="{0}" />' -f ($attachment.Name)
    Attachments = $attachment.FullName
}

Send-MailMessage @params

The logic appears to have improved for referencing inline images in v4.

Upvotes: 3

Related Questions