使用 Python 发送电子邮件时,msg["Subject"] 变量的行为不符合预期



我用Python发送电子邮件,但msg[quot;Subject"]变量填充电子邮件正文,而不是主题框,变量正文什么都不填充。。。

其他一切都很好,但我不明白为什么主体是身体,而身体是空的?我错过了什么?

这是代码:

from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
msg = MIMEMultipart()
msg['From'] = "myemail@gmail.com"
msg['To'] = 'anemail@hotmail.com'
msg['Subject'] = "for next delivery, please supply"
body = Merged_Dp_Ind_str
msg.attach(MIMEText(body, 'plain'))
text = msg.as_string()
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('username@gmail.com', 'password1')
server.sendmail(msg['From'], msg['To'], msg['Subject'])
server.quit()

收件箱的屏幕截图

您的消息很好,但实际上您并没有发送消息;您只是在发送主题。

server.sendmail(msg['From'], msg['To'], msg['Subject'])

你显然是指

server.sendmail(msg['From'], msg['To'], text)

但是,您可能应该更新代码,转而使用现代的Python3.6+API。

格式化和发送信息的正确现代方式有点像

import smtplib
from email.message import EmailMessage
msg = EmailMessage()
msg['From'] = "myemail@gmail.com"
msg['To'] = 'anemail@hotmail.com'
msg['Subject'] = "for next delivery, please supply"
msg.set_content(Merged_Dp_Ind_str)
with smtplib.SMTP('smtp.gmail.com', 587) as server:
server.starttls()
server.login('username@gmail.com', 'password1')
server.send_message(msg)
server.quit()

最新更新