Not getting desired output in my mail with smtplib and newsapi

56 Views Asked by At

I'm writing a program which uses NewsAPI and sends me news to my mail. Everything is fine but when I get the mail it gives me all the news in one single line where I expect it to use some break lines. That is the result I get.

enter image description here

That's the code I've written.

import requests
from send_email import send_email

api_key = "xxxxx"
url = ("xxxxx")

# Make a request
request = requests.get(url)

# Get a dictionary with data
content = request.json()

body = ''
# Access the article title and description
for article in content["articles"]:
    if article["title"] is not None:
        body = body + article["title"] + "\n" + article["description"] + 2*"\n"


#   Sending article titles and description via email
body = body.encode("utf-8")
message = f"""\
Subject: Python API News

{body}
"""
send_email(message)

The code for sending email I've used is working fine. I have used it in my other program.

enter image description here

That's the result I want please help.

I haven't tried to do anything to solve it because I don't know whats causing it.

EDIT: Okay so I realized that I did'nt specified few things. First is where did I used smtplib. I'll attach the code here.

import smtplib, ssl
import os


def send_email(message):
    host = "smtp.gmail.com"
    port = 465

    username = "[email protected]"
    password = os.getenv("GMAIL_APP_PASS")

    receiver = "[email protected]"
    context = ssl.create_default_context()

    with smtplib.SMTP_SSL(host, port, context=context) as server:
        server.login(username, password)
        server.sendmail(username, receiver, message)

This is the code for for send_email which uses smtplib.

Second what is newsapi?

Thats the best documentation I can provide: Newsapi.org/docs

Is this enough or am I still missing anything? please let me know, Thank You.

2

There are 2 best solutions below

0
Efremov Egor On

Your problem might be causing this line:

body = body.encode("utf-8")

So removing encoding might help you

0
5P33DC0R3 On

Okay so I got the problem. So apparently I was trying to include a subject in the mail with

body = body.encode("utf-8")
message = f"""\
Subject: Python API News

{body}
"""
send_email(message)

But when I tried

body = body.encode("utf-8")
send_email(body)

The real problem was that subject should be inside body variable so the code sould be like this:

body = "Subject: Python API News" + "\n"
# Access the article title and description
for article in content["articles"][:10:]:
    if article["title"] is not None:
        body = body + article["title"] + "\n" + article["description"] + 2*"\n"