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

Vin*_*ula 5 python email mime smtplib python-3.x

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

MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])
Run Code Online (Sandbox Code Playgroud)

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

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()
Run Code Online (Sandbox Code Playgroud)

sna*_*erb 8

您需要将消息创建为

MIMEMultiPart('alternative') 
Run Code Online (Sandbox Code Playgroud)

然后附加两个 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())
Run Code Online (Sandbox Code Playgroud)

已收到*

>>> 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())
Run Code Online (Sandbox Code Playgroud)
$  python -m smtpd -n -c DebuggingServer localhost:1025
Run Code Online (Sandbox Code Playgroud)

重新设计的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)
Run Code Online (Sandbox Code Playgroud)

输出:

---------- 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 ------------
Run Code Online (Sandbox Code Playgroud)

*smtpd包自 Python 3.9 起已被弃用。建议替换第三方aiosmtpd软件包。等效的命令是python -m aiosmtpd -n -l localhost:1025


Iba*_*iii 0

在你的“与”处:

def temp_message(filename): 
   with open(filename,'r') as fl1:
      l2=fl1.read()
Run Code Online (Sandbox Code Playgroud)

将其更改为:

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)
Run Code Online (Sandbox Code Playgroud)

您可以将文本变量的“问候”部分分开,这样您的 html(table) 就可以位于两者之间。我对你的问题是什么感到困惑(大量编辑),但如果我没有弄错的话,你的 fl1(tempt1.txt) 没有任何数据,你只“读取”(r) 文本文件,但没有什么都不写。我还建议您将 'tmp1=temp_message('temp1.txt')' 放在 'def temp_message(filename)' 中以避免混淆。