Home » Python » I get AttributeError while sending Email with Python-Exceptionshub

I get AttributeError while sending Email with Python-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am trying to send an email with Python. But I’m having a bug.
This is my code:

import smtplib


def sendmail(subject, body):
    smtp = smtplib.SMTP("smtp.gmail.com", 587)
    smtp.ehlo()
    smtp.starttls()
    smtp.login("[email protected]", PASSWORD)
    message_body = f"Subject:{subject}\n\n{body}"
    smtp.sendmail("[email protected]", "[email protected]", message_body)
    smtp.quit()

sendmail("test subject", "test body")

I however get the below bug:
AttributeError: ‘int’ object has no attribute ‘encode’

How to&Answers:

Try this :

smtp.sendmail(sender, recipient, message_body.as_string())

Answer:

from documentation

msg may be a string containing characters in the ASCII range, or a byte string. A string is encoded to bytes using the ascii codec, and lone \r and \n characters are converted to \r\n characters. A byte string is not modified.

  smtp.sendmail(sender, recipient, str(message_body))