使用Python smtplib和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:一个bytes-like object是必需的,而不是'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")

最新更新