pythonpython-3.xsendmailsmtplibemail-client

smtplib unrecognised keyword 'subject'


I want to send an email by smtplib but it give me error

    server.send_message(user_name, to, message, subject=subject)
TypeError: send_message() got an unexpected keyword argument 'subject'

This code

    import smtplib
    user_name = 'my@gmail.com'
    password = '*******'
    to = ['my@gmail.com', 'other_email@gmail.com']
    subject = 'Theme'
    message = 'Test message'
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(user_name, password)
    server.send_message(user_name, to, message, subject=subject)
    server.close()

I try delete subject from code but it give me new error

      File "C:\\lib\smtplib.py", line 939, in send_message
        resent = msg.get_all('Resent-Date')
    AttributeError: 'str' object has no attribute 'get_all'

How i can fix this?


Solution

  • You need to use sendmail() instead of send_message()

    import smtplib
    user_name = 'my@gmail.com'
    password = '*******'
    to = ['my@gmail.com', 'other_email@gmail.com']
    subject = 'Theme'
    message = 'Test message'
    email_message = 'Subject: {}\n\n{}'.format(subject, message) 
    server = smtplib.SMTP_SSL('smtp.gmail.com', 465)
    server.ehlo()
    server.login(user_name, password)
    server.send_message(user_name, to, email_message)
    server.close()
    

    Ref:

    1. Python smtplib send_message() failing, returning AttributeError: 'str' object has no attribute 'get_all'
    2. Python: "subject" not shown when sending email using smtplib module