【问题标题】:Sending email in python (MIMEmultipart)在 python (MIMEmultipart) 中发送电子邮件
【发布时间】:2023-03-27 18:26:01
【问题描述】:

我应该如何发送文本格式和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()

【问题讨论】:

  • 向我们展示您的代码!您尝试了什么,您期望什么,您在哪里遇到问题?
  • @DavidCain 我已经更新了正文。我的问题出在 MIMEMultipart([MIMEText(msg, 'text'),MIMEtext(html,'html')])

标签: python python-3.x email mime smtplib


【解决方案1】:

您需要将消息创建为

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 ------------

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

【讨论】:

    【解决方案2】:

    在你的“与”:

    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(table) 就可以介于两者之间。我对你的问题是什么感到困惑(很多编辑),但如果我没记错你的 fl1(tempt1.txt) 没有任何数据,你只是“读取”(r) 文本文件但没有什么都不写。我还建议您将 'tmp1=temp_message('temp1.txt')' 放入您的 'def temp_message(filename)' 以避免混淆。

    【讨论】:

    • 这不是我的问题。我的问题是我应该如何使用 MIMEmultipart 发送文本对象和 html 对象。我在问题中明确提到了它。我已经粘贴了@DavidCain 要求的代码
    猜你喜欢
    • 2016-02-19
    • 1970-01-01
    • 2023-01-19
    • 2022-10-13
    • 2012-12-28
    • 2018-01-25
    • 2018-06-09
    • 2012-06-02
    • 2016-12-14
    相关资源
    最近更新 更多