Friday, September 22, 2017

PowerShell: Invoke-WebRequest Android Police RSS Feed Emailer

I like Android Police and used to have their mailer but it was quirky so I wrote a RSS Feed reader which then sends an email.  I have it kick off daily via a scheduled task from my server and I get my daily dose.

[xml]$ap = iwr http://www.androidpolice.com/feed/
$articles = $ap.getelementsbytagname('item')

foreach ($a in $articles){
$link = $a.link
$comments = ($a.link + "#comments")
$title = $a.title
$title = $title -replace ('\[','"')
$title = $title -replace ('\]','"')
$html = New-Object -ComObject "HTMLFile"
$description =  ($a.description.'#cdata-section')
$html.IHTMLDocument2_write($description)
$imglink = $html.body.getelementsbytagname('img')[0].src
$text = $html.body.innertext
$text = $text -replace ('\[','"')
$text = $text -replace ('\]','"')
$text = $text -replace ('Read More\s+')
$text = $text -replace ($title)
$text = $text.replace(" was written by the awesome team at Android Police.","")
$text = $text.trim()
$text = $text + " <a href=$comments>Comments</a>"
$a.pubdate = ("<table width='100%'><tr><td style='font-family: Arial, sans-serif;'><a href=$link><img width=200 align=left src=" + $imglink + "></a><center><h3>" + $title + "</h3></center></td></tr></table><table><tr><td style='font-family: Arial, sans-serif;font-size:13;'>" + $text + "</td></tr></table><hr style='border: 2px solid mintcream;'>")

[System.Runtime.Interopservices.Marshal]::ReleaseComObject($html)|out-null
}

$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$Username = "myaccount@gmail.com"
$Password = "mypassword"
$to = "recipient@somemail.com"
$subject = ("Android Police - " + (get-date).tolongdatestring())
$message = New-Object System.Net.Mail.MailMessage
$message.subject = $subject
$message.body = $articles.pubdate
$message.to.add($to)
$message.from = $username
$message.IsBodyHTML = $true
$smtp = New-Object System.Net.Mail.SmtpClient($SMTPServer, $SMTPPort);
$smtp.EnableSSL = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($Username, $Password);
$smtp.send($message)

No comments: