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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了在python中发送电子邮件(MIMEmultipart)相关的知识,希望对你有一定的参考价值。

我应该如何在同一个机构中发送包含文本格式和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('
')[0].split()[0])
              email.append(i.split('
')[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.sendmail('a@example.com', 'b@example.com', 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('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 ------------

重新设计的电子邮件包(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 ------------
另一答案

在'与':

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)'中以避免混淆。

以上是关于在python中发送电子邮件(MIMEmultipart)的主要内容,如果未能解决你的问题,请参考以下文章

有没有办法在没有 Windows 询问“你想如何打开这个文件”的情况下在 python 中发送电子邮件?

有没有一种在事先不知道文件类型的情况下使用 SMTP 在 python 中发送电子邮件附件的快速方法?

检查在 CakePHP 中发送电子邮件是不是成功/失败?

如何在android中发送电子邮件[重复]

如何在 VC++ 中发送电子邮件?

sh 在shell中发送电子邮件