使用 Python smtplib 和 EmailMessage() 发送电子邮件

Sending emails using Python smtplib and EmailMessage()

我正在尝试使用 Python smtplib 和 EmailMessage() 通过电子邮件发送消息。

import smtplib
from email.message import EmailMessage
def email_alert(subject, body, to):
    msg = EmailMessage()
    msg.set_content(body)
    msg['subject'] = subject
    msg['to'] = to  
    user = 'username@gmail.com'
    msg['from'] = user
    password = 'app_password'
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(user, password)
    server.send(msg)
    server.quit()

email_alert("hey", "Hello world","another@mail.com")

但出现错误“TypeError: memoryview: 需要类似字节的对象,而不是 'EmailMessage'”。 代码有什么问题?我看到了这段代码起作用的视频。

工作代码

import smtplib
from email.message import EmailMessage
def email_alert(subject, body, to):
    msg = EmailMessage()
    msg.set_content(body)
    msg['subject'] = subject
    msg['to'] = to  
    user = 'username@gmail.com'
    msg['from'] = user
    password = 'app_password'
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(user, password)
    server.send_message(msg) # <- UPDATED
    server.quit()

email_alert("hey", "Hello world","another@mail.com")