James Ronald
James Ronald

Reputation: 81

Getting unauthorized sender address when using SMTPLib Python

I have a very simple Python script that I wrote to send out emails automatically. Here is the code for it:

import smtplib

From = "[email protected]"
To = ["[email protected]"]

with smtplib.SMTP('smtp.gmx.com', 587) as smtp:
    smtp.ehlo()
    smtp.starttls() 
    smtp.ehlo()

    smtp.login("[email protected]", Password)

    Subject = "Test"
    Body = "TestingTheBesting"
    Message = f"{Subject}\n\n{Body}"

    smtp.sendmail(From, To, Message)

Whenever I run this code I get a very strange error telling me that this sender is an "unauthorized sender". Here is the error in full

File "test.py", line 17, in <module>    smtp.sendmail(From, To, Message)
  File "C:\Users\James\AppData\Local\Programs\Python\Python37-32\lib\smtplib.py", line 888, in sendmail888, in sendmail    raise SMTPDataError(code, resp)smtplib.SMTPDataError: (554, b'Transaction failed\nUnauthorized sender address.')

I've already enabled SMTP access in the GMX settings and I'm unsure about what else to do now to fix this issue.

Note: I know that the variable password has not been defined. This is because I intentionally removed it before posting, it's defined in my original code.

Upvotes: 4

Views: 3681

Answers (1)

M.Herzkamp
M.Herzkamp

Reputation: 225

GMX checks a messages header for a match between the "From" entry in the header and the actual sender. You provided a simple string as message, so there is no header, and hence the error by GMX. In order to fix this, you can use a message object from the email package.

import smtplib
from email.mime.text import MIMEText

Subject = "Test"
Body = "TestingTheBesting"
Message = f"{Subject}\n\n{Body}"
msg = MIMEText(Message)

msg['From'] = "[email protected]"
msg['To'] = ["[email protected]"]

with smtplib.SMTP('smtp.gmx.com', 587) as smtp:
    smtp.ehlo()
    smtp.starttls() 
    smtp.ehlo()

    smtp.login("[email protected]", Password)


    smtp.sendmail(msg['From'], msg['To'], msg)

Upvotes: 6

Related Questions