使用 Python 发送电子邮件时,msg["Subject"] 变量的行为不正常
Sending email with Python, the msg["Subject"] variable doesn't behave as it should
我用 Python 发送电子邮件,但是 msg["Subject"] 变量填充了电子邮件的正文而不是主题框,而变量 body 没有填充任何内容...
其他都没问题,就是想不通为什么主体是body,body是空的?
我错过了什么?
代码如下:
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()
screenshot of the inbox
您的消息很好,但实际上您没有发送;您只发送主题。
server.sendmail(msg['From'], msg['To'], msg['Subject'])
你的意思显然是
server.sendmail(msg['From'], msg['To'], text)
但是,您可能应该更新代码以改用现代 Python 3.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()
我用 Python 发送电子邮件,但是 msg["Subject"] 变量填充了电子邮件的正文而不是主题框,而变量 body 没有填充任何内容...
其他都没问题,就是想不通为什么主体是body,body是空的? 我错过了什么?
代码如下:
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()
screenshot of the inbox
您的消息很好,但实际上您没有发送;您只发送主题。
server.sendmail(msg['From'], msg['To'], msg['Subject'])
你的意思显然是
server.sendmail(msg['From'], msg['To'], text)
但是,您可能应该更新代码以改用现代 Python 3.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()