首页 > 解决方案 > 我正在使用 SMTPLib 向 gmail 帐户发送电子邮件

问题描述

我有两条消息。一条是 HTML 消息,另一条是简单的纯文本消息。我将它们都附加到 MIMEMultipart 变量(tmessage)但是当电子邮件发送时,我只能看到第二条附加消息我的收件箱。我不知道为什么......这是我的代码

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
host='smtp.gmail.com'
port=587
message="<h1>Hey i have received a 3rd  email message using Python</h1>"
userName='teaching807@gmail.com'
password='teaching807299'
connection = smtplib.SMTP(host,port)

connection.ehlo()
connection.starttls()
_from=userName
_to=userName
connection.login(userName,password)

tmessage = MIMEMultipart("alternative")
tmessage['Subject']="Html Message"
tmessage['From']=_from
tmessage['To']=_to
plain_message = "This is a plain message"
html_message="""<html><body><h1>Students Marks</h1><p>These are the students 
Marks</p></body></html>"""
msg1=MIMEText(html_message,'html')
msg2=MIMEText(plain_message,'plain')
tmessage.attach(msg1)
tmessage.attach(msg2)

connection.sendmail(_from,_to,tmessage.as_string())
connection.quit()

在收件箱中只能看到 msg2

标签: pythonpython-3.xsmtpsmtplib

解决方案


尝试从 tmessage 中删除“替代”,它在 Outlook 中对我有用。

tmessage = MIMEMultipart()

推荐阅读