Prevent "Sender domain not allowed" error when sending SMTP email in Flask application

129 Views Asked by At

I'm trying to build a Flask application that can send SMTP emails. I figured out how to use the SMTPlib library to send emails:

from smtplib import SMTP_SSL, SMTP

sender = "[email protected]"
receivers = ["[email protected]"]

message = """From: Ray Drost <[email protected]>
To: Raymon Drost <[email protected]>
Subject: SMTP e-mail test

This is a test e-mail message.
"""

smtpObj = SMTP_SSL(host="smtp.dreamhost.com", port=465)
smtpObj.login("[email protected]", "password censored ;)")
smtpObj.sendmail(sender, receivers, message)
print("Successfully sent email")

However, when I insert this same code into a simple flask application, I get the following error when using Postman to send a POST request to the application:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/app.py", line 2190, in wsgi_app
    response = self.full_dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/app.py", line 1486, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/app.py", line 1484, in full_dispatch_request
    rv = self.dispatch_request()
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/flask/app.py", line 1469, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "/Users/raymondrost/VSCode-Projects/coop-hour-tracker/Backend/API/api.py", line 31, in hourlogging
    smtpObj.sendmail(sender, receivers, message)
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/smtplib.py", line 908, in sendmail
    raise SMTPDataError(code, resp)
smtplib.SMTPDataError: (550, b'5.7.1 Sender domain not allowed. Please read: http://dhurl.org/20b D07')
127.0.0.1 - - [30/Aug/2023 13:25:56] "POST /hourlogging HTTP/1.1" 500 -

From what I can tell, this error is supposed to prevent one from spoofing a domain in an email, however that is not what I am doing here.

Here's the Flask application for context:

from flask import Flask, request, jsonify
from smtplib import SMTP_SSL, SMTP

# Flask API
api = Flask(__name__)

# Hour Logging Endpoint
@api.route('/hourlogging', methods=['POST'])
def hourlogging():
    # Process incoming data
    data = request.json
    try:
        testString = data["test"]
    except:
        print("Error getting data from json")

    sender = "[email protected]"
    receivers = ["[email protected]"]

    message = f"""From: Ray Drost <[email protected]>
    To: Raymon Drost <[email protected]>
    Subject: SMTP e-mail test

    This is a test e-mail message.
    """

    smtpObj = SMTP_SSL(host="smtp.dreamhost.com", port=465)
    smtpObj.login("[email protected]", "password censored ;)")
    smtpObj.sendmail(sender, receivers, message)
    print("Successfully sent email")

    # Return a response
    responseData = {"response": "Email Sent!"}
    return jsonify(responseData)

if __name__ == '__main__':
    api.run()

I've tried contacting Dreamhost (my email provider) support, and they are stumped. I have also tried using Brevo's (formerly Sendinblue) free SMTP plan. It appears to work properly, except emails from the Flask application simply don't arrive. I assume Brevo is refusing to send the emails for the same reason that Dreamhost is, I just don't know what the reason is.

2

There are 2 best solutions below

0
ray_drost On BEST ANSWER

I was using the wrong library for my needs. The problem was fixed by using the flask_mail library, instead of smtplib.

1
Hieu On

The email address in the header seems not right.

It's To: Raymon Drost <[email protected]> Was it a typo? Should it be [email protected]?