Search code examples
python-3.xemailsmtplib

from_addr = email.utils.getaddresses([from_addr])[0][1] , error while sending the email using python


Getting below error while sending the email using python, do I need to create object?

import smtplib
from email.message import EmailMessage

email = EmailMessage()
email['from']: 'xxxxx@gmail.com'
email['to']: "xxxxx@gmail.com"
email['subject']: 'Hey Buddy Python'

email.set_content("Learning python")

with smtplib.SMTP(host="smtp.gmail.com", port="587") as smtp:
    smtp.ehlo()
    smtp.starttls()
    smtp.login("xxxx@gmail.com", "xxxx")
    smtp.send_message(email)   

Output of the program:

Traceback (most recent call last):
  File "C:/Users/xxxxx/Desktop/PYTHON/PyCharm/Email/SendEmail.py", line 15, in <module>
    smtp.send_message(email)
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 940, in send_message
    from_addr = email.utils.getaddresses([from_addr])[0][1]
  File "C:\Users\xxxxx\AppData\Local\Programs\Python\Python38-32\lib\email\utils.py", line 112, in getaddresses
    all = COMMASPACE.join(fieldvalues)
TypeError: sequence item 0: expected str instance, NoneType found

Process finished with exit code 1


Solution

  • The error you are getting NoneType instead of string is because you are not assigning the values to the email dictionary as seen in the documentation.

    More specifically, here:

    email['from']: 'xxxxx@gmail.com'
    email['to']: "xxxxx@gmail.com"
    email['subject']: 'Hey Buddy Python'
    

    Instead of : you should use the assign operator, =.

    Try with:

    email['from'] = 'xxxxx@gmail.com'
    email['to'] = "xxxxx@gmail.com"
    email['subject'] ='Hey Buddy Python'