'Issues with smtplib sending mails

I tried following a youtube video on how to use smtplib to send emails, however whenever I try to send anything it gives me this error.

in alert_mail
    msg.set_content(body)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/email/message.py", line 1162, in set_content
    super().set_content(*args, **kw)
TypeError: super(type, obj): obj must be an instance or subtype of type

I really don't know why as I followed the video very closely, only changing the Gmail credentials and passwords to my own test accounts.


import smtplib
from email.message import EmailMessage

def alert_mail(subject, body, to):
    msg = EmailMessage
    msg.set_content(body)
    msg["subject"] = subject
    msg["to"] = to

    user = "[email protected]"
    msg["from"] = user
    password = #2 way encription password would be here, but thats not the issue 

    server = smtplib.SMTP("smtp.gmail.com", 587)
    server.starttls()
    server.login(user,password)
    server.send_message(msg)

    server.quit()

alert_mail("Hey","Hey this is my first com method" , "[email protected]") # sends email to itself, doesn't work even when some different address is entred

Any advice will be appreciated!

The video: https://www.youtube.com/watch?v=B1IsCbXp0uE



Solution 1:[1]

You should add an opening and closing parenthesis to the msg = EmailMessage line, remember that EmailMessage is an object, so you must use the correct syntax for creating one. This code below should work:

server = smtplib.SMTP(GMAIL_SERVER, GMAIL_PORT)
server.starttls()

server.login(EMAIL_SOURCE, PWD_SOURCE)
msg = EmailMessage()
msg['From'] = EMAIL_SOURCE
msg['To'] = TO_EMAIL
msg['Subject'] = YOUR_SUBJECT
msg.set_content(bodyOfMail)

server.send_message(msg)

del msg
server.quit()

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1