[Python] How to make email content more appealing with bold titles in Python using NewsAPI?

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    I am building a simple Python app that fetches data from NewsAPI and sends the result as an email to a user-provided email address. The app works and successfully sends the email, but I want to make the email content more visually appealing—for instance, making the news titles bold. This is my code:

    import os
    from dotenv import load_dotenv
    import requests
    from send_email import send_email

    load_dotenv()
    key = os.getenv("API_NEWS_KEY")
    def main():
    url = f"https://newsapi.org/v2/everything?q=tesla&from=2025-03-06&sortBy=publishedAt&apiKey={key}"

    request = requests.get(url)
    content = request.json()

    mail_Body = " **Latest News Articles about From NewsAPI** \n\n"
    for article in content["articles"]:
    if article["title"] is not None:
    mail_Body += f"**Title:** {article['title']}\n"
    mail_Body += f"**Description:** {article['description']}\n"
    mail_Body += "-" * 40 + "\n\n"

    user_email = input("Which email do you want to receive email? ")

    # Ensure the email body is encoded in UTF-8
    send_email(user_email, mail_Body)
    print("Email sent!!!!")

    if __name__ =="__main__":
    main()


    and my send_email function:

    import smtplib, ssl
    import os
    from dotenv import load_dotenv
    from email.message import EmailMessage

    load_dotenv()
    email = os.getenv("usernameemail")
    email_password = os.getenv("password")

    print(email)
    print(email_password)

    def send_email(receiver,news):
    host = "smtp.gmail.com"
    port = 465

    username = email
    password = email_password
    message = EmailMessage()
    message["From"] = username
    message["To"] = receiver
    message["Subject"] = "Latest new from API News"
    message.set_content(f"This is the latest new from NewsApi: \n \n{news} ", charset ="utf-8")

    context = ssl.create_default_context()

    try:
    with smtplib.SMTP_SSL(host, port, context=context) as server:
    server.login(username, password)
    print("Login successful")
    server.send_message( message)
    print("Email sent successfully")
    except Exception as e:
    print(f"An error occurred: {e}")

    Continue reading...

Compartilhe esta Página