Отправка электронной почты в Python (MIMEmultipart) - PullRequest
1 голос
/ 07 марта 2019

Как мне отправить электронное письмо с текстовым и 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()

Ответы [ 2 ]

2 голосов
/ 09 марта 2019

Вам необходимо создать сообщение как

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 ------------
0 голосов
/ 07 марта 2019

В вашем 'with':

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)

Вы можете просто разделить часть «regards» вашей текстовой переменной, чтобы ваш html (таблица)может быть между двумя.Я был сбит с толку относительно того, в чем ваша проблема (много правок), но если я не ошибаюсь, у вашего fl1 (tempt1.txt) нет никаких данных, которые вы только «прочитали» (r) в текстовом файле, но неничего не пиши.Я бы также порекомендовал вам поместить ваш 'tmp1 = temp_message (' temp1.txt ') "внутри вашего" def temp_message (filename) ", чтобы избежать путаницы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...