python - 在Python中发送电子邮件(MIMEmultipart)

标签 python python-3.x email mime smtplib

如何在同一正文中发送文本格式和 html 格式的电子邮件? MIMEmultipart有什么用?

MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])

我能够使用此功能收到一封电子邮件,但正文为空白

PS:我正在尝试发送文本并在同一正文中附加表格。我不想将表格作为附件发送。

html = """
  <html>
   <head>
    <style> 
     table, th, td {{ border: 1px solid black; border-collapse: collapse; }} th, td {{ padding: 5px; }}
    </style>
   </head>
   <body><p>Hello, Friend This data is from a data frame.</p>
    <p>Here is your data:</p>
    {table}
    <p>Regards,</p>
    <p>Me</p>
   </body>
  </html> """

text = """
Hello, Friend.

Here is your data:

{table}

Regards,

Me"""
text = text.format(table=tabulate(df, headers=list(df.columns), tablefmt="grid"))
html = html.format(table=tabulate(df, headers=list(df.columns), tablefmt="html"))
if(df['date'][0].year==1900 and df['date'][0].month==datetime.date.today().month and df['date'][0].day==datetime.date.today().day):
a2=smtplib.SMTP(host='smtp-mail.outlook.com', port=587)
a2.starttls()
myadd='abc@gmail.com'
passwd=getpass.getpass(prompt='Password: ')
try :

    a2.login(myadd,passwd)
except Exception :
    print("login unsuccessful")
def get_contacts(filename):
    name=[]
    email=[]
    with open('email.txt','r') as fl:
         l=fl.readlines()
         print(l)
         print(type(l))
         for i in l:
          try: 
              name.append(i.split('\n')[0].split()[0])
              email.append(i.split('\n')[0].split()[1]) 
          except Exception:
              break
         fl.close()
    return (name,email)
def temp_message(filename):
    with open(filename,'r') as fl1:
        l2=fl1.read()
    return(Template(l2))
name,email=get_contacts('email.txt')    
tmp1=temp_message('temp1.txt')   
for name,eml in zip(name,email):
    msg=MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
    message=tmp1.substitute(USER_NAME=name.title())
    print(message)
    msg['FROM']=myadd
    msg['TO']=eml
    msg['Subject']="This is TEST"
    msg.attach(MIMEText(message, 'plain')) 
    #       msg.set_payload([MIMEText(message, 'plain'),MIMEText(html, 'html')])
    # send the message via the server set up earlier.
    a2.send_message(msg)
    del msg
    a2.quit()

最佳答案

您需要将消息创建为

MIMEMultiPart('alternative') 

然后附加两个 MIMEText 部分。

>>> text = 'Hello World'
>>> html = '<p>Hello World</p>'

>>> msg = MIMEMultipart('alternative')
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'

>>> msg.attach(MIMEText(text, 'plain'))
>>> msg.attach(MIMEText(html, 'html'))

>>> s = smtplib.SMTP('localhost:1025')
>>> s.sendmail('a@example.com', 'b@example.com', msg.as_string())

已收到*:

$  python -m smtpd -n -c DebuggingServer localhost:1025
---------- MESSAGE FOLLOWS ----------
Content-Type: multipart/alternative; boundary="===============2742770895617986609=="
MIME-Version: 1.0
Subject: Hello
To: a@example.com
From: b@example.com
X-Peer: 127.0.0.1

--===============2742770895617986609==
Content-Type: text/plain; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

Hello World
--===============2742770895617986609==
Content-Type: text/html; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit

<p>Hello World</p>
--===============2742770895617986609==--
------------ END MESSAGE ------------

重做的email包(Python 3.6+)可用于发送与此相同的消息(这应该是现代代码中的首选方法):

>>> from email.message import EmailMessage
>>> msg = EmailMessage()
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = 'a@example.com'
>>> msg['From'] = 'b@example.com'
>>> msg.set_content(text)
>>> msg.add_alternative(html, subtype='html')
>>> s.send_message(msg)

输出:

---------- MESSAGE FOLLOWS ----------
Subject: Hello
To: a@example.com
From: b@example.com
MIME-Version: 1.0
Content-Type: multipart/alternative;
 boundary="===============1374158239299927384=="
X-Peer: 127.0.0.1

--===============1374158239299927384==
Content-Type: text/plain; charset="utf-8"
Content-Transfer-Encoding: 7bit

Hello World

--===============1374158239299927384==
Content-Type: text/html; charset="utf-8"                                                                                            
Content-Transfer-Encoding: 7bit                                                                                                     
MIME-Version: 1.0                                                                                                                   
                                                                                                                                    
<p>Hello World</p>                                                                                                                  
                                                                                                                                    
--===============1374158239299927384==--                                                                                            
------------ END MESSAGE ------------
<小时/>

* smtpd自 Python 3.9 起,该包已被弃用。第三方aiosmtpd包装是推荐的替代品。等效命令是 python -m aiosmtpd -n -l localhost:1025

关于python - 在Python中发送电子邮件(MIMEmultipart),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55036268/

相关文章:

Python ArgParse Subparsers 并链接到正确的函数

python - Django : How to add/remove/update translation phrases (in po files) in django admin area?

python - AWS EB 客户端不支持的区域设置

python - 将列表字典转换为字典中列表中元素的所有组合的字典列表的最Pythonic方法?

security - 可以更改为 : field in email header?

email - 如何在电子邮件中使用 Hudson "Parameterized Build"值

python - 无法使用 docker-compose up 运行服务器

python - 如何处理从 except block 引发的异常链

html - 如何使表格数据在电子邮件中响应

python - 根据存储在 DataFrame 列中的 R、G、B 在 plotly 3D 散点图中设置标记颜色