SMTPRecipientsRefused error, python smtplib

I want to make a script that uses nxapi to read my Nintendo Switch friend list, and send me an email if someone in the “watched” section of my configuration file comes online. My website is hosted by DreamHost. I keep getting an SMTPRecipientsRefused error when trying to send a test email.

The script:

import json
import yaml
import os
import subprocess
import smtplib
import datetime
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import random

configpath = os.path.expanduser("~/.littlebitstudios/switchfriendwatch/configuration.yaml")

try:
  config = yaml.safe_load(open(configpath))
except FileNotFoundError:
  print("No configuration file! Create a file at", configpath, "and follow the format detailed on the project page.")
  exit()

# Setting up SMTP if email is enabled
mailsender = None
if config['email']['enabled'] == True:
  print("Email enabled.")
  print("Connecting to email server")
  try:
    mailsender = smtplib.SMTP(config['email']['server'], config['email']['port'])
    print("Logging in to email server")
    mailsender.login(config['email']['user'], config['email']['pass'])
    mailsender.ehlo_or_helo_if_needed()
    mailsender.starttls()
  except (smtplib.SMTPAuthenticationError, smtplib.SMTPConnectError, smtplib.SMTPException) as e:
    print(f"Error connecting to email server: {e}")
    exit()

# Gather NSO friend data from nxapi
nxapi = subprocess.run(["nxapi", "nso", "friends", "--json"], capture_output=True)
friends = None
if nxapi.returncode == 0:
  friends = json.loads(nxapi.stdout.decode("utf-8"))
else:
  print("Error running nxapi. Please check the tool and its installation.")


lastchecktime = datetime.datetime.fromisoformat(config['lastcheck'])
print("Last run time:",lastchecktime.strftime("%b %d, %Y at %I:%M %p"))

def mailsendonline(username, game, lastchange):
  message = MIMEMultipart()
  message['From'] = config['email']['sendfrom']
  message['To'] = config['email']['sendto']
  message['Subject'] = "Switch Friend Watch: " + username + " is online playing " + game

  # Create MIMEText object for the message body
  body_text = MIMEText("Your friend " + username + " is now online playing " + game + ". nLast status update: " + lastchange.strftime("%b %d, %Y at %I:%M %p") + "." + "nnSwitch Friend Watchna tool by LittleBit", 'plain')
  message.attach(body_text)

  # Send the email using the provided SMTP object (mailsender)
  mailsender.sendmail(config['email']['sendfrom'], config['email']['sendto'], message.as_string())

  # Optional: Print a success message
  print("Email sent successfully!")


# Checking for watched users online, and making sure their status has changed since the last time the script ran
for friend in friends:
    for watched in config['watched']:
        if datetime.datetime.fromtimestamp(friend['presence']['updatedAt']) > datetime.datetime.fromisoformat(config['lastcheck']):
          if watched['type']=="name":
            if friend['name']==watched['value']:
              if friend['presence']['state']=="ONLINE":
                print(friend['name'],"is watched and is online!")
                if config['email']['enabled']:
                  mailsendonline(friend['name'], friend['presence']['game']['name'], datetime.datetime.fromtimestamp(friend['presence']['updatedAt']))
              else:
                print(friend['name'],"is watched but isn't online.")
          elif watched['type']=="id":
            if friend['id']==watched['value']:
              if friend['presence']['state']=="ONLINE":
                print(friend['name'],"is watched and is online!")
              else:
                print(friend['name'],"is watched but isn't online.")
        else:
          print(friend['name'],"'s status hasn't changed since the script last ran, ignoring. Last change: ",datetime.datetime.fromtimestamp(friend['presence']['updatedAt']).strftime("%b %d, %Y at %I:%M %p"),sep="")
config['lastcheck'] = datetime.datetime.now().isoformat()

if config['email']['enabled']:
  if config['email']['sendtest']:
    print("Email enabled with sendtest flag set, sending a test email!")
    hashtagnumber=random.randint(1000,9999)
    mailsendonline("Player#"+str(hashtagnumber), "TestGame", datetime.datetime.now())
    config['email']['sendtest']=False

with open(configpath, 'w') as outfile:
    yaml.dump(config, outfile, default_flow_style=False)

I expected the script to finish without any errors, and an email to appear in my inbox.

What happened was an exception:

Traceback (most recent call last):
  File "/home/jaherron/code/python/switchfriendwatch.py", line 89, in <module>
    mailsendonline("Player#"+str(hashtagnumber), "TestGame", datetime.datetime.now())
  File "/home/jaherron/code/python/switchfriendwatch.py", line 57, in mailsendonline
    mailsender.sendmail(config['email']['sendfrom'], config['email']['sendto'], message.as_string())
  File "/usr/lib/python3.11/smtplib.py", line 901, in sendmail
    raise SMTPRecipientsRefused(senderrs)
smtplib.SMTPRecipientsRefused: {'[My personal email]': (554, b'5.7.1 <[My personal email]>: Recipient address rejected: Access denied')}

New contributor

LittleBit is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật