Using a simple webscraper I am able to return the contents of what I'm looking for into variables in my script content : content1
.
For some reason, I can't get the contents to display in the email body.
I have tried using message.attach(MIMEText(mail_content, 'text'))
message.attach(MIMEText(mail_content, 'html'))
that made no difference. Also imported time
module as I thought a delay in the script might help but it did not.
from selenium import webdriver
import smtplib, ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import time
DRIVER_PATH = 'C:/Users\James\Downloads\chromedriver_win32\chromedriver.exe'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.implicitly_wait(5)
driver.get('https://www.skysports.com/football/news')
FootballHeadlines = driver.find_elements_by_class_name("news-list__headline-link")
for elem in FootballHeadlines:
print(elem.text)
print(elem.get_attribute("href"))
content = (elem.text)
content1 = (elem.get_attribute("href"))
sender_address = 'some@email'
sender_password = '**********'
receiver_email = 'someother@email'
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = sender_address
message['Subject'] = 'Latest on Football'
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender_address, sender_password)
mail_content = message.as_string(content)
message.attach(MIMEText(mail_content, 'html'))
session.sendmail(sender_address, sender_address, mail_content)
The problem wasn't in sending the email. For some reason, selenium wasn't able to get the text out of the elements it found. I used beautiful soup instead. The following code works.
import bs4 as Bs
import smtplib, ssl
from selenium import webdriver
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
DRIVER_PATH = 'D:\Webdriver\chromedriver.exe'
driver = webdriver.Chrome(executable_path=DRIVER_PATH)
driver.implicitly_wait(5)
driver.get('https://www.skysports.com/football/news')
page_src = Bs.BeautifulSoup(driver.page_source)
links = page_src.findAll("a", {"class" : "news-list__headline-link"})
content = ''
for link in links:
content +='\n'+link.text
print(content)
sender_address = 'yatint5@gmail.com'
sender_password = 'ehdqxsdsuyuicupa'
receiver_email = sender_address
message = MIMEMultipart()
message['From'] = sender_address
message['To'] = sender_address
message['Subject'] = 'Latest on Football'
message.attach(MIMEText(content, 'plain'))
session = smtplib.SMTP('smtp.gmail.com', 587)
session.starttls()
session.login(sender_address, sender_password)
mail_content = message.as_string(content)
print(mail_content)
message.attach(MIMEText(mail_content, 'html'))
session.sendmail(sender_address, sender_address, mail_content)
PS: I have revoked the app-password...