0

I'm using requests-html to scrape a page and some of its text includes special characters, such as \u201D and \u2022. Then I'm emailing some data using stmplib, but I'm getting this error, for example:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 570-571: ordinal not in range(128)

The string of text in question is result_title.

import os
import smtplib
from requests_html import HTMLSession

session = HTMLSession()

def send_email(type, data):
  with smtplib.SMTP('smtp.gmail.com', 587) as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.ehlo()
    smtp.login(EMAIL_ADDRESS, EMAIL_PASSWORD)

    to = 'toemail@example.com'
    addresses = [to]
    subjectType = f'NEW EBAY RESULT(S) FOR: {type}'
    subject = subjectType
    body = data
    msg = f'Subject: {subject}\n\n{body}'

    smtp.sendmail(EMAIL_ADDRESS, addresses, msg)

response = session.get('https://www.ebay.com/sch/i.html?_from=R40&_nkw=blink+182&_sacat=0&_sop=10&rt=nc&LH_PrefLoc=2')
result = response.html.find('ul.srp-results li.s-item')
result_title = result.find('h3.s-item__title', first=True).text.replace('New Listing', '')

send_email(result_title)
Mario Parra
  • 1,504
  • 3
  • 21
  • 46
  • Show your SMTP-related code…! – deceze Jul 14 '22 at 15:16
  • Your question is about smtplib but you don't show any smtplib code? – Mark Ransom Jul 14 '22 at 15:17
  • 1
    @MarkRansom The SMTP part is uninteresting; this fails because they are passing in a random string rather than a well-formed RFC822 message. – tripleee Jul 14 '22 at 15:30
  • @tripleee Thanks, that questions helps clear up when I already knew, but not how to implement it in my script, which was my real question. When I use `MIMETEXT()` on `subject` and `body`, I get a lot of strange characters in the body and the subject becomes `Content-Type: text/plain; charset="utf-8"`. – Mario Parra Jul 14 '22 at 18:07
  • E.g. https://stackoverflow.com/a/72076020/874188 demonstrates how to assemble and send an email message with an attachment. – tripleee Jul 14 '22 at 18:50
  • @tripleee Are special characters considered attachments? – Mario Parra Jul 15 '22 at 13:08
  • @MarioParra No. – deceze Jul 15 '22 at 13:10
  • @deceze Didn't think so, I'm still trying to figure out how to implement this into my code. – Mario Parra Jul 15 '22 at 13:15
  • 1
    I'm thinking you would attach `data` as an attachment, though of course, you could also `message.set_content(data)` to provide it as the main contents of the message. – tripleee Jul 15 '22 at 14:00

0 Answers0