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

问题描述 投票:1回答:2

我应该如何在同一个机构中发送包含文本格式和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='[email protected]'
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()
python python-3.x email mime smtplib
2个回答
1
投票

您需要将消息创建为

MIMEMultiPart('alternative') 

然后附上两个MIMEText部分。

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

>>> msg = MIMEMultipart('alternative')
>>> msg['Subject'] = 'Hello'
>>> msg['To'] = '[email protected]'
>>> msg['From'] = '[email protected]'

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

>>> s.sendmail('[email protected]', '[email protected]', msg.as_string())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 's' is not defined
>>> s = smtplib.SMTP('localhost:1025')
>>> s.sendmail('[email protected]', '[email protected]', 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: [email protected]
From: [email protected]
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 ------------

重新设计的电子邮件包(Python 3.6+)可用于发送相同的消息,如下所示:

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

输出:

---------- MESSAGE FOLLOWS ----------
Subject: Hello
To: [email protected]
From: [email protected]
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 ------------

0
投票

在'与':

def temp_message(filename): 
   with open(filename,'r') as fl1:
      l2=fl1.read()

将其更改为:

def temp_message(filename):
   filename = temp_message('temp1.txt') #changed tmp1 to filename
   with open(filename, 'w+', encoding='utf-8') as fl1:
      fl1.write(text)
      fl1.write(html)
      fl1.write(regards)

您可以拆分文本变量的“问候”部分,以便您的html(表格)可以在两者之间。我很困惑你的问题是什么(很多编辑)但是如果我没弄错你的fl1(tempt1.txt)没有任何数据你只是'读'(r)文本文件但是没有什么都写不出来。我还建议您将'tmp1 = temp_message('temp1.txt')'放在'def temp_message(filename)'中以避免混淆。

© www.soinside.com 2019 - 2024. All rights reserved.